Compare commits

...
Author SHA1 Message Date
qiqi b48418c9ae feat(promptlib): 1.13.1 变量栏去掉 i 按钮 + 行间分割线(位置 2)
validate / validate (push) Canceled after 0s
用户裁定:按推荐方案 A,分割线落在「变量行与行之间」。

- 删掉每行右侧 i 圆按钮(它只做「强制展开」,与整行点击重复),连同 6 处
  .iwb-plp-vi CSS 规则;展开态由 caret 主色 + 整行 hover 反馈表达。
- 旧的 .iwb-plp-vitem dashed 行线被 dialog 作用域的 border:0 覆盖,编辑弹窗里
  实际一条线都没有;改为相邻兄弟选择器画 1px 实线,首行与末行之后都不画线。
  颜色按 design-tokens.md §3.11 的 --iwb-set-divider 公式(--iwb-border 55%)就地兜底:
  该变量只定义在 .iwb-settings-modal 作用域,插件面板不在其中,直接引用会掉到全强度边框。
- 标题下、展开字段前都不另画线,避免一屏三层线;尺寸全用 --iwb-space-* /
  --iwb-radius-control / --iwb-bw,无新增裸值。

测试:npm test 全过(新增 11 项静态断言);新增 tools/vars-panel-visual-check.mjs
(Chromium 亮/暗 19 项:i 按钮为 0、首行 0px 其余 1px、55% 淡线、暗色跟随、
hover、展开输入框、正文变量色块、连点 selectionStart 不漂移),两套截图已核对。
npm scripts 新增 test:promptlib / test:promptlib:visual,前者并入默认 npm test。
2026-11-25 13:52:36 +08:00
qiqi a923834595 feat(album): 1.1.2 看大图支持左右切换(整本相册循环浏览)
validate / validate (push) Canceled after 0s
宿主 props.onPreview 只收「已解析好的 URL 列表」:要切换就得开窗前把整本相册
的原图全部转成 dataURL(30 张 4K 图 = 几十上百 MB,还会卡主线程)。因此改成
插件自带全屏查看器,挂在 document.body:

- 点右下角放大镜 → 打开查看器,显示「N / 总数」+ 文件名;
- ← → / 左右按钮 / 滚轮切换,首尾循环,可跨分页浏览整本;
- 点图片外空白或 Esc 退出(沿用 1.1.1 定的交互);
- 只解码当前张 + 预取左右各一张(最多 3 张常驻),切页先用缩略图占位不闪黑;
- 键盘/滚轮在捕获阶段吃掉并关闭时摘掉监听,不影响宿主画布快捷键;
- 补回宿主预览原有的「复制(PNG)/ 下载」按钮,能力不回退。

测试:静态 harness 增 14 项断言;新增 album/tools/viewer-e2e.mjs(Chromium
真浏览器 22 项:开/关、键盘与按钮、循环、滚轮、单图、监听清理、复制下载)。
npm test 全过。
2026-11-25 10:32:10 +08:00
qiqi b00a59f4ba fix(album): 1.1.1 只看大图改回「点击放大镜 → 宿主全屏」
validate / validate (push) Canceled after 0s
1.1.0 的 hover 方案实测不可用:鼠标移到放大镜上时,节点内预览层
(z-index 9,铺满整个节点)把放大镜本身盖住了 —— 视觉上图标消失、
点击落在预览层上,用户感受就是「滑过去就点不了」。

因此删掉 A(hover 预览层 + showPreview/hidePreview + lastFull 缓存),
只保留 B:
- 点格子右下角放大镜 → props.onPreview 打开宿主全屏预览;
- 点图片外空白或 Esc → 宿主 ImagePreview 自己 onClose,自动退出。

顺带:放大镜显式 z-index:3(以后再加浮层也不会压住它)、
cell:focus-within 也显示放大镜、title 文案改成「点击空白处或按 Esc 关闭」。
harness 同步换成反向断言(hover 代码/CSS 必须不存在)。
2026-11-25 10:06:31 +08:00
qiqi 3eb8900b51 feat(album): 1.1.0 方形宫格 + 清除按钮 + 放大镜预览 + 修 5 个布局/翻页 bug
validate / validate (push) Canceled after 0s
用户提出的交互改造:
- 顶栏最右「清空」:一键清空(走撤销快照,⌘Z 可整体恢复;不删磁盘原文件)
- 删除右上角的批次角标「1」:顶栏「N 张 → M 个任务」已经说清楚,重复信息
- 选中线 2px → 1px(用户:太粗);失联虚线同步 1px
- 格子固定方形:aspect-ratio 1/1。此前高度由图片比例决定(4 张 16:9 会变 22px 细条),
  与 capacityOf() 按方形算的容量是两套账,最后一行常被裁
- 放大镜 A+B 方案:hover → 节点框内浮出大图(inset:0,pointer-events:none 不挡点击);
  点击 → 宿主 props.onPreview 全屏预览。删除按钮让到右上角避开

顺手修的实测 bug(都在 1.0.4 复现过):
- S/M/L 档位反了:{S:64, M:48, L:100} 里 M 比 S 小 ⇒ 中格每页 30 张比小格 20 张还多。
  现在 S/M/L = 64/80/104,300×470 下每页 20/12/4
- 容量常量与 CSS 对齐:GAP 5→4(CSS 用 --iwb-space-4)、TOOLS_H 27→25、HINT_H 24→28
- 跨页拖拽错位:pageStart 用 page × 格子数(含「+添加」格)⇒ 第 2 页拖到第 2 位实际插到全局第 13 位。
  改用 st.cap.capacity
- 删除任意页都跳回第 1 页(硬编码 page:0)⇒ 改为只做页数回圈
- 缩略图串味:key 曾是 fileRefOf(src) || name,固化后 src 无路径 ⇒ 同名文件共用缩略图。
  改 thumbKeyOf(f:/b:/c:/d: 前缀),且 localthumb 请求加 in-flight 去重
- img.src='' 触发对页面 URL 的空请求;空节点仍显示「全部 0 张一页展示」;
  网页版「文件夹」按钮 canReference() || true 恒真 ⇒ 点了没反应;addPaths 里 keep 死变量
- 缩略图预生成补进度(500 张导入时界面不再像卡死)

测试:新增 album/tools/harness.mjs(44 项,此前插件侧零测试),含「35 种节点尺寸 × 3 档 ×
有无提示行,算出的容量都装得进可视区」的几何不变量;根 package.json 加 npm test
2026-11-25 09:51:37 +08:00
qiqi 01253fceea fix(album): 1.0.4 节点 outKind 自愈(旧节点缺 outKind 时只能连中继)
validate / validate (push) Canceled after 0s
2026-11-25 08:44:34 +08:00
qiqi dd294a75cd fix(album): 1.0.3 高度稳定/文件夹导入/选中态刷新/边框 token
validate / validate (push) Canceled after 0s
2026-11-25 08:36:26 +08:00
qiqi 0ea25fcea2 chore(album): 移除无效的面板实验(宿主面板槽为白名单,插件无法新增)
validate / validate (push) Canceled after 0s
2026-11-25 08:22:25 +08:00
qiqi d43b1520dc fix(album): 点击处理读最新 node(连点模式开关失效)+ 可点击 span 挡 pointerdown(翻页/密度不响应)
validate / validate (push) Canceled after 0s
2026-11-25 07:34:27 +08:00
qiqi 37c7c4b666 fix(album): 样式改用 design-tokens(字号/间距/中性色),过插件主题与尺度双守卫 2026-11-25 07:15:42 +08:00
qiqi e97c9beb0d feat(album): 相册节点插件 v1.0.0——宫格自适应分页(随尺寸)+一图一任务/批量+仅本页参与+拖拽排序+本地文件引用/固化 2026-11-25 07:12:55 +08:00
qiqi 89841c4d4d feat(promptlib): v1.13.0 正文 {} 里放内容原文(改内容正文跟着改)+ 节点名宽 4 字、内容框 10 行
validate / validate (push) Canceled after 0s
- 用户裁定:变量「内容」就是正文 {…} 里的那段字 —— 改内容立刻改正文;名称只决定节点左栏显示,不动正文
- 占位符上限 24 → 60(KEY_MAX),5 处正则统一,避免「识别到但替换不到」把整段删掉
- 内容塞不进 {}(换行/超长)时保留原键 + 摘要提示,绝不硬塞(硬塞会让变量识别不到、sync 把内容清掉)
- 直接在正文里改 {…} 时,名称/说明继承过来(单删单增才判定为「改了这段」)
- 节点变量名列 76px → 56px(4 字),名称框提示同步 4 字
- 内容框最高 6 行(132px)→ 10 行(212px)
- 插入变量:选中原文直接作占位符;插入变量按钮不再被挤成两行

测试:harness / vars-editor-test / plp-vars-editor-check 全绿(新增 12 项断言)
2026-11-24 18:52:37 +08:00
qiqi 99269aa0ae feat(promptlib): v1.12.3 变量编辑器收敛为三字段,节点输入框默认空、空值用内容兜底
validate / validate (push) Canceled after 0s
用户要求:变量区不要功能性说明文案、不要占位符输入框,只留 名称/内容/说明;
内容框要是多行;节点里的变量输入框默认为空,不填说明时灰字展示「内容」文案。

编辑器
- 删顶部「名称只影响显示 · 内容可多行 · 与正文双向同步」、删橙色 tip(老数据占位符提示)、
  删底部「正文写作 {…};改占位符会同步替换正文。留空的内容不传给下游。」
- 删「占位符」输入项与 renameTo():key 不再给用户改(插入时自动生成,已有条目沿用正文原键)
- 内容框 rows=1 → rows=3,最高长到 132px 后框内滚动;min-height 30 → 66px
- 修测量时机:原先「append 之前」调 autoGrowArea,元素不在文档里 scrollHeight 读不到,
  高度被 min-height 兜成一行,长文案在框里被裁(用户截图里的现象)

节点
- 输入框值默认为空(不再回退 def);新建节点不再把 def 预填进 vars
- placeholder 取「说明 → 内容 → 填写 xx」:不填说明时灰字显示内容文案,与说明同一样式
- 空输入时输出用内容兜底:outputText 会把无值的 {key} 整段删掉,不兜底等于用户填的
  「内容」永远进不了提示词。vars 仍只存原始输入(空就是空,下次打开还是空)
- 「未填」提示改成只统计「既没填也没内容」的变量
- 空框按 placeholder 折行量高度(24 字内容提示需要 40px,原实高 30px,第二行看不见);
  变量集合没变时不再重建输入框,但就地同步 placeholder 文案并重测

真机验证抓到的 bug(已修)
- defOf 原先声明在 syncTplNode 内,scheduleUpdate 取不到 ⇒ ReferenceError: defOf is not defined,
  表现是「填了值写不回、清空也不回落」。改挂 st.defOf,两个函数共用。

验证
- 新增 tools/plp-vars-editor-check.mjs(真实 Chromium 挂面板 + 走「新建」弹窗 + 真实模板节点 render):
  13 项断言,含「三个输入项 / 内容框 3 行 84px / 无说明文案 / 节点默认为空 / placeholder 取内容 /
  填写值写进 vars / 清空后提示词回到内容兜底」
- harness 66 → 75 项;vars-editor-test 17 → 20 项
- 宿主 test:unit 全绿;scale-contract / token-lint / 渲染测试通过
2026-11-24 18:32:08 +08:00
qiqi 8f1f7ea7a7 fix(promptlib): v1.12.2 搜索框常驻(中文输入法能正常输入)+ 变量标签定宽 6 字
validate / validate (push) Canceled after 0s
用户报障:① 变量名长短不一,输入框左边缘不齐;② 搜索框打不进中文。

② 的根因(有对照实验)
- 搜索框写在 render() 里,而 render() 第一件事是 clear(fixed) ⇒ 每敲一个键都把搜索框
  自身销毁重建。中文输入法在组合态(compositionstart → compositionend)被打断。
- 用 Playwright 跑旧版实测:组合态中搜框 connected=false、卡片被拼音过滤成 0 条;
  走 CDP Input.imeSetComposition 真实输入法通道时 value 变成 "shui水"(拼音与汉字拼接),
  正是用户看到的「打不进中文」。
修法
- 搜索框只创建一次(ensureSearchRow),render() 只清其余节点、把搜索行留在首位;
- compositionstart/end 之外不重排:组合态只记 query(拼音不是搜索词),上屏后过滤一次;
- 结果重排走 120ms 防抖(顺带解决逐键全量重建卡顿);清空搜索后焦点回到搜索框;
- dispose 清掉防抖定时器。

① 变量标签列定宽 76px(12px 字号 × 6 字 + 4px 余量)
- 此前 flex:0 0 auto,宽度跟着名称长短变 ⇒ 每行 textarea 左边缘错位;定宽后四行实测同为 508.66px
- 6 字名称完整显示,超 6 字省略号截断(完整名称在 title)
- 名称框 placeholder 改为「变量名称(节点上最多显示 6 字)」

验证
- 新增 tools/plp-search-ime-check.mjs:真实 Chromium 挂载面板,合成组合事件 + CDP 输入法双路,
  10 项断言(含「组合态不按拼音过滤」「光标不跳末尾」);同一脚本跑 HEAD 旧版失败 6 项 ⇒ 对照成立
- harness 61 → 66 项;宿主 plugin-promptlib-render-test 的搜索等待按 120ms 防抖改 200ms
- 宿主 test:unit 全绿;scale-contract / token-lint 通过
2026-11-24 18:16:10 +08:00
qiqi 48d86f3e0f fix(promptlib): v1.12.1 变量标签列定宽 6 字,输入框左边缘对齐
validate / validate (push) Canceled after 0s
用户截图:三个变量名「风格 / 女生 / 价格与利益点」长短不一,标签列 flex:0 0 auto
跟着文字宽度走 ⇒ 每行 textarea 左边缘不齐,看着散。

- .iwb-plp-nk 改 flex:0 0 76px + width/max-width 76px(12px 字号 × 6 字 + 4px 余量),
  定宽后四行输入框左边缘实测同为 508.66px;6 字名称完整显示,超 6 字省略号截断,
  完整名称仍在 title 里
- 名称框 placeholder 改为「变量名称(节点上最多显示 6 字)」,说明为什么长名会被省略
- harness 61 项(新增 2 项:定宽不被改回 auto、提示文案在位)
2026-11-24 18:11:16 +08:00
qiqi 4092eb5437 feat(promptlib): v1.12.0 变量四字段分离 + 节点多行变量框
validate / validate (push) Canceled after 0s
用户报障:长文案挤在变量名框里显示不下;节点里变量输入框是 24px 单行,
一整句只能在一条线上左右拖动看。根因是「插入变量」把选中的整段文字
(截 24 字)当成了占位符,内容没有地方放。

字段分工(定型)
- key(占位符,≤12 字、正文 {…} 用)
- label(变量名称,只管节点左栏显示,可空)
- def(内容,可多行)
- desc(说明,同时是节点输入框 placeholder)

编辑面板
- 收起态一行:名称 + 「内容 N 字 · 有说明」;点开才出现名称/内容/说明/占位符,允许多开
- 内容用 textarea(rows=1,1→4 行自动增高,超了框内滚动)
- 修掉 label 被吃掉的旧 bug:norm/sync/list 三处都带 label 与 def
  (此前编辑器保存一次,用户填的名称就没了)
- 老数据(占位符本身是正文原句):原句借到内容框展示,不改存档不动正文;
  改名时若内容为空先把原句收进 def,避免替换正文后原句丢失

插入变量
- 短词(≤12 字且无标点空白)沿用旧习惯:直接当占位符
- 长句:占位符自动起名「变量N」,原文进该变量的内容,展开并聚焦名称框(名称一律手填)

节点侧
- 变量输入框 input → textarea:rows=1 起,随内容长高到 96px 后框内滚动
- 左栏标签 max-width 96px 单行省略(不再固定 64px 截断、也不再裂成两行)
- 新建模板节点把 def 预填进 data.vars(否则输入框全空,只剩灰字提示)
- 拦 pointerdown:宿主可交互白名单不含 textarea(ui-node-card.js:281),
  不拦会「按住文本框拖选文字 = 拖动整个节点」
- 只在内容溢出时拦 wheel,否则保留画布滚轮缩放

测试
- harness 31→59 项(新增 15 项静态断言)
- 新增 tools/vars-editor-test.mjs(17 项行为测试,vm + DOM stub 跑真实编辑器源码):
  覆盖 label/def 保存、sync 不吃字段、老长 key 借内容、改名同步正文且不丢内容
2026-11-24 18:00:27 +08:00
qiqi 7c348e60c7 feat(gallery): v1.7.0 订阅宿主图库变化 + 插入尺寸档一致
validate / validate (push) Canceled after 0s
- 订阅 ctx.gallery.onChanged(新宿主能力):宿主归档/删除/恢复后 260ms 防抖重拉。
  此前只有「面板重新可见且距上次拉取 >5s」一个入口,而生成时面板一直可见 ⇒ 出图后
  图库不刷新(用户报障「生成了但图库没图」)。
- 格子「插入」补 insertK:此前忽略「设置 → 插入尺寸」档,与右键菜单/顶部「插入」不一致。
- 插入(右键/格子/顶部/批量拖入)补「插入中…」状态:取本地原图 + 压缩 + 落盘要时间,无反馈像没反应。
- 删除改为等宿主删完再 load():固定 setTimeout 250ms 会拉到未删完的清单,格子里出现「图片已丢失」。
- 兼容旧宿主:ctx.gallery.onChanged 不存在时静默跳过(退回可见性刷新 + 手动刷新)。
- 说明:搜索框在 v1.6.1 已按用户意见移除,本次不恢复。
2026-11-24 17:12:34 +08:00
qiqi deac7513fd feat(promptlib): v1.11.0 封面文件治理(保存即落文件 + 孤儿封面回收)
validate / validate (push) Canceled after 0s
- 抽 coverFileName():迁移/保存/导入四处的内联 djb2 哈希合并为一处,
  同一张图不会再存出两个文件(文件名 = 内容哈希,天然去重)
- 上传封面、保存词条、另存副本都先 ensureCoverFile() 落成文件,
  数据 JSON 里只留 { img: 文件名 };失败退回内联 base64(宁可不省体积,不丢封面)
- 新增 plpGcCoverFiles():回收不再被任何词条引用的封面文件
  安全线:数据不是从插件 JSON 读来的不删 / keep 为空不删 / 只删图片扩展名 /
  刚 put 未引用的名字进 pending 跳过 / 两张词条共用一个封面天然保留
- 触发:面板加载后延迟 4s 自动一次 + 删词条后一次 + 设置页「清理未引用封面」手动入口
- 设置页占用行改成「封面 N 张 / 文件 M 个」,两者不等即说明有孤儿
- 样式散值归零(4px→6px、margin 13px→12px),插件尺度棘轮基线保持 0
- harness 31 → 44 项(含 plpGcCoverFiles 行为断言:只删未引用 / 空集合不删 / 无 FS 跳过)
2026-11-24 15:14:25 +08:00
qiqi f0568342b1 feat(promptlib): v1.10.1 移除分享封面开关 + 详情底部分享/插入组间竖向分割线
validate / validate (push) Canceled after 0s
2026-11-24 14:25:02 +08:00
qiqi b9c110709d feat(promptlib): v1.10.0 文本分享/文件分享双路径 + 顶部文件/文本/新建 + 右键去分组分类 + 设置去导入入口
validate / validate (push) Canceled after 0s
2026-11-24 14:19:00 +08:00
qiqi c9bb3b09f3 feat(promptlib): v1.9.3 编辑区变量浅主色底色(只画色块不改输入)+ 横向滚动同步
validate / validate (push) Canceled after 0s
2026-11-24 13:35:53 +08:00
qiqi 4f4e64a989 feat(promptlib): v1.9.2 分享设置增加「附带封面图片」开关(默认开)
validate / validate (push) Canceled after 0s
2026-11-24 13:25:09 +08:00
qiqi 9959096ab3 fix(sticky): v1.0.7 自定义调色后色板自动收起
validate / validate (push) Canceled after 0s
2026-11-24 11:54:55 +08:00
qiqi e7f8e68909 fix(sticky): v1.0.6 文本缩回时外框高度自动回缩
validate / validate (push) Canceled after 0s
2026-11-24 11:52:14 +08:00
qiqi eb6880b11f fix(sticky): v1.0.5 圆角对齐宿主节点(node-radius - 1px)
validate / validate (push) Canceled after 0s
2026-11-24 11:49:05 +08:00
qiqi ba9a4448e4 fix(sticky): v1.0.4 textarea rows=1 去掉默认预留一行高度
validate / validate (push) Canceled after 0s
2026-11-24 11:45:14 +08:00
qiqi 5ff3318fb9 fix(sticky): v1.0.3 外框高度贴字(覆盖宿主 minHeight)+ 调色点右上
validate / validate (push) Canceled after 0s
2026-11-24 11:37:24 +08:00
qiqi 8c6ed43078 fix(sticky): v1.0.2 便签贴字(textarea 内容自适应)+ 色板跟随调色按钮
validate / validate (push) Canceled after 0s
2026-11-24 11:20:19 +08:00
qiqi 9ed18827a8 feat(promptlib): 1.9.1 面板顶部加「导入词例」与「+ 新建词例」
validate / validate (push) Canceled after 0s
2026-11-24 11:16:22 +08:00
qiqi 352cac6031 fix(sticky): v1.0.1 修拖动漏底/字号无上限/双击编辑(对齐宿主文本节点机制)
validate / validate (push) Canceled after 0s
2026-11-24 10:59:56 +08:00
qiqi 2d2738f3a1 feat(promptlib,gallery): promptlib 1.9.0 单条分享/导入分享;gallery 1.6.12 打开本地目录
validate / validate (push) Canceled after 0s
2026-11-24 10:39:25 +08:00
qiqi 27a641903c feat(sticky): 便利贴插件 v1.0.0 —— 多行文本+字号/粗细+8色背景,纯标注不连线
validate / validate (push) Canceled after 0s
2026-11-24 10:37:11 +08:00
qiqi 89c2dca424 fix(gallery): 1.6.11 每次重排重量宽度 + 缩略图 eager,修复面板显隐后不刷新
validate / validate (push) Canceled after 0s
2026-11-24 07:09:27 +08:00
qiqi b8718d6810 refactor(gallery,grouplib): 尺寸收进 token 闭集(1.6.10 / 1.0.5)
validate / validate (push) Canceled after 0s
2026-11-23 20:15:45 +08:00
qiqi 17fd3be13b fix(promptlib): 1.8.24 放置框 z-index 改用 --iwb-z-anchor(过 token-lint)
validate / validate (push) Canceled after 0s
2026-11-23 20:13:23 +08:00
qiqi e7d54cb0a8 refactor(promptlib): 1.8.23 尺寸迁移到 token 闭集(字号/圆角/间距),棘轮基线下调
validate / validate (push) Canceled after 0s
2026-11-23 20:12:16 +08:00
qiqi 1aba7a0c94 refactor(promptlib): 1.8.22 颜色迁移到插件 token(视觉保持 1.8.8 基线)+ 映射表
validate / validate (push) Canceled after 0s
2026-11-23 20:06:05 +08:00
qiqi 4fc4e469c2 feat(batch-export): 1.2.2 状态色跟随宿主主题 + 去掉纯蓝主按钮
validate / validate (push) Canceled after 0s
- 成功/错误/进度条/hover 改为 var(--iwb-ok|err|brand-text|text|layer, 私有值兜底),暗色自动变亮
- 主按钮从实心蓝 #2f6fed + 白字改为 text/layer 成对反相(亮 9.51 / 暗 14.10 对比),与项目全灰阶约束一致
- 热按钮改绿描边 + 绿字 + 14% 绿底,避免暗色亮绿底压白字
- 状态文字照 design-tokens.md §3 的 iwb-mk-badge 范例用 color-mix 往 text 压 18%
- 配套宿主 M6:亮色 --iwb-ok/err/warn 调深,状态色文字对比 2.13 → 5.38
2026-11-23 18:18:51 +08:00
qiqi 7cb4379e41 feat(plugins): 主题契约收口 —— 私有皮肤自声明 + 状态点跟随主题
validate / validate (push) Canceled after 0s
- image-annotate 1.20.7 / image-vectorize 0.6.1: manifest 声明 skin:'private'(宿主据此放行整套调色板,代价是不得引用宿主颜色 token)
- browser 1.7.1: 连接关闭状态点 #888780 → var(--iwb-text-dim)
- batch-export 1.2.1: 看片台白底加 /*iwb:content*/ 内容色标记
- 配套宿主 M4-B6(image-workbench-desktop v3.26.49):文件级豁免清零
2026-11-23 17:11:22 +08:00
qiqi f5a5712628 fix(promptlib): 1.8.21 恢复编辑正文可见(覆盖 transparent)
validate / validate (push) Canceled after 0s
2026-11-23 10:09:42 +08:00
qiqi 56962dca0b fix(promptlib): 1.8.20 编辑区停用高亮层,正文由 textarea 渲染,插入点与光标严格一致
validate / validate (push) Canceled after 0s
2026-11-23 10:08:05 +08:00
qiqi e9da55cced fix(promptlib): 1.8.19 编辑高亮变量不加粗,修复插入点逐次左移;样式仍 1.8.8 基线
validate / validate (push) Canceled after 0s
2026-11-23 10:07:41 +08:00
qiqi ced0482ed8 fix(promptlib): 1.8.18 插入变量改回确定性 splice,重复插入不再偏移;样式保持 1.8.8 基线
validate / validate (push) Canceled after 0s
2026-11-23 10:04:56 +08:00
qiqi 3a563950ba docs(promptlib): 固定样式基线 v1.8.8 与插入变量规则 2026-11-23 09:56:22 +08:00
qiqi eec5ab6c9b fix(promptlib): 1.8.17 样式回退到 1.8.8 基线;插入变量改用原生 insertText 并忽略 blur 选区
validate / validate (push) Canceled after 0s
2026-11-23 09:54:20 +08:00
qiqi 385a73c111 revert+fix(promptlib): 1.8.16 回退到 1.8.9 样式基线,插入变量改用原生 insertText 精确落点
validate / validate (push) Canceled after 0s
2026-11-23 09:51:20 +08:00
qiqi 89d3cfc619 style(promptlib): 1.8.15 左侧名称/分组输入框补描边
validate / validate (push) Canceled after 0s
2026-11-23 09:48:55 +08:00
qiqi ae9b07fe91 style(promptlib): 1.8.14 重写编辑弹窗 flex 高度链,修复正文压扁/错位
validate / validate (push) Canceled after 0s
2026-11-23 09:48:43 +08:00
qiqi cb56ffdfda style(promptlib): 1.8.13 详情变量恢复黑色加粗,无底色
validate / validate (push) Canceled after 0s
2026-11-23 09:47:37 +08:00
qiqi 34ba29f04f style(promptlib): 1.8.12 输入框/名称/标签/正文底色统一纯白,i 展开态灰色
validate / validate (push) Canceled after 0s
2026-11-23 09:47:24 +08:00
qiqi 65ea7cd64c style(promptlib): 1.8.11 输入框底色改近白、i 展开态改灰,修复灰块低对比
validate / validate (push) Canceled after 0s
2026-11-23 09:47:08 +08:00
qiqi 51cfa56f26 fix(promptlib): 1.8.10 修复颜色 token 误用(详情变量不可见/输入框低对比/焦点样式失效)
validate / validate (push) Canceled after 0s
2026-11-23 09:46:22 +08:00
qiqi 9f148f06ef fix(promptlib): 1.8.9 插入变量严格落在光标位置(保留选区,toolbar 不抢焦点)
validate / validate (push) Canceled after 0s
2026-11-23 09:40:31 +08:00
qiqi 178b36c477 style(promptlib): 1.8.8 详情标题14px/元信息行分割线/封面底色更浅
validate / validate (push) Canceled after 0s
2026-11-22 23:51:05 +08:00
qiqi d8f1e89e74 style(promptlib): 1.8.7 详情标题缩小/元信息分割线与行高/去标签底色/加冒号
validate / validate (push) Canceled after 0s
2026-11-22 23:48:22 +08:00
qiqi b914c76df4 fix(promptlib): 1.8.6 修复 outputText 正则换行损坏(1.8.5 语法错误)
validate / validate (push) Canceled after 0s
2026-11-22 23:44:36 +08:00
qiqi 98ed47673f feat(promptlib): 1.8.5 输出文本剔除未填变量占位(仅编辑时展示)
validate / validate (push) Canceled after 0s
2026-11-22 23:44:13 +08:00
qiqi 1ceb241b89 fix(promptlib): 1.8.4 详情右卡片纵向拉伸,正文滚动生效
validate / validate (push) Canceled after 0s
2026-11-22 23:39:45 +08:00
qiqi efe58236e1 fix(promptlib): 1.8.3 详情左卡片撑满等距;正文滚动恢复不被遮挡
validate / validate (push) Canceled after 0s
2026-11-22 23:38:10 +08:00
qiqi dbf3adfc77 style(promptlib): 1.8.2 详情左右卡片化+分割线+内容标题
validate / validate (push) Canceled after 0s
2026-11-22 23:36:28 +08:00
qiqi b10a3bf28d style(promptlib): 1.8.1 详情元信息带标题左对齐;标签加号对齐修复
validate / validate (push) Canceled after 0s
2026-11-22 23:35:11 +08:00
qiqi 09730c7ee9 feat(promptlib): 1.8.0 详情标题/分组/标签移至封面下方;编辑标签改为输入+加号 chips
validate / validate (push) Canceled after 0s
2026-11-22 23:32:15 +08:00
qiqi 4c6ef7098c fix(promptlib): 1.7.9 详情正文独立滚动,长文挤压底部修复
validate / validate (push) Canceled after 0s
2026-11-22 23:29:05 +08:00
qiqi 7a15511582 fix(promptlib): 1.7.8 插入变量后立即重绘高亮层
validate / validate (push) Canceled after 0s
2026-11-22 23:25:48 +08:00
qiqi 1fa7a8d24a fix(promptlib): 1.7.7 对齐编辑区字体度量,修复光标与选区错位
validate / validate (push) Canceled after 0s
2026-11-22 23:20:27 +08:00
qiqi 2c96524f6b fix(promptlib): 1.7.6 封面 contain 完整展示 + 编辑取消返回详情
validate / validate (push) Canceled after 0s
2026-11-22 23:17:41 +08:00
qiqi 2c2ad434bc style(promptlib): 1.7.5 编辑封面裁切在框内 + 详情封面放大 264px
validate / validate (push) Canceled after 0s
2026-11-22 23:16:00 +08:00
qiqi a3d289da21 fix(promptlib): 1.7.4 还原标题栏拖动;名称框可拖高;插入变量按钮改黑
validate / validate (push) Canceled after 0s
2026-11-22 23:14:07 +08:00
qiqi 79d631ce86 fix(promptlib): 1.7.3 正文高亮层可见性修复 + 标题栏下沿可拖高度
validate / validate (push) Canceled after 0s
2026-11-22 23:10:53 +08:00
qiqi 98826f9ee3 style(promptlib): 1.7.2 正文变量黑粗高亮/说明灰按钮/说明透明背景/详情变量黑粗
validate / validate (push) Canceled after 0s
2026-11-22 23:08:34 +08:00
qiqi 89eb3053c6 style(promptlib): 1.7.1 编辑面板视觉精修(亮色输入框/去多余框/细分隔线)
validate / validate (push) Canceled after 0s
2026-11-22 23:02:03 +08:00
qiqi aca659615e feat(promptlib): 1.7.0 编辑面板三栏可拖宽/变量单输入双向同步/说明多开/详情封面放大与变量高亮
validate / validate (push) Canceled after 0s
2026-11-22 22:58:15 +08:00
qiqi f97fbf6330 style(promptlib): 1.6.23 放置指示改为灰色小方框
validate / validate (push) Canceled after 0s
2026-11-22 22:33:28 +08:00
qiqi 64db27155a fix(promptlib): 1.6.22 放置指示改为半透明矩形框(左上角对齐落点)
validate / validate (push) Canceled after 0s
2026-11-22 22:31:47 +08:00
qiqi e02b5f4345 feat(promptlib): 1.6.21 详情插入改为两步放置(幽灵跟随,点击落点)
validate / validate (push) Canceled after 0s
2026-11-22 22:28:22 +08:00
qiqi 59403a4867 fix(promptlib): 1.6.20 插入封面改走 canvasWrite.createImageNode
validate / validate (push) Canceled after 0s
2026-11-22 22:24:52 +08:00
qiqi 5d4bdf5400 fix(promptlib): 1.6.19 拖拽落点=鼠标位置(节点左上角,对齐风格库)
validate / validate (push) Canceled after 0s
2026-11-22 22:22:05 +08:00
qiqi 4539668c06 release(promptlib): 1.6.18 落点居中/封面插入/拖拽禁选
validate / validate (push) Canceled after 0s
2026-11-22 22:20:37 +08:00
qiqi d151df3512 fix(promptlib): 1.6.17 拖拽屏蔽文本选择 + 落点居中 + 详情插入居中 2026-11-22 22:09:32 +08:00
qiqi ca1764b2c4 fix(promptlib): 1.6.16 插入走 canvasWrite + canvas.screenToWorld(宿主 API 拆分)
validate / validate (push) Canceled after 0s
2026-11-22 21:20:13 +08:00
qiqi c9d06b8388 feat(promptlib): 1.6.15 指针拖拽插入(对齐风格库,绕开原生 DnD 焦点残留) 2026-11-22 21:09:24 +08:00
qiqi 4f92ec12dc fix(promptlib): 1.6.14 未选中时变量输入不拦截指针 + 修复 props 引用崩溃 2026-11-22 20:41:19 +08:00
qiqi d190cc6433 feat(promptlib): 1.6.12 双击查看详情 + 编辑保存返回详情 2026-11-22 20:34:31 +08:00
qiqi c917d267eb fix(promptlib): 1.6.11 封面卡高度恢复(背景层回到普通流) 2026-11-22 20:25:52 +08:00
qiqi 99649b0ecd fix(promptlib): 1.6.10 悬停缩放改内层背景层 + 封面不拦截指针(修闪烁与封面卡难点选) 2026-11-22 20:22:25 +08:00
qiqi 675ccf5016 feat(promptlib): 1.6.9 拖拽虚拟卡片预览(封面+名称+节点类型) 2026-11-22 20:17:59 +08:00
qiqi f65f037cff fix(promptlib): 1.6.8 去掉长按武装(首次拖拽失败根因)+ 卡片悬停放大/按下边框 2026-11-22 20:13:05 +08:00
qiqi b2c3dd18d0 feat(promptlib): 1.6.7 节点 outKind=prompt(可直连生图等)+ 长按拖拽反馈 2026-11-22 20:09:06 +08:00
qiqi a4f69164dd release(promptlib): 1.6.6 变量/节点封面/设置页/备份/插入变量
validate / validate (push) Canceled after 0s
2026-11-22 19:56:04 +08:00
qiqi 06fa7f0a9b fix(promptlib): 1.6.6 节点封面/参考图统一走 fileApi(迁移后 {img} 可解析) 2026-11-22 19:54:05 +08:00
qiqi 928ffa0de0 fix(promptlib): 自包含样式主题契约修正 2026-11-22 19:50:52 +08:00
qiqi d42cc3a409 feat(promptlib): 1.6.5 节点封面走 fileApi + 宿主基础样式作用域副本(CSS 自包含) 2026-11-22 19:48:49 +08:00
qiqi 00f03de106 feat(promptlib): 1.6.4 插入变量按钮 + 封面迁移失败可见 2026-11-22 19:40:45 +08:00
qiqi e6400b35c3 fix(promptlib): 移除遗留的 setBtn 引用(设置已并入宿主设置页) 2026-11-22 17:27:46 +08:00
qiqi 59ccc66de4 feat(promptlib): 1.6.0 设置改为宿主设置页内嵌(分组管理/数据备份/数据位置) 2026-11-22 17:26:20 +08:00
qiqi 8180607754 feat(promptlib): 1.5.12 设置页(分组管理/数据备份/数据位置),移除面板小图标 2026-11-22 17:24:18 +08:00
qiqi 501e46965a feat(promptlib): 1.5.9 数据备份(导出/导入 JSON,含封面与变量,默认合并去重) 2026-11-22 17:13:56 +08:00
qiqi 5c34856c6a fix(promptlib): 1.5.8 拖拽 payload 带 pluginId/nodeType(修未知节点类型) 2026-11-22 17:09:23 +08:00
qiqi 8b72967381 feat(promptlib): 1.5.7 拖拽按变量分流(有变量→模板节点)+ 去掉紫色角标 2026-11-22 17:05:05 +08:00
qiqi 2fb6372252 feat(promptlib): 1.5.6 模板节点参照风格节点(封面缩略图/变量行/参考图开关/未填提示,去掉正文预览) 2026-11-22 16:57:50 +08:00
qiqi 8078f6495e fix(promptlib): 1.5.5 变量/节点渲染改为模块作用域(修复 fillTpl/varsOf 未定义) 2026-11-22 16:52:56 +08:00
qiqi 013bb6ba13 fix(promptlib): 1.5.3 加载重试 + 编辑页封面异步绘制 + 点击异常提示 + 单一数据源 2026-11-22 16:47:14 +08:00
qiqi 5e09a587e2 wip(promptlib): 1.5.0 数据自持/变量/模板节点(封面迁移调试中) 2026-11-22 16:27:57 +08:00
qiqi aa4ec99c0b docs(ai-chat): 明确实验性/不上市场 + 补 manifest(开发者直装)
validate / validate (push) Canceled after 0s
2026-11-22 15:14:35 +08:00
qiqi a5081a81bb style(style-source): 1.3.3 颜色全部走 --iwb-* token
validate / validate (push) Canceled after 0s
2026-11-22 15:09:35 +08:00
qiqi 3e55a83169 fix(promptlib): 1.4.10 封面迁移阈值 150KB / 仅 PNG 触发
validate / validate (push) Canceled after 0s
2026-11-22 00:19:23 +08:00
qiqi c25144138d fix(promptlib): 1.4.9 PNG 封面重压
validate / validate (push) Canceled after 0s
2026-11-22 00:16:31 +08:00
qiqi 59b6393e8a fix(gallery): 缓存命中改用微任务绘制(同步挂载后立即出图)
validate / validate (push) Canceled after 0s
2026-11-22 00:07:52 +08:00
qiqi 930ca2b02a fix(gallery): 1.6.9 缩略图 Promise 共享 + 坏图快速失败
validate / validate (push) Canceled after 0s
2026-11-21 23:50:36 +08:00
qiqi b318bae3d2 fix(gallery): 1.6.9 缩略图 Promise 共享
validate / validate (push) Canceled after 0s
2026-11-21 23:48:14 +08:00
qiqi acbf31c26e fix(gallery): 1.6.7 可见后重测 + 延时重排
validate / validate (push) Canceled after 0s
2026-11-21 23:44:36 +08:00
qiqi c3eb72fb10 fix(gallery): 1.6.6 列宽铺满面板 + 量外层宽度
validate / validate (push) Canceled after 0s
2026-11-21 23:28:12 +08:00
qiqi c8ae61a3ed fix(gallery): 1.6.4 首屏宽度测量 + 边距收紧
validate / validate (push) Canceled after 0s
2026-11-21 23:23:23 +08:00
qiqi 3ea7c239ac style(promptlib): 1.4.8 面板底色透明(与图库一致)
validate / validate (push) Canceled after 0s
2026-11-21 23:12:24 +08:00
qiqi 344da1bb45 fix(promptlib): 1.4.7 恢复 .iwb-lib-cards 列规则
validate / validate (push) Canceled after 0s
2026-11-21 22:52:54 +08:00
qiqi f51626040c revert(promptlib): 1.4.6 = 1.4.0 内容(回退)
validate / validate (push) Canceled after 0s
2026-11-21 22:50:22 +08:00
qiqi 8523120f6c fix(promptlib): 1.4.5 nonce + 老 cover 解析
validate / validate (push) Canceled after 0s
2026-11-21 22:43:42 +08:00
qiqi 3d21bf6457 fix(promptlib): 1.4.2 内联样式,避免宿主样式未注入时排版错乱
validate / validate (push) Canceled after 0s
2026-11-21 22:21:14 +08:00
qiqi dfe08dcb3c feat(promptlib): 1.4.1 卡片键盘可达
validate / validate (push) Canceled after 0s
2026-11-21 22:17:47 +08:00
qiqi 87384f124d chore(promptlib): 1.4.0 删死代码 + 封面瘦身迁移
validate / validate (push) Canceled after 0s
2026-11-21 22:12:02 +08:00
qiqi 7e9d73d702 fix(promptlib): 1.3.5 无封面方形占位
validate / validate (push) Canceled after 0s
2026-11-21 22:01:47 +08:00
qiqi e8a15cca75 feat(promptlib): 1.3.4 瀑布流列表
validate / validate (push) Canceled after 0s
2026-11-21 21:56:11 +08:00
qiqi e00f211031 feat(promptlib): 1.3.3 封面任意比例(contain 显示)
validate / validate (push) Canceled after 0s
2026-11-21 21:49:08 +08:00
qiqi ebf277158b feat(promptlib): 1.3.2 详情插入封面图片
validate / validate (push) Canceled after 0s
2026-11-21 21:42:31 +08:00
qiqi b0258f9ab6 feat(promptlib): 1.3.1 详情页插入画布后关闭弹窗
validate / validate (push) Canceled after 0s
2026-11-21 21:34:00 +08:00
qiqi 59588ef4cc fix(promptlib): 1.3.0 封面缓存键 + 上传即时反馈
validate / validate (push) Canceled after 0s
2026-11-21 21:26:17 +08:00
qiqi b89b181173 fix(promptlib): 1.2.1 封面缓存修复 + 弹窗线框简化
validate / validate (push) Canceled after 0s
2026-11-21 19:45:51 +08:00
qiqi 57efde3eea feat(promptlib): 1.2.0 弹窗化详情/编辑(可拖动可缩放)+ 输入框柔化
validate / validate (push) Canceled after 0s
2026-11-21 19:36:54 +08:00
qiqi 8670619690 feat(promptlib): 1.1.0 封面网格/长文详情/宽编辑弹窗
validate / validate (push) Canceled after 0s
2026-11-21 19:14:22 +08:00
qiqi 2495c5bde7 feat(grouplib): 1.0.4 卡片交互态/空态/拖拽反馈;promptlib 1.0.2 卡片化
validate / validate (push) Canceled after 0s
2026-11-21 18:25:25 +08:00
qiqi 5da8f6d3f1 feat(promptlib): 分组胶囊改为适应面板宽度自动换行 v1.0.1
与节点组同一问题:宿主 .iwb-lib-chips 是 nowrap + .iwb-lib-chips-scroll 单行滚动(右侧渐隐),
分组多时靠后的分类看不见也点不到。
- 去掉滚动容器,胶囊行加 .iwb-plp-chips,自带 styles.css 用双类选择器改 flex-wrap: wrap
- +/⚙ 由「钉在滚动区右侧」改为随胶囊一起换行(与 grouplib 一致),归到 .iwb-plp-add
2026-11-20 17:37:40 +08:00
qiqi ceb97aecee feat(grouplib): 分类胶囊改为适应面板宽度自动换行 v1.0.3
- 宿主 .iwb-lib-chips 是 nowrap(配 .iwb-lib-chips-scroll 才单行滚动),分组多时右侧胶囊被裁掉看不见
- 去掉滚动容器,胶囊行加 .iwb-glp-chips,自带 styles.css 用双类选择器改 flex-wrap: wrap(不依赖样式注入顺序)
- 顺带修 1.0.2 的真 bug:分组名胶囊曾被 append 到外层容器、其余在滚动容器里,等于分组既拿不到滚动也被裁
- +/⚙ 归到 .iwb-glp-add,不参与压缩并与分组名稍作分隔
2026-11-20 17:28:59 +08:00
qiqi da0c3f35c2 feat(gallery): 图幅新增「极小」64px 档 v1.6.3
TILES 由 80/110/150/200 变为 64/80/110/150/200,默认仍为「中」110;
64px 时列宽上限 64(215px 面板约 3 列),列数仍按面板宽自适应。
2026-11-20 17:13:30 +08:00
qiqi 070a4818f9 fix(gallery): 图幅改为显示宽度上限(单列不再拉满面板),档位 80/110/150/200 v1.6.2 2026-11-20 15:02:31 +08:00
qiqi a487fd3d44 fix(gallery): 去掉搜索框(用户反馈无意义)v1.6.1 2026-11-20 14:56:39 +08:00
qiqi 61b279a2ca feat(gallery): 搜索 + 失败统计/全部重试 + 右键菜单 + 多选拖拽批量插入 v1.6.0 2026-11-20 14:20:41 +08:00
qiqi c7f619a36d feat(promptlib): 提示词库改为插件(搜索/分组/收藏/新建编辑/插入/复制/拖拽)v1.0.0 2026-11-20 13:42:09 +08:00
qiqi 43b02a3a1c fix(gallery 1.5.1): .iwb-hint 限定作用域,修设置页文案被居中;fix(grouplib 1.0.2): 分类胶囊改横向滚动容器,修被裁切 2026-11-20 13:31:53 +08:00
qiqi 7c7eff40ee fix(grouplib): 面板 mount 未注入 ctx 导致整块空白 + 空态/错误诊断 + 刷新按钮 v1.0.1 2026-11-20 13:28:13 +08:00
qiqi ca43f08f03 feat(grouplib): 节点组库改为插件(分组/改名/删除/拖入画布),数据仍由宿主 grouplib 能力持有 v1.0.0 2026-11-20 13:12:07 +08:00
qiqi 3dde0b15b4 feat(gallery): 自带 styles.css(无框图标/紧凑间距/设置浮层),样式不再依赖客户端发版 v1.5.0 2026-11-20 12:58:56 +08:00
qiqi 02fba5aef0 fix(gallery): 刷新/设置并入右侧工具组,修窄栏图标重叠 v1.4.2 2026-11-20 12:53:36 +08:00
qiqi 9b98eb1a7e feat(gallery): 底栏刷新/设置改用图标按钮,窄栏不再挤成竖排 v1.4.1 2026-11-20 12:50:32 +08:00
qiqi 758e76572f feat(gallery): 三个下拉收进「设置」浮层,底栏只留张数/刷新 v1.4.0 2026-11-20 12:45:44 +08:00
qiqi b904e9739e feat(gallery): 自动恢复(面板可见/窗口聚焦时重拉)+ 底部刷新按钮 + 坏图不留白块 v1.3.0 2026-11-20 12:18:56 +08:00
qiqi 70b50dc654 fix(gallery): 删除后先本地摘除再重拉,避免残留「图片已丢失」格子 v1.2.1 2026-11-20 12:13:11 +08:00
qiqi dccac9d88b fix(gallery): 缩略图失败自动重试 + 下载失败提示可重试 v1.2.0
- img 不再显示破图标与长 title:alt 置空、title 移到卡片;error 后自动重试 2 次
- 仍失败显示「缩略图加载失败(点击重试)」,点击重新拉取
- 下载:读 capability 返回的 failed[],底部状态位显示「N 张下载失败,可再点一次重试」
2026-11-20 12:07:46 +08:00
qiqi 6c3b21232c feat(gallery): 去掉标题、设定移到右侧底部横栏、下拉再窄 1/3、顶部去掉插入 v1.1.0 2026-11-20 12:01:02 +08:00
qiqi fa13eb5997 fix(gallery): 缩略图按异步处理(thumb 返回 Promise,之前当字符串 ⇒ 全部显示图片已丢失)v1.0.1 2026-11-20 11:46:42 +08:00
qiqi 21b1c70acb feat(gallery): 新增图库插件 1.0.0(宿主只保留 gallery 数据能力,界面全在插件)
- 头部:标题/计数/已选 + 全选/反选/下载/插入/删除 + 插入档/图幅/时间三个窄下拉
- 瀑布流列数按「面板宽 / 图幅」计算;单击/Shift 多选、双击预览、拖到画布
- 配置(插入档/图幅/时间)存 ctx.data;图片数据走 ctx.gallery(宿主持有)
2026-11-20 11:31:14 +08:00
qiqi df5361cf6e fix(browser): 面板回车提交路径也要记录最近访问(onUrl 不走 goTo) 2026-11-20 09:40:54 +08:00
qiqi 7119dcf356 feat(browser): 最近访问列表走 ctx.data(插件数据层首个真实用例)v1.7.0
- 地址栏挂 datalist,提交地址时记录最近 12 条(去重、新的在前)
- 数据存 ctx.data(桌面落 <资料目录>/plugin-data/browser.json),不塞进 settings
- manifest 声明 data: {schemaVersion:1, maxBytes:65536}
- 数据不可用时静默降级,不影响浏览
2026-11-20 09:39:37 +08:00
qiqi fe1d3fcaa6 feat(image-vectorize): 顶栏「取消」改「关闭」并按主色调取色;补同步全屏到源码 v0.6.0
- ui.js: 顶栏最右按钮 data-act=cancel 文本「取消」→「关闭」,加 class vz-btn-close(行为不变)
- ui.css: 新增 .vz-btn-close 用编辑器主色调 #33566f(.vz-seg 选中态同款)填充 + #eaf6ff 文字,与左边三颗灰色产出按钮区分;hover/active 提亮
- ⚠ 重要修正:0.5.0 的全屏改动当时只改了产物 src/index.js,源码 plugin/ui.css 没同步(仍是 92vw 居中卡片)—— 若将来 build 会回退。本次把全屏(100vw×100vh、去圆角/阴影/边框)补进 plugin/ui.css 源码 + 重新 build 产物,源码与产物一致。
- version 0.5.0→0.6.0(package.json,build 注入 banner)
- build image-vectorize 通过,validate 10/10
2026-11-19 15:01:23 +08:00
qiqi e5e1c25c24 feat(image-vectorize): 编辑器改全屏铺满(对齐标注),去灰边 v0.5.0
.vz-modal 由居中卡片 96vw×92vh(圆角+阴影,四周露出 .vz-root 半透明灰蒙层)改为 100vw×100vh 铺满、去圆角/阴影/边框,窄屏覆盖同步改全屏。视觉与标注 .iwb-editor-modal 统一。
两处 version 一致 0.4.2→0.5.0,validate 10/10。
未实测:全屏后内部布局(header/画布/参数面板)是否错位,需上架市场后客户端更新验证。
2026-11-19 14:13:49 +08:00
qiqi a1d0a8e980 feat(browser): 库面板浏览器默认缩放可配置(panelZoom,默认 60%)v1.6.0
新增设置项 panelZoom(type:number,default 60,范围 20-300):资源中心「浏览器」面板打开网页时的初始缩放。
- mount() panel 初始化读 ctx.settings.get('panelZoom') → setZoom(st, clampZoom(pz/100)),写 data-iwb-cwv-zoom,宿主 canvas-webview 下一帧按新值推 zoom。
- ctx.settings.onChange 订阅 panelZoom:改设置即时覆盖当前面板(D2=实时)。
- 只作用库面板(scope:panel),画布网页节点默认缩放不变(仍 zoom:1,跟画布缩放)。
- version 两处一致:package.json + src/index.js manifest = 1.6.0;validate 10/10 过。
宿主侧零改动(canvas-webview 已读 data-iwb-cwv-zoom,设置页已支持 type:number)。
2026-11-19 13:26:23 +08:00
qiqi 0cbfc15a60 feat(browser): 面板「↗」改为把当前页放到画布上;去掉书签条右侧的设置路径提示
validate / validate (push) Canceled after 0s
1. ↗ 的语义按场景分:
   - 面板里:调 canvasWrite.createNode('web', …) 在当前画布新建一个网页节点,
     带上当前网址与 traceable 标题,可选中的新节点直接出现在画布上;
   - 网页节点里:保持原样,开独立窗口(节点里的页面不好操作时甩出去)。
   - 建不出来(旧客户端没有 canvasWrite / 画布没打开)就退回独立窗口,保证点了有反应。
   manifest 增加 canvasWrite 能力;不需要它的宿主会走退路,不会报错。

2. 书签条右下角「书签在「设置 → 插件 → 应用内浏览器」里分组管理」不再显示(用户要求)。
   空分组时的「这个分组还没有书签」保留 —— 那是状态提示,不是设置指引。

harness +6 项:点击后建 web 节点并带 url、不带 paused、不再开独立窗口、
旧宿主(无 canvas)点 ↗ 不抛异常且退回独立窗口。共 85 项全过。
2026-11-19 09:36:34 +08:00
qiqi f52aeaa46e feat(browser): 书签支持分组、增删改与拖动排序(1.5.0)
validate / validate (push) Canceled after 0s
原来只有一条文本框「每行一个 名称|网址」,只能手写、不能分组。现在:

- 数据结构改成 {v:2, groups:[{id,name,items:[{id,title,url}]}]},存在 settings.bookmarks
  的 JSON 字符串里(settings 值会被整包写回配置,标量最稳)。旧文本格式读到就自动
  迁成「常用」一组,老用户不用重填。
- 设置页(宿主新增 type:'custom')渲染分组条 + 书签行:
  分组胶囊带条目数、+分组/重命名/删除分组(二次确认,3 秒复原)、
  每行 ⠿ 拖动排序 + 名称 + 地址 + ✕ 删除、底部 +添加书签。
- 面板书签区改两行:分组行(全部 · n / 组名 · n)+ 书签行,点分组只看该组;
  只有一个分组时分组行整条隐藏,不多占网页高度。
- 地址留空的行留在设置里(那是「+添加书签」还没填完的草稿),但不会出现在面板。

两个坑:
- 拖动不能用 setPointerCapture —— 手柄在拖动中会被 insertBefore 换位置,capture
  在 WKWebView 上会跟着丢,拖到第二行就收不到事件。改成 document 上挂
  pointermove/pointerup,并用 moved 标志避免「点一下松手」也写盘。
- 输入框用 change(失焦/回车)而不是 input:宿主每次 commit 都重渲染整页,
  逐字符提交会把焦点冲掉。

harness:+「书签数据层」「面板分组切换」「单分组隐藏分组条」三组断言(78 项全过),
书签条查找改深度查找(现在包在 .iwb-browser-bmwrap 里)。
2026-11-19 09:14:54 +08:00
qiqi f7e2b786c7 feat(browser)!: 1.4.0 工具栏重做(缩放设定框 + 加载态 + 站内地址回填)
validate / validate (push) Canceled after 0s
配合宿主 v3.25.29(修好了「网页压住地址栏」与「内容不跟画布缩放」)。

- 工具栏:← → ⟳(加载中变「停止」)、地址栏、− 100% + 缩放设定框(可直接输入
  百分比,双击回 100%,25%~300%)、↗ 独立窗口打开、✕ 关闭网页(paused,⟳ 可恢复)
- 状态回传:监听宿主 document 上的 iwb-cwv-state,站内跳转后地址栏跟随真实地址
- 标题为空时自动用站点名,多个网页节点并排时分得清
- 图标改 SVG(测试桩没有 createElementNS 时退回文字图标)
- 节点默认 560x520,数据新增 zoom / paused
- render 挂 dispose,销毁时清掉事件路由表引用
- harness 62 项(新增缩放框/暂停恢复/状态回填/禁用态断言)
2026-11-19 07:14:06 +08:00
qiqi 2dc43b701f feat(browser)!: 1.3.0 恢复画布内网页节点(宿主 v3.25.28 修好「一动就白」)
validate / validate (push) Canceled after 0s
v3.25.27 曾整体下线该功能,判断错了。用户补充的现象(不动有内容、移动/缩放节点/
缩放画布后消失、只有某个缩放比例能看)指向宿主侧两个策略:
「单帧变化 >18px 就藏」和「交集 <64x48 就隐藏」。宿主已改(v3.25.28),插件恢复:

- 重新注册节点类型 web(520x480,无端口),capabilities 加回 nodeTypes
- 版本提示文案改成「需要 v3.25.28 及以上」
- harness 恢复节点断言(40 项),版本断言改为与 package.json 比对
- README 补一段说明:为什么 v3.25.24~26 会白、v3.25.28 改了什么
2026-11-19 06:45:25 +08:00
qiqi 5b2e49f052 refactor(browser)!: 1.2.0 下线画布内网页节点
validate / validate (push) Canceled after 0s
宿主 v3.25.27 撤掉了 canvas_webview_* 六条命令与 src/canvas-webview.js 位置同步引擎,
插件同步移除节点类型 web 与 nodeTypes 能力,只保留独立窗口浏览器。

原因(宿主侧 CHANGELOG v3.25.27 有完整记录):原生子 webview 在画布上要每帧反推位置、
靠挪出窗口模拟隐藏,且 macOS 上 hide/show 会静默失效、get_webview_window 会永久失效,
维护成本远超收益。

- capabilities: ['panels'](不再申请 nodeTypes)
- 删除 cwv 样式/renderWebNode/buildWebNode/bindWebNode(约 130 行)
- harness 同步删掉节点断言(26 项),版本断言改为与 package.json 比对,不再写死版本号
2026-11-19 00:12:08 +08:00
qiqi 57070a5720 feat(browser): 1.1.1 画布内网页节点(原生子 webview 锚点 + 地址栏控制)
validate / validate (push) Canceled after 0s
节点体只画地址栏和一个空锚点(data-iwb-cwv),网页本体由宿主的
src/canvas-webview.js 用 Tauri Window::add_child 创建的原生子 webview
精确盖在锚点上;节点跟着画布平移缩放。

- ctx.nodes.register 声明 width=520 / height=480
- 检测 window.IWBCanvasWebview,旧客户端给出明确版本提示
- tools/harness.mjs 40 项断言
2026-11-18 23:56:08 +08:00
qiqi 01391ee8b8 feat(browser): 应用内浏览器插件 1.0.0(面板地址栏 + 书签 + 后退/刷新/关闭)
validate / validate (push) Canceled after 0s
- 调宿主 open_browser_window / browser_control / browser_state,打开独立窗口不占画布。
- 面板顶部状态行显示当前网址与开关状态,按钮随状态启用。
- 每次 mount 先解绑上一次 settings.onChange 订阅(修切 tab 累积监听)。
- 无命令的旧宿主降级 window.open(系统浏览器)。tools/harness.mjs 25 项断言。
2026-11-18 22:40:33 +08:00
qiqi 0c42831cab docs: README 补快速开始与排障速查,状态文案对齐桌面客户端 2026-11-18 17:12:49 +08:00
qiqi c78da782a2 docs: 全面桌面化——去网页版 KV/部署叙事,改为桌面市场分发链路
validate / validate (push) Canceled after 0s
2026-11-18 17:10:53 +08:00
qiqi 35133d4c23 fix(annotate): 反白被误写成「增强」逻辑(补丁插错位置),重写 invert 并补齐 boost 兜底 v1.20.6 2026-11-17 21:05:26 +08:00
qiqi f8998faef0 fix(annotate): 反白像素公式纠正为 r+(255-2r)*k(旧公式 k=0 变纯白,导致颜色发艳)v1.20.5 2026-11-17 20:53:11 +08:00
qiqi bab181b12f fix(annotate): ctx.filter 改为功能性探测(WKWebView 属性存在但被忽略);像素读取失败走混合模式兜底;效果失败弹提示 v1.20.4 2026-11-17 20:48:38 +08:00
qiqi a74978d09a fix(annotate): 快速效果在 WKWebView 下全部失效(canvas ctx.filter 不支持)→ 加逐像素/缩放兜底 v1.20.3 2026-11-17 20:37:57 +08:00
qiqi 136fdf58f5 fix(annotate): 指针状态自愈(丢 mouseup 自动收笔 + 失焦/取消复位)v1.20.2 2026-11-17 17:24:21 +08:00
qiqi 329b4638c3 fix(annotate): 丢 mouseup 后自愈收笔 + 失焦/指针取消复位交互状态(修「画一次后画布不响应」)v1.20.2 2026-11-17 17:21:24 +08:00
qiqi 9dd3b0985b fix(style-source): 1.3.2 样式表改在脚本执行时注入 + 缩略图内联兜底(修「样式节点裸奔、图片铺满」)
validate / validate (push) Canceled after 0s
根因不是样式写错,是注入点太晚 + 上一版没真正上线:
1.3.0 只在 mount() 注入 ⇒ 从存档直接进画布(面板从不 mount)时节点体无样式,
< img class=iwb-ssn-thumb > 按原图尺寸铺满节点。1.3.1 把注入提前到 setup,
但发布时 KV 只换了字节、清单仍指 1.3.0,线上等于没修。

- ensureStyle() 在 CSS 常量之后立刻调用(脚本执行即注入),setup / renderStyleNode 继续兜底
- 缩略图加行内 width/height:56px + object-fit:cover 兜底,样式表失效也不会撑爆节点
- harness 新增闸门:宿主 stub 不调 setup 时 #iwb-ss-style 必须已存在
2026-11-14 13:13:13 +08:00
qiqi e015b26e0b fix(style-source): 1.3.1 CSS 在激活时注入(不开面板也不会出现缩略图铺满节点);补冷启动回归用例 2026-11-14 13:04:09 +08:00
qiqi 9b09c7606f test(style-source): 新增测试站端到端验收脚本(15 项),README 补三层测试与守卫式发布命令 2026-11-14 08:52:15 +08:00
qiqi b136217e2f test(style-source): e2e-real 跟上 v1.3.0(按钮改文案定位、总数不写死 310、补样式节点断言) 2026-11-14 08:38:02 +08:00
qiqi 20118eec0b feat(style-source): v1.3.0 新增「样式节点」——带变量表单、可继续连线的插件节点
详情页底部新增第三颗「样式节点」按钮(点一下自动找位 / 按住拖到画布松手),
原「插入参考图 / 插入提示词」行为一个字没改。

节点 data 契约:variant/styleId/name/code/outKind:'prompt'/promptTpl/varMeta/vars/
text/preview/refOn/refUrl/refName/collapsed —— 随画布存档,撤销备份跨设备都白拿。

五条硬约束(README 已写死):
1. 不传 run ⇒ 节点上没有生成按钮,出图交给下游生图节点(用户明确要求)
2. 变量全部露出、单行 28px(label 左 / 输入右),24 个变量也不到 800px;「收起」按钮可折
3. vars 与 text 同一次 onUpdate 写回;输入 300ms 防抖 + 失焦立即提交
4. ports 只出不入(宿主兜底分支会用上游顶掉自己的文本)
5. render(node, props, host) 往 host 里画并做增量同步,正在编辑的输入框不覆盖

harness 78 → 88 项(含「二次渲染复用同一批 DOM」这条防失焦回归);
顺手修掉一处既有偶发:拖拽用例的 justDragged 400ms 窗口会吞掉紧随其后的 click。
2026-11-14 08:35:25 +08:00
qiqi a8512ba777 feat(image-annotate): v1.20.1 吸管+色值整组右对齐(不再随 tab 数量浮动),色值框 124→96 2026-11-10 08:48:25 +08:00
qiqi d16e68bfa9 feat(image-annotate): v1.20.0 去色下移为常用色第一格 + 头部控件全部定宽(不再被 flex 抵掉)
- 去色:头部按钮 → 常用色网格第一格(20px 同尺寸、虚线圆 + 斜圈)
- 不可用上下文(文字色 / 未闭合钢笔)不再 hidden,改 disabled + 42% 不透明度,title 说明原因
- 头部定宽:色值框 flex 0 0 124px(原 0 1 150)、加「底色」tab 后色值框与图钉位置不动
- 常用色 16 → 15(亮紫让位,深紫保留),去色 + 15 = 8 列 2 行
- 删掉 :has(...[hidden]) 隐藏竖线的规则,头部结构变纯静态
- harness 231 项 / 真站 e2e 40 项
2026-11-10 07:54:32 +08:00
qiqi 00a2699e89 docs(image-annotate): README 补 v1.19.0 章节 2026-11-10 07:33:04 +08:00
qiqi fdfb4ed603 feat(image-annotate): v1.19.0 右栏调色模块删除 + 头部一行(吸管/色值/去色/图钉)+ 16 常用色 8 列 + 最近两排 2026-11-10 07:31:25 +08:00
qiqi 929b7ec2a1 test(image-annotate): 真站 e2e 断言撤销组在工具条最右 2026-11-10 07:01:02 +08:00
qiqi a94e5be954 feat(image-annotate): v1.18.0 色板可钉住 + 右列竖向收窄 + 撤销组搬进工具条最右 2026-11-10 06:59:04 +08:00
qiqi b6d10339f6 test(image-vectorize): 真站 e2e 断言顶栏顺序与统一配色 2026-11-09 23:47:46 +08:00
qiqi 89c8e0a1d8 feat(image-vectorize): v0.4.2 顶栏「保存为节点」与「取消」互换,四颗按钮统一描边配色 2026-11-09 23:41:50 +08:00
qiqi 9bbb94b789 docs(image-vectorize): 更新交互说明(滚轮一律缩放 / 左键与中键拖动平移) 2026-11-09 19:19:50 +08:00
qiqi 6284f84d29 fix(image-vectorize): v0.4.1 滚轮无条件缩放(不再按 deltaY 整数猜设备)+ 拖动收尾/中键平移 2026-11-09 19:16:52 +08:00
qiqi b299895730 test(image-vectorize): 真站 e2e 补缩放/平移断言(比换算比例,不比容器宽度) 2026-11-09 18:41:36 +08:00
qiqi 32363d8c9b feat(image-vectorize): v0.4.0 预览支持缩放/平移(滚轮锚点缩放、拖动、双击复位) 2026-11-09 18:39:21 +08:00
qiqi 352a7668d7 fix(image-annotate): v1.17.1 无描边后再点无填充会把对象弄隐形,改为自动恢复描边 2026-11-09 18:11:10 +08:00
qiqi 3baa76d0cd feat(image-annotate): v1.17.0 描边支持「无色」+ 一边无色时 Shift+X 也能交换 2026-11-09 18:07:28 +08:00
qiqi a477705c7f feat(image-annotate): v1.16.0 右栏常驻调色面板 + 可拖宽度 + 字号提升一档 2026-11-09 17:36:44 +08:00
qiqi 6a14f900df fix(image-annotate): v1.15.1 退出编辑器后调节基准未清,换图调节会串上一张的像素 2026-11-09 17:21:40 +08:00
qiqi e10ccee8ad test(image-annotate): 真站 e2e 补「图片调节」两项断言
面板的 11 行是 adjust.js#mountAdjustPanel() 按参数表生成的,构建时漏带模块
(比如 adjust.js 没进依赖树)在单元探针里看不出来,只有真站能发现。
另断言面板认到了作用层,避免 target 为空时滑块看着能拖、实际没有写目标。
2026-11-09 17:07:09 +08:00
qiqi 240d02684a feat(image-annotate): v1.15.0 右侧栏「图片调节」11 项 + 快速效果强度修正
用户要「添加基本的图片调节能力到右边栏,同时优化现在的效果,效果现在弱了一些」。

## 图片调节(新 adjust.js,作用于当前位图图层,默认原图)
曝光 ±100(±2EV)/ 明度 / 对比度 / 阴影 / 高光 / 色相 ±180° /
饱和度 / 温度 / 色调 / 锐度 / 清晰度,单行紧凑布局(240px 侧栏 11 项只占约 240px 高)。
拖滑杆实时预览、松手精细、双击归零、右上全部复位。

## 为什么走 getImageData 而不是 ctx.filter
CSS filter 只有 brightness/contrast/saturate/hue-rotate/blur,做不到:
阴影/高光(要按亮度开软蒙版分区)、白平衡(要 R/B、G/M 通道分别增益)、
锐化(要 USM 卷积)。所以只能逐像素。

## 性能:拖动降到 900 长边预览,松手才全量
实测全量耗时(边长 / 像素 / 毫秒):800²/0.6M/6.7 · 1200²/1.4M/12.8 ·
2000²/4.0M/36.8 · 4000²/16M/144.6。
4000×3000 实测:纯调色全量 64ms;叠锐度 287ms;叠清晰度 343ms;
首次(建 source + preview 缓存)256ms。锐度默认 0,不主动拉就不走 USM。

## 两个必须守住的坑(都写成用例了)
1. 不叠加:source 存调节前像素,每次从它重算;每层 sourceCache 另存,切层往返
   也不会拿「调过的像素」当新基准。
2. 撤销后归零:历史只存像素快照、不存调节基准。撤销还原了像素而滑块还停 +80 的话,
   再拖一次就从错误基准算,等于调两遍。规则:撤销一步 = 调整作废、滑块归零、基准重拍。

## 效果强度
「增强」原 brightness(1.12) contrast(1.1) saturate(1.06),截图对比几乎看不出变化 ——
这就是用户说的「效果弱」。改 1.4 / 1.25 / 1.2;「高对比」contrast 1.4 → 1.6。

回归:harness 199 → 208 全通(新增 9 条),validate 9/9。
踩到的用例坑:① 前面效果用例把原图栅格化并隐藏,调色要先用「还原原图」回到单层;
② 历史栈有容量上限,push 到底后「进一条淘汰一条」,长度永远不变,数标签次数才准。
2026-11-09 17:05:23 +08:00
qiqi 1dc423c025 fix(image-annotate): v1.14.1 点一下字体下拉就把字体打回黑体
用户反馈「刚刚我测试不能切换字体」。实测复现:点开下拉(不选任何项)后
选中文字的 fontFamily 变成 sans,而 select 仍显示 kai —— 数据被静默重置。

根因:选项栏 click 委托用 closest('[data-opt-text]') 识别「文字样式按钮」,
而 <select data-opt-text="fontFamily"> 自带这个属性,被当成按钮处理:
applyTextStyle('fontFamily', textBtn.dataset.value) —— select 没有 data-value,
拿到 undefined,再被 fontKeyOf 的脏值收敛规则改写成默认 'sans'。
防御措施在这里反过来把「没有值」当成脏值改了数据。

改法:
- click 委托只认 button[data-opt-text],select[data-opt-text] 直接早退;
- syncOptionBar() 的 active 态遍历同步收紧为 button(select 没 data-value,
  混进去永远不亮,也不该走开关逻辑);
- change 处理后不再调 syncOptionBar():整体重绘会把刚操作的下拉换成新节点,
  焦点丢失、连续切字体会反复重点。字体只影响画布,其他控件取值不变,无需重绘。

为什么 v1.14.0 的 5 条字体用例没抓到:它们用 page.selectOption(),直接设值 +
派发 change,绕过了 click。真实用户必须先点开下拉,雷就在那一步。
已补 2 条:真实 click() 后字体必须不变、下拉节点不被重建。

回归:harness 197 → 199 全通(0 失败);validate 9/9;产物 392807 B。
2026-11-09 10:07:43 +08:00
qiqi 244fc9c2b2 feat(image-annotate): v1.14.0 文字可以选字体(黑 / 宋 / 楷 / 圆,系统字体族)
用户问「文字工具能不能选字体、难度大不大、性能要求高不高」。结论:能,核心只差
fontOf() 里硬编码的 'sans-serif',难度和性能都不是障碍 —— 真正的约束在字体文件怎么来。

实现(只做系统字体族,不做内置字体文件):
- text.js 新增 TEXT_FONTS(sans 黑体 / serif 宋体 / kai 楷体 / round 圆体),每个是一串
  跨平台候选栈:macOS 命中苹方/宋体,Windows 命中雅黑/宋体,全不命中退通用 sans-serif/serif。
- fontOf() 改为 weight + size + fontStackOf(t);fontKeyOf() 把 undefined / 脏值收敛回 sans,
  防止非法字符串进 ctx.font 让整串失效、静默退回浏览器默认(画面上看不出报错,极难排查)。
- 状态加 S.textFamily,对象加 fontFamily 字段;写回复用 TEXT_STYLE_STATE_KEY 一条路径,
  快照 cloneVectors 深拷贝天然带上,撤销/导出无需额外适配。
- 选项栏加「字体」下拉:唯一走 change 而非 click 的文字样式控件。
- 输入框同步字体族与字重,不会「输入时黑体、确认后宋体」。

为什么不做内置字体(三条硬约束):
1. 宿主 CSP 是 default-src 'self',font-src 回落它,第三方字体 CDN 会被直接拒绝;
2. CJK 字体本机宋体 2.3MB / 楷体 2.2MB / 苹方全字重 64MB,插件产物只有 392KB;
3. Web 字体异步,没 ready 就 measureText 会量出 fallback 宽度,选中框与字形错位、导出画错。

实测(1000²,30 个文字对象各一张整图画布):首次 13.2–42.1ms,热重绘 0.1–0.2ms ——
换字体只在首次多一次字形光栅化,之后走缓存,比现状还略快。中文全角等宽,换字体不改字宽
(10 字 48px 在 6 种字体下都是 480px),所以版面不跳动。另记既有开销:每对象一张整图画布,
1000² 3.8MB / 4000² 61MB,20 个对象在 4000² 上约 1.2GB(与字体无关)。

回归:harness 192 → 197(新增 5 条,含脏值收敛、中文宽度不变、撤销);validate 9/9;
真站 e2e 补 2 条字体断言。
2026-11-09 09:57:09 +08:00
qiqi 546999fdf9 fix(image-annotate): v1.13.1 Shift+X 改成交换填充色与描边色(原来是把填充关掉)
用户反馈「矩形 圆形 钢笔,切换填充与描边色的时候,会导致填充丢掉」,补充一句
「shift+x … 再按这个快捷键填色又回来了,但是描边一直不变」。

实测把能想到的入口全跑了一遍(工具栏两格、色板 tab、SV 拖动、hex、选项栏原生色块、
矩形/圆形/钢笔含闭合与未闭合):fillColor 从来没被清空,画面像素也没丢。
真正的错在 Shift+X 的语义 —— 它绑的是「实心 ↔ 只描边」开关,按一次填充被关掉、
描边色纹丝不动,观感就是「填充色丢了、再按才回来」。而 PS 的 X 是交换前景/背景色。

新增 swapShapeColors(),Shift+X 改为:
- 描边色 ⇄ 填充色对调(同时同步 S.color 与 S.shapeFillColor)
- 填充开关状态不动(交换的是颜色,不是有无)
- 箭头跳过,填充仍「跟随描边色」时只提示不改数据,一步历史可撤销
实心/描边切换仍保留在选项栏那两个按钮上,只把 tooltip 里「(Shift+X 切换)」改掉。

回归:harness 那条旧用例换成「色值互换 + fill 开关不变 + 再按回到原样」,
并挪到文件末尾(交换会写 S.shapeFillColor,夹在中间会污染「新建图形填充跟随描边」
那条断言)。192 项全通,validate 9/9;截图确认钢笔 绿填充/红描边 → 红填充/绿描边。
2026-11-08 22:53:34 +08:00
qiqi bf32ec6ddb test(image-annotate): 真站 e2e 跟上 v1.13 改动(层级按钮删除 / 视图按钮归位 / 快捷键排序)
原 4.6 段还在点 `.iwb-editor-layer-btn[data-layer=down]`,按钮已删会一直等到 30s 超时。
改为:断言顶栏层级按钮数为 0、工具栏末两个子元素是 zoomFit/togglePanels,
排序部分改用 Ctrl+[ / Ctrl+] / Ctrl+Shift+[ / Ctrl+Shift+] 验证,
并新增一条「置底后原图不再被钉在最底」—— 实测输出 矩形 > 原图 > 图层 2,
即被置底的那层压到了原图下面,解封生效。

真站 e2e 全通过(含 SRI / CSP 段)。
2026-11-08 22:29:45 +08:00
qiqi 31866a2407 feat(image-annotate): v1.13.0 顶栏瘦身 / 视图按钮归位 / R·O·L 快捷键 / 填充色实时 / 图层解封
1. 顶栏删掉置顶/上移/下移/置底四个层级按钮(图层拖动 + Ctrl+]/[ 已覆盖),
   `.iwb-editor-commands` 整块移除,`updateLayerUI()` / `bindLayerOrderButtons()` 一并清除。
2. 「适应窗口 / 收起侧栏」移到工具栏 DOM 末尾 —— 工具栏是 shrink-to-fit 的
   absolute 居中容器,放最后天然就在最右,无需额外定位。
3. 快捷键:R 矩形、O 圆形、L 箭头;套索从 L 迁到 A(能力不丢),U 与 Shift+U 保留。
   键盘处理改为优先匹配 e.code,修掉中文输入法下 [ ] 变【】导致的失灵。
4. 原生 <input type="color"> 补接 input 事件做实时预览(skipHistory +
   nativeColorSnapped),change 才落一次可撤销提交 —— 拖一整轮色谱只记 1 步。
5. 原图不再钉底:planPanelOrder / updateSortTarget / onSortEnd / moveLayer /
   mergeUnits 五处解封,其他图层可拖到原图下方,面板提示同步更新。

回归:tools/harness.mjs 140 → 192 条全通;npm run validate 9/9。
2026-11-08 22:26:47 +08:00
qiqi 9c938887c1 feat(image-annotate): v1.11.0 工具栏改为描边/填充双色槽,填充支持「无」
用户反馈:「工具栏的调色、描边、填充 3 个位置调色有问题,应该是 2 个调色,
就是描边与填充,但现在没跟工具栏的调色关联上」+「填色里还要一个取消颜色的按钮」。

问题是真的:工具栏只有一个色点(主色),选项栏另有两个色块。看起来三个调色口,
但工具栏那个**不参与填充**——填充只能在选项栏那个小色块里改,于是「填充跟工具栏
没关系」。颜色值本身也没错,错在入口分散、各自为政。

1) 工具栏改成「描边 + 填充」两个槽(PS 式前后色叠放,30px 位里两颗 19px)
   - 描边槽 = S.color(同时是画笔色/文字色/形状描边色,仍是一个值)
   - 填充槽 = 形状自己的 fillColor;null 时跟随描边色,右下角画蓝三角标出来
   - S.colorTarget 记录「色板在调哪一格」,调色器/SV/hex/吸管/推荐色/最近色
     全部经 applyPanelColor 按目标写,不再一律写主色
   - 点另一个槽只换目标、不收起弹层,「描边改完顺手改填充」不用开关两次
   - 选项栏 data-shape-color 两个色块与工具栏**双向同步**(都走 colorSlots())

2) colorSlots() 成为唯一取值处:工具栏色块、色板头部、hex、SV 标记全从它读,
   避免上一版那类「同一个概念算两遍必然分叉」。syncOptionBar 收尾调 updateColorUI,
   于是「选中对象 → 选项栏显示它的颜色 → 工具栏跟着换」自动成立。

3) 填充可以设「无」:色板里「无」(只在调填充时出现)把 fill 关掉,
   形状内部透明只留描边,**颜色保留**(下次点颜色还是它)。
   无填充时工具栏填充槽显示灰底红斜杠,不露颜色——露着上次的颜色会被当成
   「现在填的就是它」。fillSlotOn() 判定当前上下文有没有填充概念:
   箭头没内部、未闭合钢笔没面积、画笔/文字根本没有,这些情况只显示一格。

4) 槽位命名随工具变:文字工具下叫「文字」、画笔下叫「画笔」、形状下叫「描边」。
   一律写「描边」会让文字工具下的用户以为这个颜色跟自己没关系。

harness 172 → 179 条全通(新增:两格都在且可见、点填充槽后目标是填充、
色板选色只进填充不动主色、无填充清空画面但保留颜色、无填充显示斜杠、
选项栏改色工具栏跟随、画笔只一格);validate 9/9。
harness 顺带修两处:toggleColorPop 选择器要指定槽位(现在有两个按钮);
无填充的像素断言改用画布上不存在的 #a014b2,否则会数到前面用例留下的图形。
2026-11-08 21:52:35 +08:00
qiqi b63771f6e4 feat(image-annotate): v1.10.0 颜色语义统一、选中框改实线、选区命令归位、矢量图形补描边与填充
四个问题来自同一张界面截图,都是真缺陷。

1) 三处颜色各司其职。'#ff4444'/'#ffffff'/'#000000'/0.68 这些默认值原先散在
state.js、text.js、events.js 三处,改一处另两处不跟 —— 界面上就成了「同一个
概念三种颜色」。现在 text.js 导出 TEXT_DEFAULTS 做单点定义,state.js 与选项栏
都从这里取。三个色块统一外观但标记「生效状态」:描边宽度 0 / 底色关闭 /
图形处于描边模式时,色块显示灰色斜纹(不显示颜色本身),语义是「这里还没有
颜色」;只做半透明灰化不够,深色照样是一块黑方块。文字底色默认从纯黑 #000000
改为中性近黑 #101014(68% 透明),色块按真实不透明度渲染。选描边色时若宽度
为 0 自动给 6px,与「选底色即开底色」同一条原则。

2) 选中框从虚线改实线。虚线在修图软件里的语义是像素选区(蚂蚁线),文字外面
套一圈虚线会被当成「多出来一个删不掉的选区」。objects.js 的文字/形状、
layers.js 的位图图层三处同步改为实线,虚线只留给真正的像素选区。

3) 选区命令(全选/反选/取消)归位到选区工具。它们操作的是像素选区,跟文字对象
无关:以前挂在「选中文字/图形」的选项栏里,选中文字就冒出来;而矩形/套索
选区工具反而没有。现在选区工具有,选择工具「未选中任何元素」时也有。

4) 矢量图形补上描边色与填充色。每个形状新增独立 fillColor;描边色不再另起一份,
直接复用主色(左侧色板/吸管/选项栏一个真相源,四处永远同步)。fillColor===null
表示跟随描边色,于是新画的实心图形是同色实心,换主色整块跟着变。
矩形/圆形/钢笔/箭头的选项栏都出「描边 ■ / 填充 ■」色块(箭头无填充区域,只给
描边色);选中对象读它自己的值,没选中时改的是新建默认值。选填充色即自动切
实心,色块从斜纹变成实际颜色。「样式 描边/实心」也改成读选中对象自己的 fill
(以前只看全局默认值,选中已实心的矩形却高亮「描边」,和画面反着来)。

顺带简化:文本样式与形状颜色共用同一套色块控件与 CSS,is-off 用斜纹 +
虚线边框;底色色块用 --sw-a 变量体现半透明。

harness 162 → 172 条全通(新增:默认色不写死、色块生效态、选区命令归位、
选中框实线覆盖率 ≥0.85、图形描边/填充色与实际像素);validate 9/9。
harness 自身两处改法:清选中改用「切到别的工具再切回」(画布上早有别的用例
留下的图形,点空白会点到它们);像素断言改成全画布统计同色像素
(矢量画布含 overlayPad 外扩,按图片坐标换算单点会采到别处)。
2026-11-08 21:24:38 +08:00
qiqi 73a29715d3 fix(image-annotate): v1.9.1 文字输入框贴住点击点、选区图标归位、底色一选就生效
1) 输入框偏到左上:showTextInput 用 canvasStack 的矩形换算,但 stack 尺寸是
(imgW + 2*overlayPad)*scale、图片在 stack 内还偏移 pad*scale(图层 canvas 的
left/top)。比例偏小又漏偏移,两个误差同向叠加。改用 textCanvas 的矩形
(与图层 canvas 同基准,精确等于图片显示区域),并按 textarea 的边框 2px +
内边距 8/4px 反向偏移,让输入框里的文字起点正压在点击点上;提交后
drawTextObject 也从 t.x/t.y 起画,所见即所得。

2) 选「选择」工具后三个选区图标不见了:两处叠加。
   - selCmdHTML 排在 hint 之后,而 .iwb-opt-hint 带 margin-left:auto;
   - 更关键的是 .iwb-opt-sep 写成 margin: 0 4px 0 auto,分隔线自带 auto,
     会把分隔线之后的内容整组推到最右,选项栏排满时直接滚出可视区。
修法:分隔线只分组(margin: 0 2px),留白交给末尾 hint;选区按钮排在 hint 之前。
现在「文字」「选择」两个工具下都是同一组三个图标,未选中元素时也在。

3) 设了底色看不到:底色一直在画,只是「只改颜色没点开关」时 bgFill 仍是 false。
   - 改 bgColor 时自动打开 bgFill,按钮 active 同步;
   - 顺带修掉更硬的 bug:「底色」按钮只能开不能关 —— data-value 在生成 HTML 时
     写死,状态变了没人更新,每次点都传「开启」。改由 syncOptionBar 按当前状态翻面;
   - 默认底色透明度 0.55 → 0.68(浅色/花色底图上 0.55 太透,容易被当成没生效)。

harness 158 → 162 条全通(新增输入框落点误差 ≤3px、Esc 不留空对象、
选择工具未选中仍有 3 个图标、只选颜色即自动开底色);validate 9/9。
2026-11-08 20:53:58 +08:00
qiqi e699c22fa0 feat(image-annotate): v1.9.0 文字样式包、吸附参考线、圆角与最近色、复制到剪贴板
文字从「字号 + 颜色」扩到完整样式:字重(常规/粗/特粗)、对齐(左/中/右)、
行距、描边、底色块、多行(textarea + Shift+Enter)。新增叶子模块 text.js,
fontOf / textMetrics / textBox / drawTextObject 成为唯一事实来源,
objects.js(预览/命中/包围盒)与 layers.js(栅格化)共用,避免量一套画一套;
描边与底色撑大包围盒,手柄、吸附、缩略图随之变化。单行无描边无底色的老文字
包围盒与旧实现逐像素一致,老作业打开不变形。

吸附参考线:snap.js 只做纯计算。目标线为画布 0/中/满 + 其他可见元素的左中右、
上中下;阈值 6 屏幕像素按 viewScale() 折回图片像素,磁力不随缩放变大;
命中画洋红参考线(区别于选中框的橙),松手清空;Alt 全程禁用。
位图/文字/形状三条拖动路径都接,文字需补 b.x - t.x 原点偏移。

矩形圆角:shapeRadius 进 drawShape,半径夹到 min(w,h)/2,路径手写 arcTo
(不用 ctx.roundRect,老内核没有)。最近使用颜色最多 8 个,存 ctx.settings
跨会话保留,只有落定的改色才记录;色板改用事件委托以覆盖动态插入的色块。

导出「复制」:结果编成 PNG 写 ClipboardItem,可直接粘进聊天窗口/后台上传框
且不关闭编辑器。优先 createImageBitmap 绕开宿主 CSP 的 img-src 限制;
非安全上下文无 navigator.clipboard 时明确提示改用「导出」而非静默失败。

顺带修:选项栏中文双字标签加 white-space:nowrap(否则 36px 一行内竖排成
「常/规」);.iwb-editor-optionbar-tip 补基础样式(原来只有 display:none,
裸 span 参与 flex 收缩被挤成两行贴边);文字工具的 hint 移到按钮之后,
放不下时让说明滚出视野而不是把操作按钮顶没。

harness 140 → 158 条,全部通过;validate 9/9。
2026-11-08 20:27:32 +08:00
qiqi 040b08fe28 fix(image-annotate): v1.8.3 图层不透明度滑杆可拖动、图层拖动排序真正生效
- 去掉图层项的 HTML5 draggable(它会把子元素的原生拖动一起接管,
  滑杆因此只能点不能拖)
- 排序改为指针拖动:越过行中线就实时插位,松手读 DOM 顺序落地,
  修掉「向下拖一格索引回退等于原地不动」
- 拖动中整行浮起、其余行让位;原图固定最底层;滑块拖动像素实时跟随
- blur 兜底必须判 e.target === window,否则子元素失焦会取消拖动
- harness 新增 6 项(真实鼠标拖滑杆 / 换位与 z / 拖到最底 /
  位移不足算点击 / 焦点在工具栏时也能拖 / 位图与矢量混排),共 146 项
2026-11-08 19:27:09 +08:00
qiqi 6e1685998f fix(image-annotate): v1.8.2 选择框控制点尺寸固定为屏幕像素
现象:选中图形时,控制点巨大(约 100px 的发光方块),大小随图片尺寸变化、与缩放无关。

根因:控制点、旋转手柄、虚线间距、命中半径全部写成 5.5 / S.zoom。
但 S.zoom 是「相对 fitW 的倍数」,不是「图片像素→屏幕像素」的比例。叠加 overlay
画布按 viewScale 拉伸后,真实屏幕尺寸 = 11 * fitW / imgW —— 只跟图片尺寸走:
小图被适应窗口放大 5~10 倍时膨胀到 100px,大图缩到 4px 看不见。
zoomStep 的 anchor 换算是另一个语义(相对 fitW 单位),保持 / S.zoom 不动。

顺带发现第二个问题:overlay 画布的像素缓冲等于图片尺寸,小图放大后 UI 叠层糊成光斑。

修法:
- 新增 plugin/editor/scale.js(零依赖叶子模块)
  viewScale() = fitW*zoom/imgW;overlayScale() = clamp(fitW/imgW, 1, 4);
  resetOverlayTransform(cx) = 恢复「图片坐标 + pad + 倍率」
- 7 个文件共 30 余处 UI 常量改为 X / viewScale();去掉 Math.max(X/zoom, N)
  的托底(N 是图片单位,放大时会变成巨大命中区,导致误触)
- overlay / selection / cursor 三张画布按 overlayScale 建缓冲,绘制坐标仍是图片单位,
  所以全部绘制代码无需改动;四处置空函数(crop/selection/tools/index)改用设备像素
  clearRect + resetOverlayTransform 恢复

必须做成叶子模块:viewport 与 crop/objects/layers 存在循环 import,把换算放在循环里
esbuild 打成 IIFE 后另一侧拿到 undefined —— 实测 clearOverlay 报
"resetOverlayTransform is not defined",编辑器直接打不开(已踩过)。

实测(Playwright 按屏幕分辨率重采样后量像素包围盒):
  96x64    控制点 7~8px   旧实现 101.5px   overlay 288x256 -> 1152x1024
  800x600  控制点 8~9px   旧实现 12.2px
  2400x1800 控制点 9~10px 旧实现 4.1px
纯白内区比视觉尺寸小 1.5px(描边压边),视觉上稳定 11px。

验证:harness 140 项全通(新增 1 项控制点尺寸断言)、validate 9/9。
2026-11-08 17:49:16 +08:00
qiqi fccb9ae69e fix(image-annotate): v1.8.1 修复 SRI 加载失败(发布改内容寻址文件名)
线上报「脚本完整性校验失败(integrity 不符或加载失败)」,插件不可用。

根因不在插件代码,在发布通道:scripts/plugins-publish.sh 用固定名
plugin-image-annotate.js,而清单 integrity 随内容每次变化。客户端只要留着
旧字节(浏览器磁盘/内存缓存、中间代理),新 integrity 就对不上,SRI 判失败。
no-cache + ETag 只是「可缓存但须回源校验」,管不住已到手的旧副本。
实测服务器端三处一致(清单 integrity = 线上字节 = 本地字节,355289 B),
证明问题完全在客户端拿到的那份。

修法(宿主仓同步改 scripts/plugins-publish.sh):文件名改为内容寻址
plugin-<id>.<sha256前12位>.js,与 plugins-publish.mjs 的 storedNameOf 对齐。
内容变 ⇒ 名变 ⇒ 新版本必然是新 URL,SRI 必中;同时命中 Functions 的
IMMUTABLE_JS_RE,拿到 public, max-age=31536000, immutable。

插件本体与 1.8.0 逐字相同,产物仅 manifest 版本号不同。
验证:harness 139 项全通、validate 9/9、产物 355289 B。
2026-11-08 17:13:06 +08:00
qiqi 3819048e54 feat(image-annotate): v1.8.0 快速效果加参数(马赛克块大小 / 柔化半径 / 其余强度)
v1.4 的六个效果都是一键定死强度:马赛克在 800px 图上固定 13px 块挡不住手机号,
柔化固定 1.6px 小图上几乎看不出。现在每个效果都带参数,点完还能继续拖。

参数模型:
- 百分比类(反白/灰度/增强/高对比):强度 0~100%,走 invert()/grayscale() 原生比例,
  其余按 k 插值(高对比 = grayscale(k) contrast(1+1.4k))
- 物理量类:柔化半径 0~16px、马赛克块大小 2~96px,默认值按短边缩放

关键设计:效果不能叠加在自己的结果上。
点效果时把目标层像素备份进 S.fx.source,拖滑杆一律「先还原 source 再按新参数渲染」。
否则「马赛克 12 → 48 → 12」会做三次重采样,块越来越碎且不可逆。

交互约定:
- 一次效果 = 一条撤销(点效果时快照,拖滑杆不再拍)
- 同效果再点 = 回默认值,不再糊一层
- 切到别的层滑杆置灰(源属于旧层),切回自动恢复
- 当前生效效果描橙边;拖滑杆不重建图层面板(否则每帧 innerHTML 会闪)

顺带修了两处既有缺陷:
- .iwb-editor-fx-target 标签从来没被更新过,一直显示「原图」——现在跟随目标层
- 柔化默认过弱(1.6px / 800px 图)——系数改 400、下限 1.2

验证:harness 139 项全通(新增 6 项,含「12→48→12 像素指纹一致」的叠加检测)、
validate 9/9、产物 341608 B。
2026-11-08 17:06:56 +08:00
qiqi eb90939f11 test(image-annotate): 真站 e2e 的 SRI 断言不再写死内容寻址文件名
断言原本要求 src 必须是 plugin-image-annotate.<hash12>.js,但带主干守卫的
合规发布通道 scripts/plugins-publish.sh 产出的是固定名 plugin-image-annotate.js
(走 no-cache + ETag),于是发布成功后这条断言必红、其余 26 项全绿。

SRI 的实质要求是「带 integrity 且有值」,与命名策略无关,改为两种命名都接受。
1.7.0 实测:test 站 27 项全通。
2026-11-08 16:54:50 +08:00
qiqi 3e76f2792e feat(image-annotate): v1.7.0 图层面板补齐(缩略图 / 重命名 / 不透明度)
按通读代码后定的顺序处理 P3 剩余项里最有价值的三条。

1) 不透明度真正可调
   opacity 字段一直在(合成/合并/导出/快照都读它),但面板没有任何控件能写它,
   roadmap 里标的「已有」与事实不符。现在选中层后在该项下方展开滑杆:
   - 位图走 canvas 的 CSS opacity(像素不动),导出/合并时乘 globalAlpha,所见即所得
   - 文字/形状改完重绘矢量层(不透明度已烘进像素,不能再叠 CSS)
   - input 第一次到达才拍快照,一次拖动只产生 1 条历史;双击滑杆复位 100%
   - 非 100% 且未选中的层在名字旁挂百分比角标

2) 缩略图 + 双击重命名
   - 22px 缩略图(canvas 44 设备像素),等比缩放居中;空图层透出类型图标兜底
   - 绘制合批 90ms,避免每次 renderLayerPanel 都重画几十张
   - 双击名字改名(Enter 提交 / Esc 放弃),改名期间禁用整项拖动

3) 顺手清理
   - 删除 .iwb-layer-color / .iwb-layer-width 两个永远看不见的死控件
     (CSS display:none !important 写了三遍),连同绑定与死样式
   - pasteImageFromUrl 的 window.alert 改 toast(阻塞弹窗在宿主里会卡整页)
   - resetState() 补清 layerMulti / hoverPos / lastClick / lastNameClick / altPicker

关键修正:矢量层不透明度只能乘一次。
drawVectorToCanvas / drawShape 已把 opacity 画进像素,getCompositeCanvas 与
composeUnitsInto 再乘 globalAlpha 就是双倍透明 —— 两处都改为只对位图乘。

验证:harness 133 项全通(新增 4 项)、validate 9/9、产物 331811 B。
harness 的版本断言改为读 package.json,不再硬编码。
2026-11-08 16:43:38 +08:00
qiqi 7c2e23e4e3 ci: 补 paths-ignore(只改文档/CI 自身不触发 validate)
HANDBOOK 第八节 8.2 第 3 条硬性要求:push 触发必须配 paths-ignore,
至少覆盖 **/*.md、docs/**、.github/**。本仓库此前只有 concurrency 与
timeout-minutes,缺这一条——插件目录 README 改动会白跑一次 validate。
2026-11-05 11:55:17 +08:00
qiqi 5f11e40f43 feat(image-annotate): v1.6.0 色板入工具栏 + 快速效果 + 画完回 V + 图层合并(补齐 1.3.0–1.6.0)
上一次提交停在 1.2.12,本次把 1.3.0 → 1.6.0 四个版本的源码一并归档。

v1.3.0 色板进工具栏 + 矢量/文字工具只负责创建
- 工具栏最左色点 → 弹层(前调色器、后颜色设置 + 推荐颜色)
  - 弹层必须挂 .iwb-editor-modal 下:工具栏是 overflow-x:auto、画布 wrap 是 overflow:clip,塞进去会被裁
  - applyColorChange 改 pointerdown 拍一次快照,修「拖调色器爆撤销栈」
  - 每次按下前从 S.color 重同步 hsv,修「点推荐色后再拖 SV 跳回红」
  - 外部点击改 document 捕获阶段监听(画布 mousedown preventDefault,冒泡收不到)
- onShapeMouseDown / onTextMouseDown 不再命中已有对象;setTool 的 keepSel 只剩 select|picker

v1.4.0 侧栏快速效果
- 6 个:反白(反相,非排版意义的黑底白字)/ 灰度 / 提亮 / 压暗 / 高对比 / 马赛克
- 目标是当前位图图层,标题右侧实时显示层名;不碰图层几何也不改 image
- 导入图片层先克隆栅格化成「xxx · 效果」层、原层 visible=false(直接改像素会被 redraw 冲掉)
- 撤销走快照,base 与画笔层走像素路径

v1.5.0 画完自动回 V,编辑统一走 V
- 图形/文字落笔完成即退出当前工具并切 V
- 钢笔改为只用 V 双击进节点编辑
- 双击判定改成自算 380ms 窗口:单击选中会重绘矢量画布,浏览器不再派发 dblclick

v1.6.0 笔刷环 + 图层合并
- 画笔用 [ / ] 调粗细时立刻刷新笔刷环(原来只在 mousemove 里 drawToolRing,键改后不动)
- 图层合并:⌘/Ctrl 点击多选后合并、⌘E 向下合并、⌘⇧E 合并可见(PS 语义)
  - 统一用 composeUnitsInto 合成并按结果重排 z,避免合并后像素为空
  - 隐藏层不参与且保留;矢量(文字/形状/钢笔)直接栅格化
  - 有 base 参与时写回 base(像素快照可逐像素撤销),否则新建位图层承载

harness 129 项全通。1.6.0 已发布到线上:
plugin-image-annotate.198a20e4d722.js / sha256-GYog5NcinRDM67in67JxJUtBhUPB2lfttM/kw9UHwFo=
2026-11-05 11:27:37 +08:00
qiqi 577a891e73 ci: 限制触发分支 + 并发取消 + 超时兜底,减少 Actions 分钟消耗 2026-11-05 11:27:04 +08:00
qiqi 4ab12be15d feat(image-vectorize): v0.3.1 预览改白底 + 填充/背景色并排(带底可选写入导出) 2026-11-05 09:11:19 +08:00
qiqi 866c420c5c feat(image-vectorize): v0.3.0 按孤岛拆分元素(Figma 里可单独选中)
用户需求:「现在元素是一个整体,我需要有个勾选按单个元素分解,孤岛是分离的,
输出时能选分类的还是整体的」。

potrace 出厂把所有轮廓塞进一个 <path>(800×800 菜单图 1 个 path / 129 个子路径,
靠 fill-rule=evenodd 互相挖洞),所以粘到 Figma 只是一个整体。

新增 plugin/islands.js:
- 解析 d 为子路径(只认 potrace 输出的 M/C/L/Z,全绝对坐标)
- 按几何包含建父子关系(bbox + 射线法点在多边形内),深度偶数 = 外壳、奇数 = 孔洞
- 每个外壳 + 它的孔洞合成一个 path(孔洞必须同 path,evenodd 才挖得出洞),
  不同组并列输出、不包 <g>;元素按面积降序(大块在下,遮挡关系同原图)
- 为什么不能按 M 直接切:切了孔洞就变实心("O" 中间被填满)

UI:输出区加「按孤岛拆分」开关(默认开,ctx.settings 记忆),统计改显示元素数,
合并时标注「N 孤岛合并」;复制反馈说明粘过去是 N 个独立元素还是 1 个整体。

验证:harness 47 项(新增 8 项:多 path / 无 g / 统计一致 / 取消勾选合回 1 个 /
坐标集合完全一致 / 渲染差异 0.003%)、真站 e2e 18 项全绿。
2026-11-05 08:50:53 +08:00
qiqi d151de74a1 feat(image-vectorize): v0.2.1 精度可调 + 复制到剪贴板 + 高级默认展开
用户反馈三项:
1. 高级参数默认展开(不再藏起来),折叠按钮保留、展开状态记忆在 ctx.settings
2. 新增「复制 SVG」:一次写入 image/svg+xml + text/html + text/plain 三种口味,
   粘到 Figma / Illustrator 直接是真矢量。Chrome 对可写 MIME 有白名单,
   塞了不支持的类型会整次 write 失败,所以先 ClipboardItem.supports() 探测再逐级降级
3. 边缘精度可调:optTolerance 默认 0.2 → 0.05(三档 精细/标准/轻量),
   大图降采样上限 2000 → 3000px(实测单色 3200px 96ms、灰度 4 层 3000px 179ms)

预览底部的说明改为胶囊提示(原 #75758a 裸文字在浅灰棋盘上几乎看不见),
面板间距压紧,高级区展开后整列参数在 980px 高下不用滚。

验证:本地 harness 38 项、真站 e2e 17 项(含真实剪贴板读回校验)全绿。
2026-11-05 08:33:51 +08:00
qiqi c4e4b15375 feat(image-vectorize): v0.2 换 potrace 引擎,只做单色/灰度
用户裁定「只要单色/灰度就够」后重做:VTracer(彩色分层 wasm)换成 potrace
(纯 JS,Inkscape 同款内核)。文字笔画完整、turdSize 去掉毛刺、灰度层数 2–5。

- 纯 JS ⇒ 不需要宿主放宽 CSP;插件 238KB → 116KB
- 自带 potrace 移植(GPL-2.0,去 jimp 依赖,改吃 ImageData),License 随目录
- 灰度阈值自己按等像素量分位算(上游 steps:5 要 28s,这里几十 ms),
  并处理「主背景峰要排除」「切点必须严格递增」两个坑
- 新增 tools/trace-cli.mjs:拿真实素材直接跑参数、出对比图
- harness 重写 32 项(含「无 wasm-unsafe-eval 的 CSP 下跑通」反向锁);真站 e2e 13 项
2026-11-05 07:57:18 +08:00
qiqi 6f3a4676bb chore(image-vectorize): 存档未发布插件(描摹质量不达标,已下线)
用户实测描摹效果达不到可交付线(中文笔画断裂 / 抗锯齿边缘毛刺 / 浅色块碎层),
裁定不做这个插件。线上已清理:KV 清单移除、字节 GC 删除、宿主 `wasm-unsafe-eval` 收回。

代码本身是好的(VTracer wasm 跑通、5 预设 + 全参数面板 + 空格对比预览 + SVG/PNG 双输出、
本地 harness 27 项 + 真站 e2e 13 项全绿),问题在算法定位:VTracer 适合 logo / 线稿 /
纯平色块,不适合照片与带抗锯齿的合成图。留档备查,README 顶部已标注「已下线,未发布」。
2026-11-05 01:04:35 +08:00
qiqi 3080916c62 feat(image-annotate): v1.2.12 画笔/橡皮按住 Alt 临时吸色(PS 手感)
- 画笔或橡皮下按住 Alt 立即切吸管,点击取色后仍保持吸管(可连续取色),松开 Alt 回到原工具
- S.altPicker 标记区分「真按 I 切吸管」与临时吸管;exitPicker 在 altPicker 下只清缓存不退出
- 兜底:窗口 blur / 主动切别的工具都会结束临时吸管,避免工具卡在 picker
- Alt keydown preventDefault(防 Windows 浏览器把单独 Alt 当菜单激活)
- __debug 补 color / altPicker;harness 新增 Alt 吸色回归断言(116 项全绿)
2026-11-04 23:17:56 +08:00
qiqi c176744846 feat(image-annotate): v1.2.11 选中框手柄/旋转手柄/顶栏与选项栏打磨
- 缩放手柄 17px→11px(形状/文字/位图/放置四处统一),命中半径同步收小
- 旋转手柄重绘:细弧+末端小箭头(旋转语义更直观),线更细、色 #f0b34e
- Shift+X 切换选中形状 描边/实心(箭头无实心给提示);isTyping 放行 Shift 组合键,
  参数数字框里按 Shift+X 不再被吞
- 硬度:滑杆 84→140px + 5 个快捷点(0/25/50/75/100);笔刷推荐大小 7→4 个
- 顶栏:标题在最前,新建/覆盖/退出跟其后且三键统一中性色;标题后与撤销组后各加竖分隔
- harness 更新/新增断言(115 项全绿)
2026-11-04 23:06:39 +08:00
qiqi 0d161d6ded fix(image-annotate): v1.2.10 选中形状/文字后切吸管取色能改对象颜色
- 根因:setTool() 切工具时无差别清掉 selectedShapeId/selectedTextId/selectedLayerId,
  选中形状按 I 切吸管时选中态当场丢失,applyColorChange 找不到对象,颜色只写进画笔色
- 修复:picker 作为临时工具保留选中态(与 select 同级白名单);exitPicker 按落回的工具用
  同一套规则清理,避免画笔工具下残留选中框
- 吸管提示文案补充「选中形状/文字时取色直接改它的颜色」
- __debug().shapes 补 color 字段;harness 新增 1 项回归断言(114 项全绿)
2026-11-04 22:52:46 +08:00
qiqi 9d923aed26 feat(image-annotate): v1.2.9 图层 PS 快捷键 + 顶栏会话组左移
- 图层快捷键(PS 同款,e.code 匹配防中文输入法吞键):
  Ctrl+]/[ 上/下移一层、Ctrl+Shift+]/[ 置顶/置底、Alt+]/[ 向上/向下选层
- Delete 删除选中的位图图层(原图锁定除外)
- moveLayer 无选中时 toast 提示,不再无声失败
- 顶栏「新建/覆盖/退出」移到最左会话组;右侧只留 输出+导出,下载改文案「导出」
- [ / ] 笔刷大小同时匹配 e.code,中文输入法下不再失灵
- __debug().shapes 补 z 字段;harness 新增 6 项断言(113 项全绿)
2026-11-04 22:48:12 +08:00
qiqi e1465b9d68 feat(image-annotate): 1.2.8 工具栏移至画布底部悬浮(Figma 风格) + 修 canvas-wrap 可编程滚动导致画布跳位(overflow:clip) + computeFit 预留工具条高度 + 工具条上滚轮不缩放 2026-11-04 22:33:56 +08:00
qiqi a1c3a40f17 fix(image-annotate): 1.2.7 首笔自动建层缺视图样式导致第一笔错位(补 updateLayerCanvasStyles) + PS 画笔大小快捷键 [/] 2026-11-04 21:59:03 +08:00
qiqi 9e50697dd6 feat(image-annotate): 1.2.6 图层新建/导入回面板标题栏 + 还原图标改循环重置 + 适应窗口真重算 fit + 全量 PS 快捷键(V/M/L/B/E/P/T/U/C/I/H, Ctrl+0/1/S/O/Shift+N, Tab, Shift+U/M) 2026-11-04 21:49:49 +08:00
qiqi c87cec659b feat(image-annotate): 1.2.5 选区命令(全选/反选/取消)移入选择工具选项栏,竖工具条不再占用 2026-11-04 21:35:34 +08:00
qiqi 77b4f7d5fe feat(image-annotate): 1.2.4 选择态就地改形状参数(描边/实心/线宽) + 顶栏命令带(更多菜单图标化: 新建/导入图层、置顶/上/下/置底、适应窗口、收起侧栏) + 选区命令入竖工具条 2026-11-04 21:12:36 +08:00
qiqi b83b8f3755 fix(image-annotate): 1.2.3 橡皮修复(漏 import getActiveLayer + 锁定层兜底)/钢笔描边实心切换/侧栏笔刷粗细移除/顶栏输出组右置 2026-11-04 20:44:52 +08:00
qiqi f50b734fd7 feat(image-annotate): 1.2.2 手柄仅选择工具/高亮跟随绘制目标/选项栏快捷点与裁剪参数/Enter-Esc 裁剪 2026-11-04 20:30:49 +08:00
qiqi 1bf8220c05 feat(image-annotate): 1.2.1 默认不预建画笔层(按需自动落标注层)+ 侧栏硬度/透明去重 2026-11-04 20:06:38 +08:00
qiqi d8e4e0cb26 feat(image-annotate): 1.2.0 非破坏性裁剪(可撤销/不 flatten)+ 工具参数解耦与就地选项栏 2026-11-04 18:30:54 +08:00
qiqi a4e89f5f8b fix(image-annotate): 1.1.2 输出预设收口(JPG 自动白底、边长/体积控件、maxKB 只属电商预设、下载与还原后摘要刷新) 2026-11-04 18:09:06 +08:00
qiqi 9a0f5bab69 fix(image-annotate): 1.1.1 反选作用区域/裁剪态选区互斥/Delete 优先级/退出结算宿主 Promise(含 1.1.0 布局修复) 2026-11-04 17:54:40 +08:00
qiqi be05f31479 fix(image-annotate): dom 模板多余闭合标签导致状态栏被挤出 modal、右侧漏出宿主界面(1.1.0 布局修复) 2026-11-04 17:39:17 +08:00
qiqi 662d7eae77 feat(image-annotate): 选区编辑 + 便利版 UI + 单张输出预设(1.1.0) 2026-11-04 17:00:49 +08:00
qiqi b9ace636ef fix(image-annotate): 图层 z 序统一 + 排序按钮/选中修复(1.0.5)
- 根因:粘贴图片用 S.layers.length 当 z,矢量用 ++S.zCounter ⇒ z 撞车;
  面板/DOM/合成/命中四处各自排序,导致排序按钮交换 z 无效、截图选不中、双高亮
- objects.js 新增 layerUnits()/layerUnitsDesc()/assignLayerZ()/selectUnit()/hitTopmost():
  图层顺序唯一真源、连续 z、选中态唯一、统一 z 降序命中
- moveLayer 改为统一列表重排(置顶/上移/下移/置底全部生效,base 固定在最底不吞元素)
- placement 改 ++S.zCounter;deleteLayer 不再重置位图 z;面板高亮与画笔目标(✎)分离
- 形状/文字/钢笔创建、裁剪、清空标注、重开编辑器均清旧位图选中 id
- e2e 补 9 条回归断言(真站 22/22 通过);README 记录与上游的偏离,防回灌覆盖
2026-11-04 16:14:57 +08:00
qiqi 5f9303986a feat(image-annotate): 编辑器内 ⌘/Ctrl+V 粘贴剪贴板图片为新图层(1.0.4)
- 粘贴优先级:剪贴板图片文件 > text/html 的 <img src> > text/plain 图片 URL/data URL
- 命中后进入既有「图片放置」模式(拖动/缩放,点外部或回车确认,Esc 取消)
- URL 一律 fetch→blob→dataURL(跨域图直接挂 <img> 会污染画布,导出时 toBlob 抛 SecurityError);
  data: URL 反而不能 fetch(CSP connect-src 无 data:),直接走 loadImage
- 命中即 stopImmediatePropagation:宿主在 window 气泡阶段也监听 paste(建 ref 节点+下载),
  不掐断会一次粘贴双响应,且宿主抢先建节点会破坏后续「覆盖」写回(e2e 实测抓到)
- 正在文字输入框打字时不抢 text/html 与 text/plain 的粘贴
- e2e 新增合成 ClipboardEvent 粘贴用例;修过期 SRI 断言(内容寻址名带哈希)
2026-11-04 15:49:50 +08:00
qiqi 0cdadc3a89 docs(style-source): 说明拖放落点会被宿主就近吸附(空处不偏移) 2026-11-02 21:17:55 +08:00
qiqi 8dca2a5b67 feat(style-source): 拖拽插入 —— 按住「插入提示词/参考图」拖到画布上松手,节点落在松手点(1.2.0)
- 松手点交给宿主换算(ctx.canvas.screenToWorld),插件不碰 pan/zoom
- 拖拽中跟一张幽灵卡片,进画布提示「松手放这里」,松手不在画布上则取消
- 位移 <6px 视作点击,仍走 findSpot 自动找位;拖完抑制随后的 click(不会插两次)
- window + 捕获阶段监听:面板 .iwb-fullmask 的 stopPropagation 拦不住
- 详情重绘前摘掉旧监听(否则每选一次卡片叠 3 个 window 监听)
- harness 补 7 条断言(幽灵卡片 / pointer-events / 世界坐标换算 / 只插一次 / 画布外取消)
2026-11-02 21:01:36 +08:00
qiqi 75ea785fcc fix(style-source): 插入位置交给宿主,不再自己估算 (1.1.2)
用户反馈:插入的提示词会叠在已有节点上,也不在画布中间。

根因:插件自己算坐标。它只有节点的 x/y,拿不到 viewport(pan/zoom)、canvasSize 和各节点
实测高度,旧实现是「选中节点右侧固定 +380 / 最右节点右侧 / 空画布 (80,80)」——既不居中也不避让。

- 删掉 nextSpot / GAP_X,insertPrompt 改为 createNode('prompt', null, null, ...)
- 宿主收到空坐标时走 findSpot():从视口中心向外环形扫,跳过与已有节点相交的格子,
  并把候选钳在视口内;宿主那边有 viewport、canvasSize、measuredH,只有它算得准
- 参考图本来就经 createImageNode → findSpot('ref'),同一套逻辑,无需改动
- harness:mock 宿主复刻 findSpot 的最小行为;断言从「插在选中节点右侧 (480,120)」
  改为「插件传空坐标(auto=true)」+「宿主定位结果不与已有节点相交」
- README 补「插入位置为什么必须交给宿主」

⚠️ 依赖宿主 2026-11-02 的 createNode 改动(空坐标 → findSpot),发布顺序:先宿主后插件。
2026-11-02 18:48:07 +08:00
qiqi 3969acb9b9 fix(style-source): 面板拉宽后右侧留白 —— 容器撑满 + 详情栏限宽 (1.1.1)
用户反馈:拉宽资源库后右边一大片空白没填充。

根因:宿主 .iwb-full-main 是 display:flex,插件容器 .iwb-full-panel-plugin 是裸 div,
作为 flex 子项默认 flex:0 1 auto ⇒ 宽度按内容算(实测 664px);根元素的 width:100%
只能等于 664,多出来的 380 全空着。

- mount 时按条件补 flex:1 1 0%:仅当「自身没有显式宽度 + 父容器是 flex row」。
  无条件设 flex 会把固定宽度的侧栏拉满父容器(之前踩过),所以必须带判据
- 详情栏 46% → 40%,且 clamp 300~380:上限保持不变(用户确认现在宽度合适),
  栅格才是浏览主体;1040 宽时栅格 660(5 列)、详情 380,两栏之和正好等于面板宽
- footer 按钮补 min-width:0 + ellipsis,避免超长文案顶出右边缘
- README 补「容器为何要 flex:1 且为何要判据」与详情限宽的理由
- harness 新增 3 条守门:
  · flex 父容器(1360 - 左栏 320)下容器撑满 1040
  · 宽档两栏之和 == 容器宽(无空白)
  · 一行 ≥4 张且卡片 90~150px(越宽只加列、不撑宽卡片)
2026-11-02 18:02:45 +08:00
qiqi 1ef85e7d55 fix(style-source): manifest version 跟上 package.json(1.0.4 → 1.1.0)
CI 的 scripts/validate.mjs 会比对 entry 内 version 与 package.json,
上一版只改了 package.json,validate 直接红。

harness 里也把版本号写死成 '1.0.4' 了,一并改成从 package.json 读——
正是这种硬编码让本地测试看不见这个不一致。
2026-11-02 12:00:03 +08:00
qiqi 493dd21303 test(style-source): harness 改成注入探针风格,覆盖两个降级分支
数据仓整改后(PR malongan/style-source#195),线上数据已经
「槽位全部有声明、desc 有就全有」,原来拿脏数据当样本的 3 条断言失去前提:

- 「有占位符但没声明也有输入框」:改用注入的探针风格 __probe_undeclared
  (克隆真实风格,只改 id/name/prompt/variables),继续覆盖 implicit 降级
- 「没有 desc 的变量降级成占位符名」:换到第二个探针 __probe_desc_mix
  (一半变量带 desc),并补一条「desc 全覆盖的风格每个输入框都有说明」
- {SUBJECT} 的中文标签断言:从「回退成 SUBJECT」改为「认得 画面主体」

另外修到一个真坑:styles.json 里 variables 是 {kv_var: style_var} 的字典,
探针写成数组时 Object.keys 拿到的是 0/1 索引,desc 全丢。

63 条断言全过。
2026-11-02 11:57:54 +08:00
qiqi 12446cb7d4 feat(style-source): 变量 desc 作为输入框填写提示 (1.1.0)
数据仓 styles.json 新增 variable_descs(按 kv_var 索引),插件是它唯一的消费者,
之前这个字段在 generate_data 阶段就被丢掉了。

- varKeys():与 labelOf 同构地建 descOf,把 desc 从 kv_var 转到占位符名上
- rowOf():placeholder 优先用 desc,没有才退回占位符名;完整说明挂 title
- input 加 data-var-name 属性——placeholder 现在可能是中文说明,
  靠它反推槽位名会把「有 desc 的风格」全判成声明落空(harness 原来就这么取,已改)

兼容性:纯增量。没有 variable_descs 的旧数据照常工作(placeholder 退回占位符名)。

harness 新增 4 条断言,变量特写截图改为拍「东方花茶香氛海报」(同时有 desc 和无 desc 两种形态)。
2026-11-02 11:29:14 +08:00
qiqi 3f3bd5690b feat(style-source): 变量全部平铺,去掉「展开其余 N 个变量」按钮 (1.0.4)
用户反馈:折叠按钮的「收起」状态容易让人以为变量就这几个,且要多点一次。

- 删掉 VAR_SHOW=6 的折叠逻辑与 .iwb-ss-vartoggle / .iwb-ss-varmore 相关代码样式
- 有多少占位符就平铺多少输入框,详情页本身可滚动(Vigo 那批最多 24 个也能撑住)
- harness:删「先给 6 个 / 折叠默认收起 / 点展开后出现」3 条,换成
  「8 个输入框全可见且无折叠按钮」;顺手修正 2 条随上游数据整改失效的样本断言
  (mondrian 8 个已全部有声明 → 改断言中英混写声明都能对上;
   婚礼那 3 个也不再是零声明 → 改断言标签可读)
2026-11-02 11:04:25 +08:00
qiqi 005c0307a6 docs(style-source): 指向数据仓的变量制作规范
链接 docs/PROMPT_VARIABLES_SPEC.md(数据仓),并把「有槽位但零声明」的
计数从 78 更正为实测 75。
2026-11-02 10:29:56 +08:00
qiqi c3e2625ac8 feat(style-source): 变量改按提示词占位符识别,不再依赖数据声明 (1.0.3)
「有的风格有变量、有的没有」的根因在数据:线上 970 条 variables 里 625 条的值只是
人话描述(没有花括号),旧逻辑拿它当占位符名去找 `{人话}`,永远找不到;
反过来还有 78 个风格提示词里明明有 {xxx} 却一条都没声明。结果是声明了的是摆设、
没声明的干脆不出输入框。

- varKeys 改成「扫 prompt 里的 {占位符}」为准,variables 只负责配标签:
  · 值带花括号(新写法)→ 直接命中
  · 值是描述 / key 带反引号(Vigo 导入数据)→ 拿 key 兜底找占位符,标签剥掉 ` 和 *
  · 两边都对不上 → 照常出输入框,标签退化成占位符名(浅色斜体标记)
- 输入框最多先摆 6 个,其余折进「展开其余 N 个变量」(Vigo 单条提示词最多 24 个占位符)
- harness 新增 6 条:未声明也给输入框 / 反引号剥离 / 不造死输入框 / 声明落空退回占位符名 / 折叠与展开 / 无占位符不摆空框
- README 补「变量」格式规范(花括号、variables 必须是列表、别用 [方括号])
2026-11-02 10:22:18 +08:00
qiqi 4f7bed96c6 fix(style-source): 手动拉高提示词节点时文字不再卡在 240px (1.0.2)
上一版注入的 `.iwb-node .iwb-textarea-plain{max-height:240px}` 把宿主
`.iwb-node-fixed .iwb-textarea{max-height:none;height:auto!important}` 盖掉了:
两者特异性同为 (0,2,0),插件样式注在 style.css 之后 ⇒ 上限赢。用户拉高节点
后文字仍停在 240px,下面一大片空白。

- 上限改为只作用于 `.iwb-node:not(.iwb-node-fixed)`(node.h 有值 = 手动拉过尺寸),
  并补 `.iwb-node.iwb-node-fixed .iwb-textarea-plain{max-height:none}` 兜底
- harness:合成宿主补抄 style.css 的 fixed 规则;新增 2 条断言(文本域随节点撑满 / maxH=none)
- 实测 273px 默认节点仍限 240 内滚动;拉高到 522 时 textarea 撑到 492,无裁切
2026-11-02 10:06:21 +08:00
qiqi 99717eb5e8 feat(style-source): 分类 chips 随面板宽度换行 + 长提示词节点内滚动 (1.0.1)
分类 chips:
- 由「单行 + 横向滚动 + scrollbar 隐藏」改为 flex-wrap:宽档一行铺完,窄档折两三行,
  右边几类不再永远看不见(用户以为只有 7 个分类)
- 名称/数量拆 span,窄档(<480)只藏数量后缀,少折一行
- harness 新增 4 条守门:chips 全部落在容器内 / 窄档多行 / 宽档一行 / 数量后缀随档显隐

长提示词:
- 宿主 autoGrow 把 textarea 高度设成 scrollHeight 且无上限,一条长提示词会把节点拉成
  两米高柱子;插件挂载时注入 `.iwb-node .iwb-textarea-plain{max-height:240px}`(幂等、
  只碰节点内纯文本域,不动宿主弹窗),节点尺寸固定、超出部分节点内滚动,全文走「放大编辑」⌘E
- 新增设置项 promptMaxH(120~800,默认 240);插入时长文本额外提示一次
- harness 新增 3 条:样式注入 / 内联 height=1200 被压到 240 / overflow-y 为 auto
2026-11-02 09:50:25 +08:00
qiqi 98f66ccaf8 fix(style-source): 修面板在真实宿主里被撑宽裁切 + 容器尺寸兜底
- 根因:.iwb-full-panel-plugin 是裸 div(宿主无样式),flex 子项 min-width 默认 auto,
  13 个分类 chip 单行不换行的 max-content 约 955px,把容器顶到 955,
  资源中心窗口只有 918 ⇒ 搜索框/刷新按钮/chips 尾巴/状态栏全被裁在右边
- mount 时给容器补 min-width:0 + min-height:0 + height:100% + overflow:hidden
  (只给收缩许可,不写 flex:1 —— 资源中心是 flex row、侧栏是 flex column,语义不同)
- chips 自身再加 min-width:0 / max-width:100% 双保险
- harness 加两条「无水平溢出」断言(窄档/宽档),host 不再预置 min-width:0 以真实复现
- 真实站点复验:容器 918 = 面板 918,overflowX=0,卡片图片/名称全部正常
2026-11-02 09:24:11 +08:00
qiqi 38a34ff533 feat(style-source): 风格库插件(资源库面板浏览 310 个 AI 绘画风格)
- 直连 malongan.github.io 的 styles.json 与预览图(CORS *),无后端、不改宿主 CSP
- 面板宽度自适应:网格 auto-fill 列数,详情按 480px 拐点切「覆盖 body / 右侧栏」
  判定用 ResizeObserver(拖侧栏时视口不变,@media 不响应)
- 按容器建实例:宿主侧栏与放大窗口可同时渲染同一面板,各自独立 RO,数据走模块级共享
- 变量替换:{占位符} 按 variables 字段生成输入框,留空保留原占位符
- 插入:预览图 blob→dataURL→createImageNode(ref);提示词 createNode('prompt') 插选中节点右侧
- 修 grid-auto-rows 默认 auto 导致图片未加载时卡片塌成横条的坑(显式 max-content)
- 加 tools/harness.mjs(离线合成宿主)与 tools/e2e-real.mjs(真实网络冒烟)
- 已发布 KV:plugin-style-source.fd634473ee66.js(v1.0.0,integrity 校验通过)
2026-11-02 09:18:05 +08:00
qiqi c31c92d07a style(icons): 三个插件改用指定 lucide 图标(标注 pencil-ruler / 抠图 scissors / 白底图 vector-square)
- image-annotate:plugin/glue.js 的命令与节点操作 icon: layer → pencil-ruler(已重新构建 src/index.js)1.0.2 → 1.0.3
- xianyi-cutout:两条注册 icon: ref → scissors,1.0.2 → 1.0.3
- white-bg-800:两条注册 icon: fit → vector-square,1.2.0 → 1.2.1
- npm run validate:7/7 通过

注:宿主已内置同名图标(pencil-ruler / scissors / vector-square),发布到 KV 后刷新即生效。
2026-11-01 22:42:05 +08:00
qiqi 68af559a57 feat(ai-chat): 浮窗 AI 对话插件(直连本机 Magpie)
- 单文件 IIFE,直连 http://127.0.0.1:3425/v1,不走后端代理
- 动态拉取模型(按 owned_by 分组/可搜索/标视觉/显上下文窗口)
- 默认模型不写死:ctx.storage 记忆上次选择,首次自动选第一个
- 流式对话 + 附带画布选中节点图片(仅视觉模型可勾选)
- 一键写回画布提示词节点(createNode('prompt',...))
- capabilities: ['canvas','canvasWrite'];已发布到 KV
2026-10-31 23:03:21 +08:00
qiqi fca860c078 feat(batch-export): 1.2.0 行尾 JPG / PNG 单张下载
- 每行尾部常驻两个小按钮,产物生成前灰掉、生成后亮起,点一下直接落盘
- 复用同一条 Blob(downloadBlob 建 URL,10s 后 revoke),不重新编码、不打包、不增内存
- 亮/灰判据是 item.files 里真实存在的扩展名,不是当前「版本」设置 —— 避免
  「按钮亮着但点下去没有文件」;跑完双版本再改成单版本,旧 PNG 依然可下
- 灰态提示区分四种原因:未处理 / 处理中 / 失败 / 本次设置不产出该格式
- 修窄面板名称被挤成 0 宽:.iwb-bx-name 的 min-width 0 → 70px,.iwb-bx-tag 补 min-width:0
- harness 新增 7 项断言(跑前灰、跑后亮、点击触发下载与扩展名一致、仅 JPG 模式下 PNG 灰);
  版本号断言改为从 package.json 读,不再钉死 1.1.0
- e2e-site 新增 3 项(每行两个按钮、跑完全可点、点 JPG 真实下载 菜单A_800x800.jpg)
2026-10-31 12:30:08 +08:00
qiqi 605dc55fc9 feat(batch-export): 新增批量出图插件 1.1.0(本地抠图 + 白底/透明 + 双版本 + ZIP)
- 资源中心面板:参数区 + 待处理节点列表(30px 缩略图)+ 进度条 + 开始出图 + 导出 ZIP
- 串行跑节点,可选走本机抠图服务(默认 http://localhost:30092/rmbg)
- 每个节点白底/透明合成后按格式/质量/体积上限编码,双版本时输出两个文件
- 自写 STORE 模式 ZIP(流式 CRC32 + UTF-8 文件名 bit 11),不依赖外部库以符合 CSP
- 修复:布尔属性走 property 赋值为准(setAttribute('checked','false') 仍算勾选)
- 修复:MutationObserver 监测宿主容器,切 tab 时自动摘除面板,避免串页
- 修复:mount 时给宿主容器补 inline 宽度,面板撑满半屏
- 修复:makeSrcThumb/fillSrcThumbs 移入 setup(ctx) 作用域(原先访问到未定义的 ctx 被 catch 吞掉)
- .gitignore 忽略 .workbuddy/ 工作目录
2026-10-31 10:29:54 +08:00
qiqi a4701746e1 feat(white-bg-800): 1.2.0 可配置导出(尺寸/格式/质量/体积上限)+ 双版本
- 新增 8 项设置:bgSize、ratioPct、format、quality、maxKB、transparent、replace、dual
- encodeWithLimit:先按设定质量编码,超上限则在 [0.2, quality] 二分找能进上限的最高质量
- dual=true 时同时出透明 PNG + 白底 JPG,单版失败不拖累另一版
- 商品长边默认占比由 85% 调整为 80%(640/800,符合电商主图规范)
- harness 修正:ctx.log 是函数、几何断言放 ±4px 容差(JPEG 振铃)
- e2e-site 修正:SRI 支持内容寻址文件名、默认格式改 jpeg、节点 data 兼容 { __cache: url }
2026-10-31 10:29:49 +08:00
qiqi 75876f92be fix(plugin): 图片处理动作只在 ref 节点出现(不再挂 gen/out/layer)
- image-annotate 1.0.2 / white-bg-800 1.0.1 / xianyi-cutout 1.0.2

- 产图节点一个可能有多张结果或多个图层,getNodeImage 只能取 result[0],漂浮菜单里放「编辑图片」会被误读成「编辑结果图」;先「复制/插入为参考图节点」

- 命令面板通道不受影响(仍可显式调用)
2026-10-30 11:02:18 +08:00
qiqi 9e09a48285 feat(plugin): 新增 blank-canvas 空白画布插件(移植自 iwb-cutout-extension)
- 仅空白 ref 节点出现入口;11 种 1K 比例;纯白 PNG 原地填当前节点

- 与上游差异:只 1K、只填当前节点、不联动编辑器
2026-10-30 09:08:57 +08:00
qiqi d41e85e288 feat(plugin): 新增 white-bg-800 白底图插件(移植自 iwb-cutout-extension)
把选中节点的图等比缩放居中合成到正方形画布(白底/透明底),输出 <name>_<size>x<size>.png。
入口:节点漂浮菜单「白底图」(ref/out/gen)+ 右键命令「白底图:选中节点」。
设置:bgSize(800)/ratioPct(85)/transparent/replace。

有意不移植:上游 autoWhiteBg(入口即功能,不做抠图后自动转白底)、批量处理 / 下载 / 剪贴板。
修正上游 bug:上游文件名硬编码 _800x800,此处按夹取后的真实边长命名。

验证:tools/harness.mjs 40/40(本地 mock 端到端)+ tools/e2e-site.mjs 14/14
(带 CSP 的真实站点端到端,测试站与正式站均通过)。
2026-10-19 15:59:20 +08:00
qiqi 320cd6e4d0 fix(image-annotate): loadImage 不再 fetch(dataURL)(宿主 CSP connect-src 不含 data:)
带 CSP 的真站 e2e 抓出:编辑器 loadImage 用 fetch(dataURL) 转 blob URL,被
connect-src 'self' https: … 拦下 → 每次打开编辑器都产生一次 CSP 违规
(靠上游 catch 回退才没坏,功能正常、只在控制台报错)。mock 页无 CSP,永远测不出。

改为纯本地解码 atob → Uint8Array → Blob → blobURL,行为与上游一致(同样拿到
blob URL、同样载入后 revoke),且不依赖 CSP/网络。这是相对上游编辑器唯一的移植改动。

版本 1.0.0 → 1.0.1(产物字节已变,按语义升版并已在 KV 重新发布)。

顺带:
- 新增 tools/e2e-site.mjs:带 CSP 真站端到端(真 KV + 浏览器 SRI + 漂浮菜单 →
  编辑器 → 覆盖/新建)。开发用,不进 CI(CI 仍只跑 npm run validate)。
- README:写清唯一的移植改动与原因;发布段补实测踩到的坑——发布器用传入文件
  「重建」清单,必须把所有插件文件一起传,否则别的插件会被挤掉。
2026-10-19 14:13:44 +08:00
qiqi d99173321e chore(validate): entry version 与 package.json 交叉核对;README 补复杂插件约定
- 需构建的插件由 build-plugin.mjs 从 package.json 注入版本,校验器负责兜底
- 根 README 记录 plugin/ → src/index.js 的三段构建原因与 shared/ 约定
- 修 xianyi-cutout/README 里 plugins-publish.sh 的过时警示(现已产出 integrity)
2026-10-19 14:03:55 +08:00
qiqi e7b6e23f8f feat(plugin): 新增 image-annotate 标注/修图插件 + 构建链
- 编辑器逐字移植自 iwb-plaus/iwb-cutout-extension(11 模块 + 2 个 shared 文件,纯 Canvas 2D、零第三方库)
- plugin/ 存 ESM 源码,src/index.js 是构建产物(提交进仓,CI 只校验不构建)
- scripts/build-plugin.mjs:esbuild 打包 + banner/footer 手写单引号 manifest + 产物自检
- 能力 commands / nodeActions / canvas / canvasWrite;入口 = 节点漂浮菜单 + 右键命令
- 导出模式按编辑器字面量映射:replace → setNodeImage,newNode → createImageNode
2026-10-19 14:03:55 +08:00
qiqi 2b93a6bfeb docs: 更正 README 中 plugins-publish.sh 的过时警示
宿主已修 .sh 补齐 integrity,故「不要用 .sh」不再成立;改为说明两者都产 integrity、.mjs 推荐。
2026-10-19 11:05:52 +08:00
123 changed files with 54845 additions and 118 deletions

No files matched your search

+17 -1
View File
@@ -1,10 +1,26 @@
name: validate
on: [push, pull_request]
on:
push:
branches: [main]
# 只改文档/CI 自身不触发:额度按 job 分钟累计(HANDBOOK 第八节 8.2 第 3 条)
paths-ignore:
- '**/*.md'
- 'docs/**'
- '.github/**'
pull_request:
branches: [main]
workflow_dispatch:
# 连推多次时只保留最后一次,避免排队任务白烧分钟
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
validate:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
+2
View File
@@ -3,3 +3,5 @@ dist/
.DS_Store
*.log
.omo/
.workbuddy/
style-source/tools/shot-*.png
+157 -102
View File
@@ -1,144 +1,199 @@
# IWB 插件仓
# IWB 插件仓(桌面客户端)
本仓**只写插件**,不复制宿主契约。宿主(`image-workbench-web` / 工作树 `iwb-arch`)负责提供并演进
`window.IWBPluginHost` 契约;这里只消费它。
本仓**只写插件**,是桌面宿主 `image-workbench-desktop`(Tauri v2 客户端,数据全部落本机)的插件源仓。
宿主负责提供并演进 `window.IWBPluginHost` 契约,这里只消费它;本仓不复制宿主契约、不改宿主代码。
## 为什么能"不动主仓"
插件是**可信代码**:与画布同页、同源、同 JS 上下文运行(宿主动态注入 `<script>`),可读画布数据、可发网络请求。
只写你信任的插件。
插件**不复制宿主契约**,只消费 `window.IWBPluginHost`。两条落地路径**都不需要改宿主代码**:
## 插件怎么到用户手里
- **路径 A(推荐,实际采用)**:运行时从 KV 加载 —— 本仓开发 → 上传 KV → 刷新即生效(**不重编译、不部署宿主**)。
- **路径 B**:构建期并入 —— 本仓开发 → `src/plugin-<id>.js`(宿主构建**自动发现** `plugin-*.js` 并排序追加)→ 宿主 verify → 部署。
桌面客户端**不随包发布插件**,插件全部从插件市场安装到本机资料目录:
两条路都**不需要改宿主的代码 / 清单 / 快照**。详见下文「两条合入路径」与「运行时机制」。
## 两条合入路径(同一条契约,不同部署形态)
宿主(`iwb-arch`)同时提供两条路径;**当前唯一真实插件 `xianyi-cutout` 走的是路径 A**。
### 路径 A:运行时发布到 KV(推荐,本仓插件实际采用)
源码迁出主仓,经 Cloudflare Function `functions/plugins/[[path]].js` + KV(binding `PLUGINS`)**同源运行时加载**。
上传后**刷新浏览器即生效**,不重编译、不 deploy 主仓。
```bash
cd /Users/qiqi/open/github/iwb-arch
# 发布器算 SHA-256(SRI integrity)→ 写 plugins/index.json → 上传 KV;输入文件名须为 plugin-<id>.js
cp /绝对路径/<插件目录>/src/index.js /tmp/plugin-<id>.js
node scripts/plugins-publish.mjs /tmp/plugin-<id>.js --upload --version <id>=<ver>
```
本仓 <id>/src/index.js
→ 桌面仓 node scripts/sync-plugins-from-repo.js # 拷到 plugins/runtime/,内容寻址命名 + SRI
→ 桌面仓 node scripts/gen-market.js # 生成 market/index.json + market/plugins/*
→ 上传 market/ 到 NAS /vol8/web/iwb-market/ # market.maqiart.eu.org(纯静态)
→ 用户在客户端「设置 → 插件 / 市场」安装
```
- **必须用 `plugins-publish.mjs`**:它算 **SHA-256(SRI integrity)** 写进 `plugins/index.json`;宿主用 `<script integrity>` 强制校验,
**缺失/不符即拒载(fail-closed)**。
⚠️ **不要用 `plugins-publish.sh`**:它写清单时不产 `integrity`,会被 fail-closed 拒载。
- A2 Function 已在**测试站与正式站**上线;本地发布后刷新浏览器即生效。
- 市场索引:`https://market.maqiart.eu.org/index.json`,每个条目带 `sha256` 与 `integrity`。
- 安装落点:`<资料目录>/plugins/`(macOS 默认 `~/Documents/ImageWorkbench/plugins/`)。
加载时校验 sha256/integrity,**不符即拒载(fail-closed)**。
### 路径 B:构建期并入 `src/plugin-<id>.js`
```bash
cd /Users/qiqi/open/github/iwb-arch
scripts/plugins-sync.sh <本仓路径或 URL> <插件 id> [源文件,默认 dist/plugin.js] [--force]
npm run verify # 全绿
npm run deploy:test # 发到测试站
```
`scripts/build.js` 自动发现 `src/plugin-*.js`(按文件名排序追加),合入**不需要改主仓任何代码**。
`plugins-sync.sh` 会打印来源 `仓库@tag (sha)`,请把它写进宿主的提交信息,便于追溯。
## 校验(本地 + CI)
```bash
npm run validate # 校验每个插件的 ibwPlugin 契约、entry 语法、entry 内 manifest 与契约是否一致
```
`.github/workflows/ci.yml` 在 push / PR 时跑同一条命令(只读源码,不需要网络或依赖)。
开发者调试不必走市场:用「开发者模式」直接加载本机未签名代码,见下文「本地调试」。
## 插件契约(写插件前必读)
每个插件 = **一个 IIFE 文件**,加载时向宿主注册:
每个插件 = **一个 IIFE 文件**,脚本执行时向宿主注册:
```js
;(function (global) {
if (!global.IWBPluginHost) return
global.IWBPluginHost.register(manifest, function (ctx) {
'use strict'
global.IWBPluginHost.register({
id: 'hello-world', name: '示例插件', version: '0.1.0', apiVersion: 1,
capabilities: ['nodeActions', 'canvas']
}, function (ctx) {
// 在这里用 ctx 注册能力;返回 { dispose } 可选
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
```
**manifest**:`id`(`^[a-z][a-z0-9-]{2,31}$`)、`name`、`version`、`apiVersion`、`capabilities`、可选 `settings`(每项 `{type:'text'|'number'|'boolean', label, desc, default}`)。
**manifest 必填**:`id`(`^[a-z][a-z0-9-]{2,31}$`)、`name`、`version`、`apiVersion`(当前 `1`)、`capabilities`。
可选 `settings`:对象 `{ 键: { label, desc, default, type } }`,`type` 为 `text` / `number` / `boolean`。
**恒定提供**:`ctx.settings` / `ctx.log` / `ctx.storage`(按插件 id 隔离)/ `ctx.events`。
**恒定提供**(`ctx` 上一定有):
**声明式能力**(在 `capabilities` 里声明后才发放):
| API | 用途 |
|---|---|
| `ctx.settings` | `all()` / `get(k)` / `set(k,v)` / `onChange(fn)`;缺省值取 manifest 的 `settings[].default` |
| `ctx.storage` | `ctx.storage.namespace(ns)` → `{ get, set, remove, keys }`,按插件 id + 命名空间隔离 |
| `ctx.log(...)` | 写宿主日志 |
| `ctx.events` | `on(name,fn)` / `emit(name,payload)` |
| capability | `ctx.` 下的 API | 用途 |
**声明式能力**(在 `capabilities` 里声明后才发放到 `ctx`):
| capability | 挂到 ctx 的 key | 用途 |
|---|---|---|
| `commands` | `ctx.commands.register({id,title,icon,run})` | 右键菜单「插件命令」 |
| `nodeActions` | `ctx.nodeActions.register({id,title,icon,appliesTo(node),run(node)})` | 节点漂浮菜单按钮 |
| `nodeTypes` | `ctx.nodes.register({id,title,defaults,run})` | 通用插件节点 `type:'plugin'` 的变体 |
| `panels` | `ctx.ui.registerPanel({id,title,mount(el)})` | 资源中心新增插件面板 |
| `generationHooks` | `ctx.generation.use({beforeRequest,afterResult})` | 改写生图请求体 / 处理归档结果 |
| `providers` | `ctx.providers.register({id,name,baseUrl,key,models})` | 外部服务提供方(可直接当生图后端) |
| `canvas` | `ctx.canvas.getNodes()/listNodeTypes()/getSelectedNode()/getNodeImage(id)` | 只读画布(`getNodeImage` 异步直出 dataURL) |
| `canvasWrite` | `ctx.canvas.createNode(...)/createImageNode({dataUrl,name})/setNodeImage(id,dataUrl)` | 受控写画布 |
| `panels` | `ctx.ui` | `registerPanel({id,title,mount(el)})`,资源中心新增插件面板 |
| `commands` | `ctx.commands` | `register({id,title,icon,run})`,右键菜单「插件命令」 |
| `nodeActions` | `ctx.nodeActions` | `register({id,title,icon,appliesTo(node),run(node)})`,节点漂浮菜单按钮 |
| `nodeTypes` | `ctx.nodes` | `register({id,title,ports,height,color,render})`,通用插件节点变体 |
| `generationHooks` | `ctx.generation` | `use({beforeRequest,afterResult})`,改写生图请求 / 处理归档结果 |
| `providers` | `ctx.providers` | `register({id,name,baseUrl,key,models})`,外部服务提供方 |
| `canvas` | `ctx.canvas` | 只读画布:`getNodes()` / `listNodeTypes()` / `getSelectedNode()` / `getNodeImage(id)` / `screenToWorld()` |
| `canvasWrite` | `ctx.canvas`(合并) | 受控写画布:`createNode()` / `createImageNode()` / `setNodeImage()`。注意**没有 `ctx.canvasWrite`**,仍需同时声明本能力 |
**硬约束**:
- 插件是**可信代码**(无沙箱):可读画布数据、可发网络请求。只合入你信任的代码。
- **不得依赖其他插件的加载顺序**(自动发现按文件名排序,彼此独立)。
- **不得引用宿主的内部实现**(宿主的守门测试会检查:`src/*.js` 不能引用 `app.js` 定义的全局)——只用 `ctx`。
- CSP:页面只放行 `'self'` + `https:` + `http://127.0.0.1:30092` / `http://localhost:30092`。要连别的 http 地址会被拦。
未声明的能力在 `ctx` 上是 undefined,调用会抛错。插件 id 重复会被拒绝注册(先注册者生效)。
工厂抛异常会被宿主隔离;`dispose()`(以及工厂返回值里的 `dispose`)里清理你自己加的 DOM / 定时器 / 监听器。
## 目录约定
## 桌面环境约束(CSP)
```
template/ # 最小可运行插件(复制它开始)
xianyi-cutout/ # 真实插件:鲜艺抠图(A2 运行时插件,已发布到宿主 KV)
```
宿主的内容安全策略在 `image-workbench-desktop/src-tauri/tauri.conf.json`,要点:
每个插件目录含 `src/index.js`(IIFE 产物)与 `package.json`(`version` + `ibwPlugin.entry` 供人读,
`version` 用于来源追溯)。合入/发布时把 `src/index.js` 的绝对路径传给对应脚本:路径 A 传
`plugins-publish.sh` 的第二参数,路径 B 传 `plugins-sync.sh` 的第三参数(默认 `dist/plugin.js`)。
- `script-src 'self' blob:`:经典脚本 IIFE,禁 `eval` / `new Function` / CDN;blob 注入用于本地开发插件。
- `style-src 'self' 'unsafe-inline'`:样式用 JS 注入 `<style>`。
- `connect-src` 放行 `self` / `ipc:` / `https:` / `blob:` / `data:` 及本机 `127.0.0.1:30092`、`localhost:30092`(本地抠图服务)。
**其它本机端口未放行**(如 ai-chat 用的 Magpie `3425`)——要连需改宿主 CSP 并重新打包客户端。
- `img-src` / `font-src` 放行 `data:`、`blob:`,`https:`(字体仅 `data:`)。
## 运行时机制(插件怎么跑 / 为什么发布更新不用宿主)
因为 CSP 里 `connect-src` 含 `blob:`/`data:`,在客户端里 `fetch(blob:)` / `fetch(data:)` 是允许的;
但测试用的合成宿主可能按更严的策略跑,插件保留本地解码兜底更稳妥。
**运行位置**:插件与画布/生图**同页、同源、同 JS 上下文**(由 `app.js` 动态插 `<script src="/plugins/<file>">`)。
## 目录与插件清单
- **可信代码,无沙箱**:与核心同权限(可读画布、可发网络)。只合入你信任的代码。
- **插件彼此独立**:不得依赖加载顺序;生命周期由 `plugin-host.js` 管(`register` / `activate` / `deactivate` / `dispose`),
存储按插件 id **命名空间隔离**、工厂异常被 try/catch **隔离**。
- **但依赖宿主契约** `window.IWBPluginHost`(没有它 IIFE 直接 `return`)——**不是**脱离宿主的独立进程/沙箱。
顶层目录**有 `package.json` 才会被当成插件**(`scripts/validate.mjs` 的发现规则);
多插件共用的源码可放顶层 `shared/`,无需改校验器或 CI。
**发布/更新为何不用宿主**(A2 的设计核心):
| 目录 | 插件 | 形态 |
|---|---|---|
| `template/` | 最小可运行模板(复制它开始,手写单文件) | 模板 |
| `xianyi-cutout/` | 鲜艺抠图:调本机服务抠图 → 透明底节点 | 手写单文件 |
| `white-bg-800/` | 白底图:等比居中合成白底/透明大图(双版本,≤500KB) | 手写单文件 |
| `batch-export/` | 批量出图:面板 + 串行队列 + 抠图 + 合成 + ZIP / 单张下载 | 手写单文件 |
| `blank-canvas/` | 空白画布:给空 ref 节点填纯白图 | 手写单文件 |
| `image-annotate/` | 标注 / 修图:全屏单张图片编辑器(选区 / 图层 / 裁剪…) | **需构建** |
| `image-vectorize/` | 位图转矢量:potrace 单色 / 灰度描摹 → SVG / PNG | **需构建** |
| `style-source/` | 风格库:367 风格面板 → 插预览图 / 提示词 / 样式节点 | 手写单文件 |
| `ai-chat/` | AI 对话:直连本机 Magpie 网关的浮窗流式对话 | 手写单文件 · 实验/需本机 Magpie+CSP |
- 运行时**唯一数据源是 KV**:宿主 `functions/plugins/[[path]].js` 读 `env.PLUGINS`(键 `plugins/index.json` + `plugins/<file>`),
`app.js` 明说「**更新只需上传到 KV、刷新即生效**」。
- 宿主**没有**插件 id 白名单 / 硬编码清单 ⇒ 新增插件 id **不需要改宿主**。
- 宿主仓里的 `plugins/index.json` 只是**本地记录**(`dist/` 不含 `plugins/`,function 直读 KV)⇒ 加/改插件**不必**在宿主提交。
- `scripts/plugins-publish.{sh,mjs}` 只是**便利脚本**(从宿主 `wrangler.toml` 读 KV namespace id、本地算 SHA-256、`wrangler kv put`),
**不改宿主代码、不重编译、不部署宿主**。可直接用裸命令绕过:
> 桌面仓的同步脚本 `sync-plugins-from-repo.js` 里有一份**上架白名单**(当前为
> `batch-export / blank-canvas / image-annotate / image-vectorize / style-source / white-bg-800 / xianyi-cutout`)。
> **新增插件要上架市场,必须把 id 加进那份白名单**,并在桌面仓 `plugins/meta.json` 补名称 / 描述 / 图标等展示信息。
## 快速开始:5 分钟做出第一个插件
```bash
# 只需 KV namespace id(宿主 wrangler.toml 的 [[kv_namespaces]] id)
wrangler kv key put --namespace-id <PLUGINS_ID> --remote "plugins/plugin-<id>.js" --path <本仓插件文件>
wrangler kv key put --namespace-id <PLUGINS_ID> --remote "plugins/index.json" --path <清单>
cp -r template my-plugin # 复制模板
# 改 my-plugin/package.json 的 name,以及 my-plugin/src/index.js 里的 id / name
npm run validate # 校验 manifest 与 package.json 是否一致
```
**仅两个前置/例外**(都不是"改宿主功能"):
把 `my-plugin/src/index.js` 拷到 `<资料目录>/plugins/local/my-plugin/plugin.js`,
客户端「设置 → 插件」打开**开发者模式**并重启 —— 右键菜单里就能看到新命令。
本地调试免签名、免市场,改完代码重启一次即可重新加载(详见「本地调试」)。
1. **一次性前置**:A2 Function 需先在目标环境**上线一次**。正式站若未部署,`/plugins/index.json` 会走 SPA 兜底、插件不加载;
上线之后,插件发布/更新与宿主无关。
2. **新能力例外**:插件用到现有 8 项能力之外的新能力时,才需回宿主扩契约(见下节)。
## 开发、构建、校验
## 什么时候必须改宿主
```bash
npm install # esbuild 是 devDependency,只有构建时需要
| 情形 | 动主仓? |
npm run validate # 契约校验:manifest 与 package.json 一致、entry 语法、无重复 id
npm run build -- image-annotate # 需要构建的插件:ESM 源码 → 单文件 IIFE 产物
```
校验脚本是 `scripts/validate.mjs`(只读源码、不联网、无依赖),CI 配置在 `.github/workflows/ci.yml`。
**CI 只校验、不构建**:所以 `src/index.js` 产物必须提交进仓,不能只提交源码等 CI 来构建。
### 手写单文件插件
`src/index.js` 即最终产物(IIFE),改完直接 `npm run validate`。模板见 `template/`。
### 需要构建的插件(编辑器 / 多文件类)
用 ESM 写,esbuild 打成单文件 IIFE:
```
<插件>/
plugin/entry.js # 打包入口
plugin/manifest.banner.js # 手写 manifest(单引号,原样放产物最前)
plugin/manifest.footer.js # 手写注册 IIFE(原样放产物最后)
plugin/editor/…、*.css # 源码;CSS 以 text loader 内联
src/index.js # 构建产物(提交进仓,CI 只校验不构建)
```
分三段拼接的原因:esbuild 会把字符串统一改写成双引号,而校验器只认单引号 manifest,
且用「文件里第一个 `id` 字面量」判定插件 id,manifest 必须排在 bundle 之前。
`version` 只有一处真源:构建时从 `package.json` 注入 banner 的 `__PLUGIN_VERSION__`。
## 本地调试(开发者模式)
1. 把单文件产物放到 `<资料目录>/plugins/local/<插件 id>/plugin.js`。
2. 客户端「设置 → 插件」打开**开发者模式**(不开则 `plugins/local/` 下的插件不会加载)。
3. 重启客户端(插件在启动时加载);改完代码再重启一次即可重新加载。
开发者模式下的插件**不校验签名**(免 SRI / sha256),仅限本机调试;正式分发走市场。
各插件 `tools/harness.mjs` 是本地端到端测试(合成宿主 + 真实 Chromium),改完插件先跑它;
需要 Playwright(可从桌面仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定)。
## 发布到市场
前提:源码已提交,并在桌面仓完成同步与重建市场。步骤:
```bash
# 1) 本仓:改版本(package.json 与 src/index.js 的 manifest.version 保持一致)→ 构建 → 校验 → 提交
npm run build -- <需构建的插件> # 手写单文件跳过
npm run validate
# 2) 桌面仓:同步源仓产物(内容寻址命名 + SRI),再生成市场
cd /Users/qiqi/open/github/image-workbench-desktop
node scripts/sync-plugins-from-repo.js # 默认读 ../iwb-plugins-desktop
node scripts/gen-market.js
# 3) 把 market/ 上传到 NAS /vol8/web/iwb-market/(market.maqiart.eu.org)
```
- 同步脚本按白名单读取每个 `<id>/src/index.js`,生成 `plugin-<id>.<sha12>.js`(sha256 前 12 位),
重建 `plugins/index.json`;内容不变时产物名与清单完全一致(幂等,可用 `git diff` 验证)。
- `gen-market.js` 读 `plugins/index.json` + `plugins/meta.json`,写出市场索引,每个条目带 `sha256` 与 `integrity`。
- **版本两处一起改**:`package.json` 的 `version` 与 `src/index.js` 里 manifest 的 `version`(`validate` 会校验一致)。
- 发布后回读市场索引确认版本与文件哈希已更新,再在客户端市场里刷新、安装验证——不能只看命令退出码。
历史上出过「字节传了、清单没换」导致用户仍拿到旧版的事故(见 `style-source/README.md`)。
## 排障速查
| 现象 | 常见原因 / 排查方向 |
|---|---|
| **发布/更新插件**(仅用现有能力,A2 Function 已上线) | **不用**——上传 KV + 刷新即生效(见上节) |
| 只用上表能力、纯加文件 | **不用** |
| 需要**新的能力/API** | 要——那是一次性契约扩展(宿主侧) |
| 需要放宽 CSP / 改构建语义 | 要(安全或架构变更) |
| A2 Function 首次上线(正式站) | 要——一次性 `npm run deploy`(之后与插件发布无关) |
| 插件完全不加载,状态 `not-registered` | manifest 的 `id` 与产物文件名 `plugin-<id>.js` 的 id 不一致;或 `capabilities` 写错——注意能力名与 ctx key 不同(`nodeTypes` → `ctx.nodes`、`panels` → `ctx.ui`),写错会静默失效 |
| 状态 `error`,提示「脚本完整性校验失败(integrity 不符或加载失败)」 | SRI 校验不符或文件 404;重跑同步脚本并回读市场索引,确认清单指向的哈希文件确实存在 |
| 状态 `error`,提示「外部插件不可用 / 完整性校验失败(外部插件)」 | 市场条目缺 `src` 或 `integrity`;重跑 `gen-market.js` 重建索引 |
| 装了新版本却还是旧行为 | 多半是清单没更新(版本字节传了但索引没换);对照市场索引里的 `sha256` 与客户端实际加载文件算一遍 |
| 面板能开,但节点体是无样式裸 DOM / 图片铺满 | CSS 只在面板 `mount()` 里注入了——从存档直接进画布时面板从不 mount。**在脚本执行时就注入 `<style>`**(定义 `ensureStyle()` 并紧跟 CSS 常量调用),关键元素再补行内尺寸兜底 |
| 节点里输入框一输入就失焦 | `render()` 里重建了 DOM。幂等同步、不重建;输入框 `pointerdown` 阻止冒泡;`activeElement` 是自己时跳过 value 覆盖 |
| 本机服务连不上(如抠图 / Magpie) | 检查 CSP `connect-src`:桌面版只放行本机 `30092`,其它端口(如 `3425`)需改 `tauri.conf.json` 并重新打包客户端 |
| 连了多条线却只出一个任务 | 任务身份按 `ownerNodeId`(节点自己)而非 `sourceNodeId`(文本真实来源),多条路径会归约到同一 owner;这是宿主侧语义,排查时别误判为插件丢线 |
即:**契约是接口**;插件在接口内玩,宿主只是"收文件的"。**发布 ≠ 改宿主**。
遇到具体插件的问题,先去对应 `README.md` 的历史版本章节,多数坑都记着来龙去脉。
+62
View File
@@ -0,0 +1,62 @@
# AI 对话(ai-chat)
浮窗式 AI 对话插件:直接连你本机的 **[Magpie](https://github.com/yetone/magpie)**(OpenAI 兼容网关,默认 `http://127.0.0.1:3425/v1`),在画布上方开聊。不嵌网页、不走后端代理——桌面客户端没有服务端,插件直接连本机网关。
## 能力
- **模型动态拉取**:打开即从 `GET /v1/models` 拉清单,按厂商(`owned_by`)分组、可搜索、标 👁(视觉)、显示上下文窗口。
- **默认模型不写死**:用 `ctx.storage` 记忆上次选择;首次无记录时自动选清单第一个。完全跟随你的 Magpie 配置(DeepSeek / Claude 订阅 / Ollama / 免费层皆可)。
- **流式对话**:标准 OpenAI SSE,逐字渲染。
- **附带画布图片**:勾选「附带当前选中图」后,把画布当前选中节点的图随消息发出(仅当所选模型支持视觉时才可勾选;发送时实时读取选中节点与图片)。
- **写回提示词节点**:一键把最近一条 AI 回复生成画布上的新「提示词节点」(`ctx.canvas.createNode('prompt', …)`)。
## 配置
插件设置(资源中心里本插件卡片内):
| 项 | 默认 | 说明 |
|---|---|---|
| Magpie 地址 | `http://127.0.0.1:3425/v1` | 本机 Magpie 端点。改端口需同步放宽桌面宿主 `src-tauri/tauri.conf.json` 的 CSP `connect-src`。 |
| API Key | `magpie` | Magpie 走 loopback,任意值均可(只认本机)。 |
## 前置
1. 本机跑起 Magpie,并配好你想用的 provider(详见 Magpie 文档)。
2. 桌面宿主 CSP 的 `connect-src` 默认**未放行 `3425`**(只放了 `30092` 抠图端口)。
要用本插件需先在 `image-workbench-desktop/src-tauri/tauri.conf.json` 的 `connect-src` 里加
`http://127.0.0.1:3425 http://localhost:3425`,再重新打包客户端(见根 README「桌面环境约束」)。
> ⚠️ 因为 CSP 需改宿主并重新打包,本插件当前**不在市场同步白名单里**(见根 README),
> 只能以「开发者模式」本机加载使用。
## 用法
- 启用插件 → 右下角出现「AI」悬浮按钮,同时对话窗自动展开在画布上方。
- 先点模型栏选一个模型(红色状态点变绿 = 已连上 Magpie)。
- 输入消息,Enter 发送 / Shift+Enter 换行。
- 要聊图:先在画布选中一个节点,模型支持视觉时点「附带当前选中图」。
- 收到回复后点「写回提示词节点」,会在画布上(贴近选中节点处)新建一个提示词节点。
## 契约
- `capabilities: ['canvas', 'canvasWrite']`
- 无沙箱(可信代码),与画布同页同源,可发网络请求。
## 发布
手写单文件(IIFE),`src/index.js` 即产物,无需构建。本插件因需改宿主 CSP(见「前置」),
暂以开发者模式本机加载:把 `src/index.js` 放到 `<资料目录>/plugins/local/ai-chat/plugin.js`,
打开客户端开发者模式后重启。若要纳入市场,需先把 id 加进桌面仓同步脚本的白名单、改好 CSP 并重新打包客户端,
再走根 README「发布到市场」的链路。
## 状态:实验性,默认不上市场(2026-11-22 明确)
本插件**不在** `plugins/index.json` / `market/index.json` 的同步白名单里(见根 README 与 `image-workbench-desktop/scripts/sync-plugins-from-repo.js` 的 `DEV_ONLY_IDS`)。原因:
1. 依赖**本机 Magpie** 网关(默认 `127.0.0.1:3425`),多数用户没有;
2. 需要宿主 CSP `connect-src` 放行 `3425`,必须**改客户端并重新打包**才生效。
因此它只作为「开发者直装」保留:
- 目录里已有 `manifest.json`(`main` 指向 `src/index.js`);想本机试用,把整个 `ai-chat/` 放到资料目录 `plugins/ai-chat/`,并在宿主 CSP 里放行 3425 后重启;
- 不随客户端发版、不进市场,避免用户装了连不上。
+12
View File
@@ -0,0 +1,12 @@
{
"id": "ai-chat",
"name": "AI 对话",
"version": "1.0.0",
"apiVersion": 1,
"main": "src/index.js",
"description": "浮窗直连本机 Magpie(OpenAI 兼容网关)的 AI 对话插件;需本机网关 + 宿主 CSP 放行 3425 端口,默认不上市场。",
"author": "official",
"icon": "💬",
"tags": ["AI", "对话", "实验"],
"files": {}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/ai-chat",
"private": true,
"version": "1.0.0",
"description": "AI 对话:浮窗直连本机 Magpie(OpenAI 兼容网关),动态拉取模型、流式对话、附带画布选中图、一键写回提示词节点",
"ibwPlugin": {
"id": "ai-chat",
"entry": "src/index.js",
"apiVersion": 1
}
}
+612
View File
@@ -0,0 +1,612 @@
// iwb-plugin: AI 对话 —— 浮窗直连本机 Magpie(OpenAI 兼容网关,默认 http://127.0.0.1:3425/v1),
// 不嵌网页、不走后端代理(Pages Function 跑在边缘、连不到本机 127.0.0.1,故插件直连)。
// 能力:模型动态拉取(按厂商分组 / 可搜索 / 标视觉 / 显上下文窗口)、流式对话、
// 附带画布当前选中节点图片(仅当模型支持视觉时)、一键把回复写回画布「提示词节点」。
// 默认模型不写死:localStorage(ctx.storage)记忆上次选择;首次无记录时自动选清单第一个,完全跟随 Magpie 配置。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
var BASE_DEFAULT = 'http://127.0.0.1:3425/v1'
var KEY_DEFAULT = 'magpie'
// ---------- 小工具 ----------
function trimUrl(v) {
return String(v || BASE_DEFAULT).trim().replace(/\/+$/, '') || BASE_DEFAULT
}
function el(tag, attrs, kids) {
var node = document.createElement(tag)
if (attrs) {
for (var key in attrs) {
if (!Object.prototype.hasOwnProperty.call(attrs, key)) continue
var value = attrs[key]
if (value === null || value === undefined) continue
if (key === 'class') node.className = value
else if (key === 'text') node.textContent = String(value)
else if (key.slice(0, 2) === 'on') node.addEventListener(key.slice(2).toLowerCase(), value)
// checked / disabled 这类布尔属性必须走 property,否则 setAttribute('checked','false') 仍会被勾上
else if (key === 'checked' || key === 'disabled' || key === 'selected' || key === 'readOnly') node[key] = Boolean(value)
else node.setAttribute(key, String(value))
}
}
if (kids) {
for (var i = 0; i < kids.length; i++) if (kids[i]) node.appendChild(kids[i])
}
return node
}
function fmtCtx(n) {
if (!n) return ''
if (n >= 1000000) return (Math.round(n / 100000) / 10) + 'M'
if (n >= 1000) return (Math.round(n / 100) / 10) + 'K'
return String(n)
}
// ---------- 样式(沿用宿主 CSS 变量,明暗主题自适应) ----------
var CSS = [
'.iwb-ai-rt{position:fixed;z-index:2147483000;width:384px;max-width:92vw;height:560px;max-height:86vh;',
'display:flex;flex-direction:column;min-height:0;border-radius:12px;overflow:hidden;',
'background:var(--iwb-surface,#ffffff);color:var(--iwb-text,#1c2333);',
'border:1px solid var(--iwb-border,#d5d9e0);box-shadow:0 16px 48px rgba(0,0,0,.28);',
'font:13px/1.5 system-ui,-apple-system,"PingFang SC",sans-serif}',
'.iwb-ai-rt[hidden]{display:none}',
'.iwb-ai-head{display:flex;align-items:center;gap:8px;padding:9px 12px;cursor:move;',
'background:var(--iwb-layer,#f0f1f4);border-bottom:1px solid var(--iwb-border,#d5d9e0)}',
'.iwb-ai-dot{width:9px;height:9px;border-radius:50%;flex:0 0 auto;background:#9aa3b2}',
'.iwb-ai-dot-ok{background:#1d9e75}',
'.iwb-ai-dot-err{background:#d85a30}',
'.iwb-ai-dot-load{background:#e0a93b}',
'.iwb-ai-title{font-weight:600;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
'.iwb-ai-x{cursor:pointer;border:none;background:transparent;color:var(--iwb-text2,#4d5668);',
'font-size:16px;line-height:1;padding:2px 6px;border-radius:6px}',
'.iwb-ai-x:hover{background:rgba(0,0,0,.08)}',
'.iwb-ai-bar{position:relative;padding:8px 10px;border-bottom:1px solid var(--iwb-border,#d5d9e0)}',
'.iwb-ai-model{width:100%;display:flex;align-items:center;gap:6px;padding:6px 8px;border-radius:8px;',
'border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer,#f0f1f4);color:inherit;',
'font:inherit;cursor:pointer;text-align:left}',
'.iwb-ai-model:hover{border-color:#2f6fed}',
'.iwb-ai-model-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
'.iwb-ai-vision{font-size:11px;color:#2f6fed;flex:0 0 auto}',
'.iwb-ai-drop{position:absolute;left:10px;right:10px;top:calc(100% - 4px);z-index:5;',
'background:var(--iwb-surface,#fff);border:1px solid var(--iwb-border,#d5d9e0);border-radius:10px;',
'box-shadow:0 12px 32px rgba(0,0,0,.22);max-height:300px;display:flex;flex-direction:column;min-height:0;overflow:hidden}',
'.iwb-ai-drop[hidden]{display:none}',
'.iwb-ai-search{margin:8px;padding:5px 8px;border-radius:7px;border:1px solid var(--iwb-border,#d5d9e0);',
'background:var(--iwb-layer,#f0f1f4);color:inherit;font:inherit;width:calc(100% - 16px);box-sizing:border-box}',
'.iwb-ai-drop-head{display:flex;align-items:center;gap:6px;padding:0 8px 6px}',
'.iwb-ai-refresh{cursor:pointer;border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer,#f0f1f4);',
'color:inherit;font:inherit;border-radius:6px;padding:2px 8px;font-size:12px}',
'.iwb-ai-refresh:hover{border-color:#2f6fed;color:#2f6fed}',
'.iwb-ai-list{flex:1;min-height:0;overflow:auto;padding-bottom:6px}',
'.iwb-ai-group-h{padding:6px 10px 2px;font-size:11px;color:var(--iwb-text2,#4d5668);font-weight:600}',
'.iwb-ai-opt{display:flex;align-items:center;gap:6px;padding:6px 10px;cursor:pointer}',
'.iwb-ai-opt:hover{background:var(--iwb-layer,#f0f1f4)}',
'.iwb-ai-opt-sel{background:rgba(47,111,237,.12)}',
'.iwb-ai-opt-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
'.iwb-ai-opt-meta{font-size:11px;color:var(--iwb-text2,#4d5668);flex:0 0 auto;white-space:nowrap}',
'.iwb-ai-node{display:flex;align-items:center;gap:6px;padding:7px 10px;border-bottom:1px solid var(--iwb-border,#d5d9e0);',
'font-size:12px;color:var(--iwb-text2,#4d5668)}',
'.iwb-ai-node.chk-on{color:var(--iwb-text,#1c2333)}',
'.iwb-ai-node input[type=checkbox]{width:auto;margin:0;flex:0 0 auto}',
'.iwb-ai-node label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer}',
'.iwb-ai-msgs{flex:1;min-height:0;overflow:auto;padding:10px;display:flex;flex-direction:column;gap:10px;',
'background:var(--iwb-canvas-bg,#f7f8fa)}',
'.iwb-ai-msg{max-width:88%;padding:8px 10px;border-radius:10px;white-space:pre-wrap;word-break:break-word}',
'.iwb-ai-user{align-self:flex-end;background:#2f6fed;color:#fff;border-bottom-right-radius:3px}',
'.iwb-ai-assistant{align-self:flex-start;background:var(--iwb-layer,#f0f1f4);color:var(--iwb-text,#1c2333);border-bottom-left-radius:3px}',
'.iwb-ai-msgs-empty{margin:auto;color:var(--iwb-text2,#4d5668);text-align:center;font-size:12px}',
'.iwb-ai-foot{display:flex;flex-direction:column;gap:8px;padding:8px 10px;border-top:1px solid var(--iwb-border,#d5d9e0)}',
'.iwb-ai-input{width:100%;box-sizing:border-box;resize:none;min-height:54px;max-height:140px;padding:7px 9px;',
'border-radius:8px;border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer,#f0f1f4);color:inherit;font:inherit}',
'.iwb-ai-row{display:flex;align-items:center;gap:8px}',
'.iwb-ai-btns{flex:1;display:flex;gap:8px;justify-content:flex-end}',
'.iwb-ai-btn{padding:5px 12px;border-radius:7px;border:1px solid var(--iwb-border,#d5d9e0);',
'background:var(--iwb-layer,#f0f1f4);color:inherit;font:inherit;cursor:pointer;white-space:nowrap}',
'.iwb-ai-btn:hover{border-color:#2f6fed}',
'.iwb-ai-btn[disabled]{opacity:.45;cursor:not-allowed}',
'.iwb-ai-btn-primary{background:#2f6fed;border-color:#2f6fed;color:#fff}',
'.iwb-ai-btn-primary[disabled]{background:#9aa3b2;border-color:#9aa3b2}',
'.iwb-ai-toast{position:absolute;left:50%;bottom:14px;transform:translateX(-50%);',
'background:rgba(28,35,51,.92);color:#fff;padding:6px 12px;border-radius:8px;font-size:12px;',
'opacity:0;transition:opacity .2s;pointer-events:none;z-index:6}',
'.iwb-ai-toast.show{opacity:1}',
'.iwb-ai-launch{position:fixed;z-index:2147482900;right:18px;bottom:18px;width:46px;height:46px;border-radius:50%;',
'border:none;background:#2f6fed;color:#fff;font-size:20px;cursor:pointer;box-shadow:0 6px 18px rgba(47,111,237,.45)}',
'.iwb-ai-launch:hover{background:#2257c9}',
].join('')
function ensureStyle() {
try {
if (document.querySelector('style[data-iwb-ai]')) return
var style = document.createElement('style')
style.setAttribute('data-iwb-ai', '1')
style.textContent = CSS
;(document.head || document.documentElement).appendChild(style)
} catch (error) { /* 样式注入失败不影响功能 */ }
}
// ---------- 注册 ----------
global.IWBPluginHost.register({
id: 'ai-chat',
name: 'AI 对话',
version: '1.0.0',
apiVersion: 1,
capabilities: ['canvas', 'canvasWrite'],
settings: {
baseUrl: {
type: 'text',
label: 'Magpie 地址',
desc: '本机 Magpie 的 OpenAI 兼容端点,默认 http://127.0.0.1:3425/v1。改端口需同步放宽宿主 _headers 的 connect-src。',
default: BASE_DEFAULT,
},
apiKey: {
type: 'text',
label: 'API Key',
desc: 'Magpie 走 loopback,任意值均可(只认本机)。默认 magpie。',
default: KEY_DEFAULT,
},
},
}, function (ctx) {
var models = [] // [{id, owned_by, display_name, vision, context_window, reasoning}]
var modelById = {} // id -> model
var selectedModel = ''
var messages = [] // [{role:'user'|'assistant', content: string | [{type,text}|{type:'image_url',image_url:{url}}]}]
var busy = false
var dropVisible = false
var pollTimer = null
var dom = null
var lastAssistantEl = null
var removed = false
function prefs() {
try {
return ctx.storage && typeof ctx.storage.namespace === 'function' ? ctx.storage.namespace('prefs') : null
} catch (error) { return null }
}
function authHeaders() {
return {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + String(ctx.settings.get('apiKey') || KEY_DEFAULT),
}
}
function normalizeModel(m) {
var mod = m || {}
var mods = (mod.modalities && mod.modalities.input) || []
return {
id: mod.id || '',
owned_by: mod.owned_by || 'unknown',
display_name: mod.display_name || mod.id || 'unknown',
vision: mods.indexOf('image') >= 0,
context_window: mod.context_window || 0,
reasoning: !!mod.reasoning,
}
}
// ---------- 状态点 ----------
function setStatus(kind, msg) {
if (!dom) return
dom.dot.className = 'iwb-ai-dot' + (kind === 'ok' ? ' iwb-ai-dot-ok' : kind === 'error' ? ' iwb-ai-dot-err' : kind === 'loading' ? ' iwb-ai-dot-load' : '')
dom.dot.title = msg || (kind === 'ok' ? '已连接本机 Magpie' : kind === 'error' ? '无法连接本机 Magpie' : kind === 'loading' ? '正在连接…' : '未连接')
}
// ---------- 模型拉取 + 选择 ----------
function selectModel(id, save) {
selectedModel = id || ''
if (save && id) {
try { var p = prefs(); if (p) p.set('lastModel', id) } catch (error) { /* ignore */ }
}
renderModelButton()
updateNodeRow()
}
async function refreshModels() {
setStatus('loading')
try {
var base = trimUrl(ctx.settings.get('baseUrl'))
var resp = await global.fetch(base + '/models', { headers: authHeaders() })
if (!resp.ok) throw new Error('HTTP ' + resp.status)
var json = await resp.json()
var list = (json && json.data) || []
models = list.map(normalizeModel).filter(function (m) { return !!m.id })
modelById = {}
for (var i = 0; i < models.length; i++) modelById[models[i].id] = models[i]
var last = null
try { var pp = prefs(); if (pp) last = pp.get('lastModel') } catch (error) { last = null }
if (last && modelById[last]) selectModel(last, false)
else if (models.length) selectModel(models[0].id, true)
else selectModel('', false)
setStatus('ok')
} catch (error) {
models = []
modelById = {}
selectModel('', false)
setStatus('error', String((error && error.message) || error))
}
renderDropdown()
}
function currentModel() {
return modelById[selectedModel] || null
}
// ---------- 视图:模型按钮 + 下拉 ----------
function renderModelButton() {
if (!dom) return
var m = currentModel()
dom.modelName.textContent = m ? (m.display_name + (m.context_window ? ' · ' + fmtCtx(m.context_window) : '')) : (models.length ? '选择模型' : 'Magpie 无模型')
var vision = el('span', { class: 'iwb-ai-vision', text: m && m.vision ? '👁' : '' })
// 清掉旧 vision 标
var old = dom.model.querySelector('.iwb-ai-vision')
if (old && old.parentNode) old.parentNode.removeChild(old)
dom.model.insertBefore(vision, dom.modelName.nextSibling)
}
function renderDropdown() {
if (!dom) return
var filter = (dom.search.value || '').trim().toLowerCase()
dom.list.textContent = ''
if (!models.length) {
dom.list.appendChild(el('div', { class: 'iwb-ai-group-h', text: 'Magpie 未返回模型,请检查 Magpie 配置' }))
return
}
var groups = {}
var order = []
for (var i = 0; i < models.length; i++) {
var m = models[i]
var key = m.owned_by
if (!groups[key]) { groups[key] = []; order.push(key) }
if (filter && (m.display_name + ' ' + m.id + ' ' + key).toLowerCase().indexOf(filter) < 0) continue
groups[key].push(m)
}
var any = false
for (var g = 0; g < order.length; g++) {
var items = groups[order[g]]
if (!items.length) continue
any = true
dom.list.appendChild(el('div', { class: 'iwb-ai-group-h', text: order[g] }))
for (var j = 0; j < items.length; j++) {
(function (model) {
var opt = el('div', {
class: 'iwb-ai-opt' + (model.id === selectedModel ? ' iwb-ai-opt-sel' : ''),
onclick: function () { selectModel(model.id, true); setDrop(false); },
}, [
el('span', { class: 'iwb-ai-opt-name', text: model.display_name, title: model.id }),
el('span', { class: 'iwb-ai-opt-meta', text: (model.vision ? '👁 ' : '') + (model.context_window ? fmtCtx(model.context_window) : '') }),
])
dom.list.appendChild(opt)
})(items[j])
}
}
if (!any) dom.list.appendChild(el('div', { class: 'iwb-ai-group-h', text: '无匹配模型' }))
}
function setDrop(open) {
dropVisible = open
if (dom) dom.drop.hidden = !open
}
// ---------- 视图:选中节点行 + 发图开关 ----------
function selectedNode() {
try { return ctx.canvas.getSelectedNode() } catch (error) { return null }
}
function updateNodeRow() {
if (!dom) return
var m = currentModel()
var sel = selectedNode()
var canVision = !!(m && m.vision)
dom.nodeChk.disabled = !(canVision && sel)
dom.nodeLabel.textContent = sel ? ('当前选中:' + sel.name) : (canVision ? '未选中节点(无法发图)' : '当前模型不支持视觉发图')
dom.node.className = 'iwb-ai-node' + (dom.nodeChk.checked && sel ? ' chk-on' : '')
}
function attachEnabled() {
return dom && !dom.nodeChk.disabled && dom.nodeChk.checked
}
// ---------- 视图:消息 ----------
function renderMessages() {
if (!dom) return
var box = dom.msgs
box.textContent = ''
lastAssistantEl = null
if (!messages.length) {
box.appendChild(el('div', { class: 'iwb-ai-msgs-empty', text: '和本机 Magpie 的对话会出现在这里。选好模型,直接开聊。' }))
return
}
for (var i = 0; i < messages.length; i++) {
var msg = messages[i]
var text = typeof msg.content === 'string' ? msg.content : (msg.content.map(function (p) { return p.type === 'text' ? p.text : '[图片]' }).join('\n'))
var bubble = el('div', { class: 'iwb-ai-msg ' + (msg.role === 'user' ? 'iwb-ai-user' : 'iwb-ai-assistant'), text: text })
box.appendChild(bubble)
if (msg.role === 'assistant') lastAssistantEl = bubble
}
box.scrollTop = box.scrollHeight
}
function toast(text) {
if (!dom) return
dom.toast.textContent = text
dom.toast.classList.add('show')
global.setTimeout(function () { if (dom) dom.toast.classList.remove('show') }, 2200)
}
// ---------- 发送 + 流式 ----------
function setBusy(v) {
busy = v
if (dom) {
dom.send.disabled = v || !selectedModel
dom.send.textContent = v ? '生成中…' : '发送'
}
}
function warn(text) { toast(text) }
async function send() {
if (busy) return
if (!selectedModel) { warn('请先选择模型'); return }
var text = dom.input.value.trim()
var useImg = attachEnabled()
if (!text && !useImg) { warn('请输入内容,或勾选「附带当前选中图」'); return }
var content
if (useImg) {
var sel = selectedNode()
if (!sel) { warn('请先在画布选中一个节点'); return }
var img = null
try { img = await ctx.canvas.getNodeImage(sel.id) } catch (error) { img = null }
var imgUrl = img && (img.dataUrl || img.url)
if (!imgUrl) { warn('选中的节点没有可发送的图片'); return }
content = [
{ type: 'text', text: text || '(请看图)' },
{ type: 'image_url', image_url: { url: imgUrl } },
]
} else {
content = text
}
messages.push({ role: 'user', content: content })
dom.input.value = ''
renderMessages()
await runAssistant()
}
async function streamParse(resp, onDelta) {
var reader = resp.body.getReader()
var decoder = new global.TextDecoder()
var buffer = ''
while (true) {
var r = await reader.read()
if (r.done) break
buffer += decoder.decode(r.value, { stream: true })
var lines = buffer.split('\n')
buffer = lines.pop()
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim()
if (!line || line.indexOf('data:') !== 0) continue
var data = line.slice(5).trim()
if (data === '[DONE]') return
try {
var json = JSON.parse(data)
var delta = json.choices && json.choices[0] && json.choices[0].delta
if (delta && delta.content) onDelta(delta.content)
} catch (error) { /* 跳过非 JSON(如注释行) */ }
}
}
}
async function runAssistant() {
setBusy(true)
var msg = { role: 'assistant', content: '' }
messages.push(msg)
renderMessages()
var elRef = lastAssistantEl
try {
var base = trimUrl(ctx.settings.get('baseUrl'))
var body = {
model: selectedModel,
messages: messages.map(function (m) { return { role: m.role, content: m.content } }),
stream: true,
}
var resp = await global.fetch(base + '/chat/completions', {
method: 'POST',
headers: authHeaders(),
body: JSON.stringify(body),
})
if (!resp.ok) {
var detail = ''
try { detail = await resp.text() } catch (error) { detail = '' }
throw new Error('API ' + resp.status + (detail ? ':' + String(detail).slice(0, 200) : ''))
}
await streamParse(resp, function (delta) {
msg.content += delta
if (elRef) elRef.textContent = msg.content
})
setStatus('ok')
} catch (error) {
msg.content += '\n[错误] ' + String((error && error.message) || error)
if (elRef) elRef.textContent = msg.content
setStatus('error', String((error && error.message) || error))
} finally {
setBusy(false)
renderMessages()
updateWriteback()
}
}
// ---------- 写回提示词节点 ----------
function lastAssistantText() {
for (var i = messages.length - 1; i >= 0; i--) {
if (messages[i].role === 'assistant' && messages[i].content) return messages[i].content
}
return ''
}
function updateWriteback() {
if (dom) dom.write.disabled = !lastAssistantText()
}
function writeback() {
var text = lastAssistantText()
if (!text) return
var x = 200
var y = 200
try {
var sel = selectedNode()
if (sel) {
var nodes = ctx.canvas.getNodes() || []
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].id === sel.id) { x = (Number(nodes[i].x) || 0) + 48; y = (Number(nodes[i].y) || 0) + 48; break }
}
}
} catch (error) { /* 用默认坐标 */ }
var id = null
try { id = ctx.canvas.createNode('prompt', x, y, { text: text, title: 'AI 回复' }) } catch (error) { id = null }
if (id) toast('已新建提示词节点')
else toast('写回失败:createNode 返回空(提示词节点类型未注册?)')
}
// ---------- 构建浮窗 ----------
function build() {
var dot = el('span', { class: 'iwb-ai-dot' })
var title = el('span', { class: 'iwb-ai-title', text: 'AI 对话' })
var btnMin = el('button', { class: 'iwb-ai-x', text: '–', title: '最小化到悬浮按钮' })
var btnClose = el('button', { class: 'iwb-ai-x', text: '×', title: '关闭(插件停用后彻底移除)' })
var modelName = el('span', { class: 'iwb-ai-model-name', text: '连接中…' })
var modelBtn = el('button', {
class: 'iwb-ai-model',
onclick: function () { setDrop(!dropVisible) },
}, [modelName])
var search = el('input', { class: 'iwb-ai-search', type: 'text', placeholder: '搜索模型…' })
var refresh = el('button', { class: 'iwb-ai-refresh', text: '刷新', onclick: function () { refreshModels() } })
var list = el('div', { class: 'iwb-ai-list' })
var drop = el('div', { class: 'iwb-ai-drop', hidden: true }, [
search,
el('div', { class: 'iwb-ai-drop-head' }, [refresh, el('span', { class: 'iwb-ai-group-h', text: '模型(按厂商分组)' })]),
list,
])
search.addEventListener('input', function () { renderDropdown() })
var nodeChk = el('input', { type: 'checkbox' })
var nodeLabel = el('label', { text: '未选中节点' })
var nodeRow = el('div', { class: 'iwb-ai-node' }, [nodeChk, nodeLabel])
nodeChk.addEventListener('change', function () { updateNodeRow() })
var msgs = el('div', { class: 'iwb-ai-msgs' })
var input = el('textarea', { class: 'iwb-ai-input', placeholder: '输入消息,Enter 发送 / Shift+Enter 换行' })
input.addEventListener('keydown', function (e) {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send() }
})
var btnClear = el('button', { class: 'iwb-ai-btn', text: '清空', onclick: function () { messages = []; renderMessages(); updateWriteback() } })
var btnWrite = el('button', { class: 'iwb-ai-btn', text: '写回提示词节点', disabled: true, onclick: function () { writeback() } })
var btnSend = el('button', { class: 'iwb-ai-btn iwb-ai-btn-primary', text: '发送', disabled: true, onclick: function () { send() } })
var toastEl = el('div', { class: 'iwb-ai-toast' })
var root = el('div', { class: 'iwb-ai-rt', hidden: true }, [
el('div', { class: 'iwb-ai-head' }, [dot, title, btnMin, btnClose]),
el('div', { class: 'iwb-ai-bar' }, [modelBtn, drop]),
nodeRow,
msgs,
el('div', { class: 'iwb-ai-foot' }, [
input,
el('div', { class: 'iwb-ai-row' }, [
btnClear,
el('div', { class: 'iwb-ai-btns' }, [btnWrite, btnSend]),
]),
]),
toastEl,
])
// 拖拽
var drag = { on: false, dx: 0, dy: 0 }
root.querySelector('.iwb-ai-head').addEventListener('mousedown', function (e) {
if (e.target === btnMin || e.target === btnClose) return
drag.on = true
var rect = root.getBoundingClientRect()
drag.dx = e.clientX - rect.left
drag.dy = e.clientY - rect.top
document.addEventListener('mousemove', onDrag)
document.addEventListener('mouseup', offDrag)
})
function onDrag(e) {
if (!drag.on) return
var w = root.offsetWidth, h = root.offsetHeight
var left = Math.max(8, Math.min(global.innerWidth - w - 8, e.clientX - drag.dx))
var top = Math.max(8, Math.min(global.innerHeight - h - 8, e.clientY - drag.dy))
root.style.left = left + 'px'
root.style.top = top + 'px'
root.style.right = 'auto'
root.style.bottom = 'auto'
}
function offDrag() { drag.on = false; document.removeEventListener('mousemove', onDrag); document.removeEventListener('mouseup', offDrag) }
btnMin.addEventListener('click', function () { root.hidden = true; if (launchBtn) launchBtn.hidden = false })
btnClose.addEventListener('click', function () { root.hidden = true; if (launchBtn) launchBtn.hidden = false })
// 点击浮窗外部关闭下拉
document.addEventListener('click', function (e) {
if (dropVisible && root && !root.contains(e.target)) setDrop(false)
})
launchBtn = el('button', { class: 'iwb-ai-launch', text: 'AI', title: '打开 AI 对话', hidden: true, onclick: function () { root.hidden = false; launchBtn.hidden = true; refreshModels(); updateNodeRow() } })
dom = {
root: root, dot: dot, model: modelBtn, modelName: modelName, drop: drop, search: search, list: list,
nodeChk: nodeChk, nodeLabel: nodeLabel, node: nodeRow, msgs: msgs, input: input,
send: btnSend, write: btnWrite, toast: toastEl,
}
ensureStyle()
document.body.appendChild(root)
document.body.appendChild(launchBtn)
root.hidden = false // 插件激活即自动展开在画布上方
renderMessages()
updateWriteback()
refreshModels()
updateNodeRow()
// 轻量轮询选中节点(宿主无画布变更事件)
pollTimer = global.setInterval(function () {
if (removed || root.hidden) return
updateNodeRow()
}, 1500)
return root
}
var launchBtn = null
build()
return {
dispose: function () {
removed = true
if (pollTimer) { global.clearInterval(pollTimer); pollTimer = null }
if (dom && dom.root && dom.root.parentNode) { try { dom.root.parentNode.removeChild(dom.root) } catch (error) { /* ignore */ } }
if (launchBtn && launchBtn.parentNode) { try { launchBtn.parentNode.removeChild(launchBtn) } catch (error) { /* ignore */ } }
var styleTag = document.querySelector('style[data-iwb-ai]')
if (styleTag && styleTag.parentNode) { try { styleTag.parentNode.removeChild(styleTag) } catch (error) { /* ignore */ } }
},
}
})
})(typeof window !== 'undefined' ? window : globalThis)
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/album",
"private": true,
"version": "1.1.2",
"description": "相册:一个节点装多张本地图(只引用不复制),宫格自适应分页,一图一任务 / 批量两种模式批量生图",
"ibwPlugin": {
"id": "album",
"entry": "src/index.js",
"apiVersion": 1
}
}
+849
View File
@@ -0,0 +1,849 @@
// 相册节点(2026-11-26,iwb-plugin: album)
//
// 一件事:把「多个图片节点」收成一个节点——宫格装 N 张本地图,接提示词/组合做批量生图。
//
// 三条关键设计(都对宿主有依赖,别在插件里重造):
// ① 只引用不复制:item.src = { __file: '/abs/a.png' };宿主生成时才读盘(ctx.images.reference / dataUrl)
// ② 任务展开由宿主任务图做:data.outKind='images' + data.items,宿主按 albumMode 展开成 N 个任务
// (一图一任务)或分批(批量,每组 ≤12 张);本插件只负责「数据 + 界面」
// ③ 分页容量随节点尺寸实时算:拖大 = 一页装更多(装得下就隐藏分页条),缩小 = 自动多页;
// 只有 data.onlyPage 打开时才把可见区间写进 data.pageRange 交给宿主过滤
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
// 密度档位 = 目标单元格边长(px)。1.1.0 修正:旧值 {S:64, M:48, L:100} 里 M 比 S 还小,
// 于是「中格」每页装 30 张(比小格的 20 张还多),档位语义是反的。现在 S < M < L 严格递增。
const DENSITY = { S: 64, M: 80, L: 104 }
// ⚠ 下面这一组必须与 styles.css 逐个对齐(换了 box-sizing / padding 就会算错容量 ⇒ 最后一行被裁)。
// 宿主全局 * { box-sizing: border-box },所以 CSS 里写的 height 已含 padding。
const GAP = 4 // .iwb-album-grid 的 gap = --iwb-space-4
const PAD_X = 16 // 宫格左右 padding 合计(.iwb-album-grid 左右各 --iwb-space-8)
const PAD_Y = 8 // 上下 padding 合计(.iwb-album-grid 2px + 6px)
const BAR_H = 26 // 状态栏
const TOOLS_H = 25 // 工具条(padding 2+2 + 按钮 21)
const PAGER_H = 26 // 分页条 / 一页提示条
const HINT_H = 28 // 批量模式提示行(含 margin-bottom 4)
const DEFAULT_H = 470 // 注册时声明的默认高度(与 height 字段保持一致)
const THUMB_EDGE = 256
const THUMB_Q = 0.8
const IMG_EXT = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg']
const STATE = new WeakMap() // host 元素 → 渲染状态(一个容器一个实例)
// ── 小工具 ──────────────────────────────────────────────
function el (tag, attrs, kids) {
const node = document.createElement(tag)
if (attrs) for (const k in attrs) {
const v = attrs[k]
if (v === null || v === undefined || v === false) continue
if (k === 'className') node.className = v
else if (k === 'text') node.textContent = v
else if (k === 'style' && typeof v === 'object') Object.assign(node.style, v)
else if (k.slice(0, 2) === 'on' && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v)
else node.setAttribute(k, v === true ? '' : String(v))
}
for (const kid of (Array.isArray(kids) ? kids : (kids ? [kids] : []))) {
if (kid === null || kid === undefined || kid === false) continue
node.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid)
}
return node
}
// 可点击元素:宿主在节点体上的 pointerdown 会启动「拖动节点」,单击事件因此被吞。
// 所有可点击的非 input/button 元素都必须挡住 pointerdown(与 ui-node-bodies 里 stop 的用法一致)。
function onTap (el0, fn) {
el0.addEventListener('pointerdown', (e) => e.stopPropagation())
el0.addEventListener('click', (e) => { e.stopPropagation(); fn(e) })
return el0
}
function hash32 (s) {
let h = 0x811c9dc5
const str = String(s || '')
for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0 }
return ('00000000' + h.toString(16)).slice(-8)
}
const extOf = (p) => { const m = /\.([a-z0-9]{1,5})$/i.exec(String(p || '')); return m ? m[1].toLowerCase() : '' }
const isImagePath = (p) => IMG_EXT.indexOf(extOf(p)) >= 0
const fileRefOf = (src) => (src && typeof src === 'object' && typeof src.__file === 'string') ? src.__file : ''
const nameOf = (p) => String(p || '').replace(/^.*[\\/]/, '')
const str = (v) => (v == null ? '' : String(v))
// ── 缩略图(插件私有缓存,几十 KB/张,不碰画布存储)────────────
const thumbNameOf = (key) => 't-' + hash32(key) + '.jpg'
// 缩略图缓存键(1.1.0 修「串味」):旧实现是 `fileRefOf(src) || it.name`,一旦固化(src 变成
// {__blob})或从别处导入,路径就没了 ⇒ 键退化成纯文件名 ⇒ 不同目录下的 1.png 共用同一张缩略图。
// 现在按引用本身取键:路径 → 路径;blob/cache → 各自 id;dataURL → 内容哈希;只有都没有才退回文件名。
function thumbKeyOf (it) {
const src = (it && it.src) != null ? it.src : it
const path = fileRefOf(src)
if (path) return 'f:' + path
if (src && typeof src === 'object') {
if (typeof src.__blob === 'string' && src.__blob) return 'b:' + src.__blob
if (typeof src.__cache === 'string' && src.__cache) return 'c:' + src.__cache
}
if (typeof src === 'string' && src) {
if (src.length > 4096) return 'd:' + hash32(src.slice(0, 2048) + src.slice(-2048) + ':' + src.length)
return 'd:' + hash32(src)
}
const n = (it && (it.name || it.size)) || ''
return 'n:' + str(n)
}
function makeThumb (dataUrl) {
return new Promise((resolve) => {
try {
const img = new Image()
img.onload = () => {
try {
const scale = Math.min(1, THUMB_EDGE / Math.max(img.naturalWidth || 1, img.naturalHeight || 1))
const w = Math.max(1, Math.round((img.naturalWidth || 1) * scale))
const h = Math.max(1, Math.round((img.naturalHeight || 1) * scale))
const cv = document.createElement('canvas')
cv.width = w; cv.height = h
const c2 = cv.getContext('2d')
c2.drawImage(img, 0, 0, w, h)
resolve(cv.toDataURL('image/jpeg', THUMB_Q))
} catch (e) { resolve('') }
}
img.onerror = () => resolve('')
img.src = dataUrl
} catch (e) { resolve('') }
})
}
// ── 容量:随节点宽高实时算(放大 = 一页装更多)────────────────
function capacityOf (width, height, density, hasHint) {
const target = DENSITY[density] || DENSITY.S
const innerW = Math.max(0, width - 4 - PAD_X)
const innerH = Math.max(0, height - 4 - BAR_H - TOOLS_H - PAGER_H - (hasHint ? HINT_H : 0) - PAD_Y)
const cols = Math.max(1, Math.floor((innerW + GAP) / (target + GAP)))
const cell = Math.floor((innerW - (cols - 1) * GAP) / cols) || target
const rows = Math.max(1, Math.floor((innerH + GAP) / (cell + GAP)))
return { cols, rows, cell: Math.max(20, cell), capacity: Math.max(1, cols * rows) }
}
function measure (host) {
const rect = host.getBoundingClientRect()
return { width: Math.round(rect.width || 0), height: Math.round(rect.height || 0) }
}
// ── 数据读写 ────────────────────────────────────────────
function itemsOf (node) {
const d = (node && node.data) || {}
return Array.isArray(d.items) ? d.items : []
}
function update (props, node, patch, snapshot) {
try { if (snapshot && typeof props.onSnapshot === 'function') props.onSnapshot() } catch (e) { /* 撤销快照失败不影响写入 */ }
try { props.onUpdate(node.id, patch) } catch (e) { /* 宿主不可写时保持只读 */ }
}
// ── 外壳 ────────────────────────────────────────────────
function buildShell (ctx, node, props, host) {
const st = {
nodeId: node.id,
thumbs: new Map(), // key → dataURL(内存缓存)
pending: new Map(), // key → Promise(并发去重:格子挂载和预生成会同时要同一张)
missing: new Set(), // 失联文件的 key
busy: '',
checkedMissing: false,
sig: '',
cap: null, // 最近一次容量计算(拖拽排序换算页码要用)
}
const bar = el('div', { className: 'iwb-album-bar' })
const track = el('span', { className: 'iwb-album-track' }, el('i', null))
const modeLabel = el('label', { className: 'iwb-album-toggle' }, track, document.createTextNode('一图一任务'))
modeLabel.addEventListener('pointerdown', (e) => e.stopPropagation())
modeLabel.addEventListener('click', (e) => {
e.stopPropagation()
// ⚠ 必须读 st.node(每次 sync 更新),不能读 buildShell 捕获的 node ——
// 那是**挂载时**的旧数据,连点两次会一直算出同一个 next(实测:永远停在批量)。
const cur = st.node || node
const d = (cur && cur.data) || {}
const next = d.albumMode === 'batch' ? 'per-image' : 'batch'
update(st.props || props, cur, { albumMode: next })
})
const count = el('span', { className: 'iwb-album-count' })
// 一键清空(2026-11-26 用户需求):只清本节点持有的 items,删源文件与画布存储一概不碰。
// 走 snapshot:true ⇒ ⌘Z 能整批恢复,所以不加二次确认弹窗(多一步点击反而更烦)。
const btnClear = el('button', { className: 'iwb-album-btn iwb-album-clear', title: '清空相册(⌘Z 可撤销;不会删除磁盘上的原文件)' }, '清空')
bar.appendChild(modeLabel); bar.appendChild(count); bar.appendChild(btnClear)
const btnAdd = el('button', { className: 'iwb-album-btn', title: '选择本地图片(桌面端只引用,不复制字节)' }, '+ 添加图片')
const btnDir = el('button', { className: 'iwb-album-btn', title: '按文件夹批量添加' }, '文件夹')
const btnSettle = el('button', { className: 'iwb-album-btn', title: '把引用复制进画布存储(删源文件/分享画布前用)' }, '固化')
const seg = el('span', { className: 'iwb-album-seg' })
const segs = {}
for (const key of ['S', 'M', 'L']) {
const s = onTap(el('span', { title: key === 'S' ? '小格(默认)' : (key === 'M' ? '中格' : '大格') }, key), () => update(st.props || props, st.node || node, { density: key }))
segs[key] = s; seg.appendChild(s)
}
const tools = el('div', { className: 'iwb-album-tools' }, [btnAdd, btnDir, btnSettle, seg])
const hint = el('div', { className: 'iwb-album-hint' })
const grid = el('div', { className: 'iwb-album-grid' })
const empty = el('div', { className: 'iwb-album-empty' }, [
el('div', { className: 'box' }, '+'),
el('div', null, '把图片拖到这里,或点「添加图片」选本地文件'),
el('div', { style: { fontSize: '10px', opacity: '.85' } }, '支持 PNG / JPG / WebP / GIF / AVIF / SVG'),
])
const pager = el('div', { className: 'iwb-album-pager' })
const onepage = el('div', { className: 'iwb-album-onepage' }, '全部图片一页展示')
// 节点内 hover 预览层已于 1.1.1 移除(用户实测:鼠标移到放大镜上时预览层盖住图标,反而点不到)。
// 现在只看大图走「点击放大镜 → 宿主全屏预览(props.onPreview)」,点图片外或 Esc 自动退出。
host.textContent = ''
const root = el('div', { className: 'iwb-album' }, [bar, tools, hint, grid, empty, pager, onepage])
host.appendChild(root)
Object.assign(st, { root, bar, track, count, btnClear, btnAdd, btnDir, btnSettle, segs, grid, empty, pager, onepage, hint })
// 按钮绑定(用闭包里的当前 node/props:每次 sync 会更新 st.node/st.props)
btnAdd.addEventListener('pointerdown', (e) => e.stopPropagation())
btnAdd.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, false) })
btnDir.addEventListener('pointerdown', (e) => e.stopPropagation())
btnDir.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, true) })
btnSettle.addEventListener('pointerdown', (e) => e.stopPropagation())
btnSettle.addEventListener('click', (e) => { e.stopPropagation(); settleAll(ctx, st) })
btnClear.addEventListener('pointerdown', (e) => e.stopPropagation())
btnClear.addEventListener('click', (e) => { e.stopPropagation(); clearAll(ctx, st) })
// 拖拽入图:桌面端拿不到绝对路径 ⇒ 按「方案 1」复制进画布存储
host.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation() })
host.addEventListener('drop', (e) => {
e.preventDefault(); e.stopPropagation()
const files = Array.from((e.dataTransfer && e.dataTransfer.files) || [])
if (files.length) importDropped(ctx, st, files)
})
return st
}
// ── 同步(宿主每次重渲染都会调用;必须可增量)──────────────────
function sync (ctx, st, node, props) {
st.node = node; st.props = props
const d = (node && node.data) || {}
const items = itemsOf(node)
const density = DENSITY[d.density] ? d.density : 'S'
const mode = d.albumMode === 'batch' ? 'batch' : 'per-image'
// 尺寸来源:**只认显式 node.h 或变体默认高度**(2026-11-26 修"插入后慢慢变矮")。
// ⚠ 绝不能用 props.measuredH / 自身 getBoundingClientRect():插件节点体是内容撑开的,
// 我们按它写回高度 ⇒ 卡片变矮 ⇒ 下次量到更矮 ⇒ 一路缩水。
// 拖拽调整尺寸时宿主会把新高度写进 node.h,那才是权威值。
const measured = measure(st.root)
const cardW = Number(node.w) || measured.width || 300
const cardH = Number(node.h) || DEFAULT_H
const wantH = Math.max(120, Math.round(cardH) - 4) + 'px'
if (st.root.style.height !== wantH) st.root.style.height = wantH
const cap = capacityOf(cardW, cardH, density, mode === 'batch')
st.cap = cap // 拖拽排序换算「本页第 i 格 → 全局第几格」要用(旧代码用格子数,把「+添加」也算进去了)
const pages = Math.max(1, Math.ceil(items.length / cap.capacity))
const page = Math.max(0, Math.min(pages - 1, Number(d.page) || 0))
const from = page * cap.capacity
const to = Math.min(items.length, from + cap.capacity)
const selected = items.filter((it) => it && it.on !== false).length
// 一图一任务开关 / 计数 / 密度高亮 / 固化可用性
st.track.className = 'iwb-album-track' + (mode === 'per-image' ? ' on' : '')
st.count.innerHTML = ''
st.count.appendChild(document.createTextNode('已选 '))
st.count.appendChild(el('b', null, String(selected)))
st.count.appendChild(document.createTextNode('/' + items.length + ' · 每页 ' + cap.capacity))
for (const k in st.segs) st.segs[k].className = (density === k ? 'on' : '')
const hasFileRef = items.some((it) => fileRefOf(it && it.src))
st.btnSettle.style.display = hasFileRef ? '' : 'none'
// 「文件夹」只在能做路径引用的宿主里有意义(桌面端)。旧写法 `canReference() || true` 恒真,
// 于是在网页版点它永远没反应。网页版仍可用「+ 添加图片」走文件选择器。
const canRef = !!(ctx.images && typeof ctx.images.canReference === 'function' && ctx.images.canReference())
st.btnDir.style.display = canRef ? '' : 'none'
st.btnClear.style.display = items.length ? '' : 'none'
if (st.busy) { st.btnAdd.textContent = st.busy } else { st.btnAdd.textContent = '+ 添加图片' }
// 批量模式提示:N 张 → M 个任务(每组 ≤ 12)
if (mode === 'batch' && items.length) {
st.hint.style.display = ''
st.hint.innerHTML = ''
st.hint.appendChild(document.createTextNode('整本一次请求:'))
st.hint.appendChild(el('b', null, items.length + ' 张 → ' + Math.ceil(items.length / 12) + ' 个任务'))
st.hint.appendChild(document.createTextNode('(每组 ≤ 12 张)'))
} else st.hint.style.display = 'none'
// 分页条 / 一页展示
// 空节点不再显示「全部 0 张一页展示」那条灰条(2026-11-26):它压着空态提示,说的还是废话。
const showPager = pages > 1
const showOne = !showPager && items.length > 0
st.pager.style.display = showPager ? '' : 'none'
st.onepage.style.display = showOne ? '' : 'none'
if (showOne) st.onepage.textContent = '全部 ' + items.length + ' 张一页展示 · 无需翻页'
if (showPager) {
st.pager.innerHTML = ''
const pg = el('span', { className: 'iwb-album-pg' })
const prev = onTap(el('span', { title: '上一页' }, '‹'), () => { if (page > 0) update(st.props, st.node, { page: page - 1 }) })
const next = onTap(el('span', { title: '下一页' }, '›'), () => { if (page < pages - 1) update(st.props, st.node, { page: page + 1 }) })
pg.appendChild(prev); pg.appendChild(el('b', null, (page + 1) + '/' + pages)); pg.appendChild(next)
st.pager.appendChild(pg)
const only = el('label', { className: 'iwb-album-mini' }, [
el('span', { className: 'iwb-album-track' + (d.onlyPage === true ? ' on' : '') }, el('i', null)),
document.createTextNode('仅本页参与'),
])
only.addEventListener('pointerdown', (e) => e.stopPropagation())
only.addEventListener('click', (e) => {
e.stopPropagation()
update(st.props, st.node, { onlyPage: !(d.onlyPage === true) })
})
st.pager.appendChild(only)
}
// 仅本页参与:把可见区间写回 data.pageRange(宿主任务图据此过滤;关闭时清掉)
const wantRange = (d.onlyPage === true) ? [from, to] : null
const curRange = Array.isArray(d.pageRange) ? d.pageRange : null
const rangeChanged = (!!wantRange !== !!curRange) || (wantRange && curRange && (wantRange[0] !== curRange[0] || wantRange[1] !== curRange[1]))
if (rangeChanged || (Number(d.page) || 0) !== page) {
update(st.props, st.node, { page: page, pageRange: wantRange })
}
// 宫格(签名不变就不重建:避免每帧重排导致闪烁/丢拖拽态)
const sig = [node.id, density, page, cap.capacity, mode, items.length, d.onlyPage === true ? 1 : 0,
items.map((it) => thumbKeyOf(it) + (it && it.on === false ? ':0' : ':1')).join(','), Array.from(st.missing).join(',')].join('|')
if (sig !== st.sig) {
st.sig = sig
st.grid.innerHTML = ''
st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)'
if (!items.length) {
st.grid.style.display = 'none'; st.empty.style.display = ''
} else {
st.grid.style.display = ''; st.empty.style.display = 'none'
for (let i = from; i < to; i++) st.grid.appendChild(cellOf(ctx, st, items[i], i, mode))
if (to - from < cap.capacity) {
const add = el('button', { className: 'iwb-album-cell iwb-album-add', title: '添加图片' }, [el('b', null, '+'), el('span', null, '添加')])
add.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, st.root, false) })
st.grid.appendChild(add)
}
}
} else {
st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)'
}
// 失联检测(每个节点一次;文件被移动/删除时给出明确提示)
if (!st.checkedMissing && items.some((it) => fileRefOf(it && it.src))) {
st.checkedMissing = true
checkMissing(ctx, st, items).then((changed) => { if (changed) { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } } })
}
}
// ── 单元格 ──────────────────────────────────────────────
// 放大镜图标(内联 SVG,CSP 禁外部资源):圆 + 手柄,10px 下仍看得清
function zoomIcon () {
const NS = 'http://www.w3.org/2000/svg'
const mk = (tag, attrs) => {
const n = document.createElementNS(NS, tag)
for (const k in attrs) n.setAttribute(k, attrs[k])
return n
}
const svg = mk('svg', { viewBox: '0 0 24 24', 'aria-hidden': 'true' })
svg.appendChild(mk('circle', { cx: 10, cy: 10, r: 7, fill: 'none', stroke: 'currentColor', 'stroke-width': 2.4 }))
svg.appendChild(mk('path', { d: 'M15.2 15.2 21 21', fill: 'none', stroke: 'currentColor', 'stroke-width': 2.4, 'stroke-linecap': 'round' }))
return svg
}
function cellOf (ctx, st, it, index, mode) {
const src = it && it.src
const path = fileRefOf(src)
const key = thumbKeyOf(it)
const on = !(it && it.on === false)
const missing = path && st.missing.has(path)
const btn = el('button', {
className: 'iwb-album-cell' + (on ? ' sel' : ' off') + (missing ? ' missing' : ''),
title: (it && it.name ? it.name : ('图 ' + (index + 1))) + (missing ? '(文件已不在原位置:点一下重新定位)' : ''),
})
const img = el('img', { alt: '', draggable: 'false' })
const cached = st.thumbs.get(key)
if (cached) img.src = cached
// 不设 img.src = '':空字符串会向页面 URL 发一次请求(控制台 ERR_UNKNOWN_URL_SCHEME)。
// 不设 src 属性时 <img> 什么都不做,缩略图到了再赋上即可。
else loadThumb(ctx, st, it, key).then((url) => { if (url && img.isConnected !== false) img.src = url })
btn.appendChild(img)
btn.appendChild(el('span', { className: 'iwb-album-idx' }, String(index + 1)))
// 批次角标(右上角那个「1」)已删除:顶栏「N 张 → M 个任务」已经说清楚,角标是重复信息,
// 还会和删除按钮抢同一个角。位置让给了 ×。
const del = el('span', { className: 'iwb-album-del', title: '移除(不删除磁盘上的原文件)' }, '×')
del.addEventListener('pointerdown', (e) => e.stopPropagation())
del.addEventListener('click', (e) => {
e.stopPropagation()
const items = itemsOf(st.node).slice()
items.splice(index, 1)
// 删除后留在当前页(旧实现硬编码 page:0,第 2 页删一张直接跳回第 1 页)。
// 只做「页数变少时往回收」,正常情况 page 不动。
const capNow = st.cap || { capacity: 20 }
const pagesNow = Math.max(1, Math.ceil(items.length / capNow.capacity))
const pageNow = Math.max(0, Number((st.node.data || {}).page) || 0)
update(st.props, st.node, { items: items, page: Math.min(pageNow, pagesNow - 1) }, true)
})
btn.appendChild(del)
// 放大镜(右下角):点开插件自带的全屏查看器,可 ← → 切换整本相册(1.1.2)。
// 1.1.1 的 hover 预览已废(那层会盖住放大镜本身)。
const zoom = el('span', { className: 'iwb-album-zoom', title: '查看大图(← → 切换,点击空白处或 Esc 关闭)' }, zoomIcon())
zoom.addEventListener('pointerdown', (e) => e.stopPropagation())
zoom.addEventListener('click', (e) => { e.stopPropagation(); openFull(ctx, st, index) })
btn.appendChild(zoom)
btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btn.addEventListener('click', (e) => {
e.stopPropagation()
if (missing) { relocate(ctx, st, index); return }
const items = itemsOf(st.node).slice()
if (!items[index]) return
items[index] = Object.assign({}, items[index], { on: !on })
update(st.props, st.node, { items })
})
// 拖拽排序
btn.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return
const startX = e.clientX, startY = e.clientY
let moved = false
const target = { index: index }
const onMove = (ev) => {
const dx = ev.clientX - startX, dy = ev.clientY - startY
if (!moved && Math.abs(dx) + Math.abs(dy) < 5) return
moved = true
btn.classList.add('dragging')
const cells = Array.from(st.grid.querySelectorAll('.iwb-album-cell'))
let hit = cells.length - 1
for (let i = 0; i < cells.length; i++) {
const r = cells[i].getBoundingClientRect()
if (ev.clientX < r.left + r.width / 2 + (r.width * 0.1) && ev.clientY < r.bottom && ev.clientX > r.left - r.width) { hit = i; break }
}
cells.forEach((c, i) => c.classList.toggle('dropbefore', i === hit))
target.index = hit
}
const onUp = () => {
document.removeEventListener('pointermove', onMove)
document.removeEventListener('pointerup', onUp)
btn.classList.remove('dragging')
Array.from(st.grid.querySelectorAll('.dropbefore')).forEach((c) => c.classList.remove('dropbefore'))
if (!moved) return
const items = itemsOf(st.node).slice()
// 1.1.0 修跨页错位:本页起点 = page × **每页容量**(旧代码乘的是「本页格子数」,而格子数里
// 还含末尾那个「+添加」格 ⇒ 第 2 页永远算少一格,把 21 号拖到第 2 位会插到全局第 13 位)。
const capNow = st.cap || { capacity: 20 }
const pageNow = Math.max(0, Number((st.node.data || {}).page) || 0)
const pageStart = pageNow * capNow.capacity
const realCount = Math.min(capNow.capacity, Math.max(0, items.length - pageStart))
const srcIndex = index
let dest = pageStart + Math.min(target.index, realCount)
if (dest === srcIndex || dest < 0) return
const [movedItem] = items.splice(srcIndex, 1)
if (dest > srcIndex) dest -= 1
items.splice(Math.max(0, Math.min(items.length, dest)), 0, movedItem)
update(st.props, st.node, { items: items }, true)
}
document.addEventListener('pointermove', onMove)
document.addEventListener('pointerup', onUp)
})
return btn
}
// ── 缩略图取用:内存 → 插件文件 → 现做 ───────────────────
// 并发去重(1.1.0):格子一挂载就各自要缩略图,而 addPaths 又顺序预热一遍 ⇒ 同一张图会被读两次盘。
// 用 pending 表把同 key 的请求合成一个 Promise(否则导入 30 张会解 60 次原图,内存直接翻倍)。
async function loadThumb (ctx, st, it, key) {
if (st.thumbs.has(key)) return st.thumbs.get(key)
const flight = st.pending && st.pending.get(key)
if (flight) return flight
const p = loadThumbInner(ctx, st, it, key).finally(() => { if (st.pending) st.pending.delete(key) })
if (st.pending) st.pending.set(key, p)
return p
}
async function loadThumbInner (ctx, st, it, key) {
if (st.thumbs.has(key)) return st.thumbs.get(key)
const name = thumbNameOf(key)
try {
if (ctx.files) {
const got = await ctx.files.get(name)
if (got && got.ok && got.url) { st.thumbs.set(key, got.url); return got.url }
}
} catch (e) { /* 没缓存就现做 */ }
let dataUrl = ''
const src = it && it.src
try {
if (fileRefOf(src)) dataUrl = await ctx.images.dataUrl(src)
else if (typeof src === 'string') dataUrl = src
else dataUrl = await ctx.images.dataUrl(src)
} catch (e) { dataUrl = '' }
if (!dataUrl) return ''
const thumb = await makeThumb(dataUrl)
if (!thumb) return ''
st.thumbs.set(key, thumb)
// 内存里已经有一张就够本会话用了;写盘失败(配额满)不影响显示
try { if (ctx.files) await ctx.files.put(name, thumb) } catch (e) { /* ignore */ }
return thumb
}
// ── 看大图:插件自带全屏查看器(1.1.2 起支持 ← → 切换)──────────
// 历史:1.1.0 做过「hover 节点内浮大图 + 点击全屏」两套,hover 层把放大镜盖住了 ⇒ 1.1.1 删掉。
// 1.1.2:宿主 props.onPreview 只收「已解析好的 URL 列表」,一本 30 张的相册要左右切换,
// 就得开窗前把 30 张原图全转成 dataURL(几十上百 MB,还可能卡住主线程)。所以改成自建查看器:
// 只解码当前这张 + 预取左右各一张(最多 3 张常驻),切换即时、内存可控。
// 交互沿用宿主那套肌肉记忆:点图片外的空白 / Esc 退出,← → 切换,滚轮也切。
const FS_KEEP = 3 // 同时保留的原图张数(当前 + 左右各一)
function closeViewer (st) {
const v = st && st.viewer
if (!v) return
st.viewer = null
try { window.removeEventListener('keydown', v.onKey, true) } catch (e) { /* ignore */ }
try { window.removeEventListener('wheel', v.onWheel, true) } catch (e) { /* ignore */ }
if (v.root && v.root.parentNode) v.root.parentNode.removeChild(v.root)
}
function openFull (ctx, st, index) {
closeViewer(st)
const items = itemsOf(st.node)
const total = items.length
if (!total) return
const pick = (i) => items[((i % total) + total) % total]
const keyAt = (i) => thumbKeyOf(pick(i))
let cur = Math.max(0, Math.min(total - 1, Number(index) || 0))
let curUrl = '' // 当前显示图的地址(复制/下载用)
let token = 0
const cache = new Map() // key → 原图 URL
const pending = new Map() // key → Promise(预取与切页会同时要同一张)
const img = el('img', { alt: '', draggable: 'false' })
const count = el('span', { className: 'iwb-album-fs-count' })
const name = el('span', { className: 'iwb-album-fs-name' })
const btnCopy = el('button', { className: 'iwb-album-fs-btn', title: '复制当前图片到剪贴板(PNG)' }, '复制')
const btnDl = el('button', { className: 'iwb-album-fs-btn', title: '下载当前图片' }, '下载')
const bar = el('div', { className: 'iwb-album-fs-bar' }, [count, name, btnCopy, btnDl])
const hint = el('div', { className: 'iwb-album-fs-hint' }, '点击空白处或按 Esc 关闭 · ← → 切换')
const btnPrev = el('button', { className: 'iwb-album-fs-nav prev', title: '上一张(←)' }, '‹')
const btnNext = el('button', { className: 'iwb-album-fs-nav next', title: '下一张(→)' }, '›')
const root = el('div', { className: 'iwb-album-fs' + (total > 1 ? '' : ' single') }, [img, btnPrev, btnNext, bar, hint])
// 原图按需读:命中缓存直接用;读盘失败就保持缩略图(不白屏、不报错)
const fullOf = (i) => {
const it = pick(i)
const key = keyAt(i)
if (cache.has(key)) return Promise.resolve(cache.get(key))
const flight = pending.get(key)
if (flight) return flight
if (!ctx.images || typeof ctx.images.dataUrl !== 'function') return Promise.resolve('')
const p = Promise.resolve(ctx.images.dataUrl(it && it.src)).then((u) => {
pending.delete(key)
if (!u) return ''
cache.set(key, u)
// 只留当前 + 左右各一张:4K 图的 dataURL 一张就几 MB,全书缓存直接爆内存
const keep = new Set([keyAt(cur), keyAt(cur + 1), keyAt(cur - 1)])
if (cache.size > FS_KEEP) for (const k of Array.from(cache.keys())) if (!keep.has(k)) cache.delete(k)
return u
}).catch(() => { pending.delete(key); return '' })
pending.set(key, p)
return p
}
const paint = (i) => {
const it = pick(i)
const my = ++token
const cached = cache.get(keyAt(i))
const thumb = st.thumbs.get(keyAt(i)) || ''
// 先用缩略图占位(切换时不会闪一块黑),原图到了再换上;缩略图也还没好就现做
if (cached) { img.src = cached; curUrl = cached }
else if (thumb) { img.src = thumb; curUrl = thumb }
else {
img.removeAttribute('src'); curUrl = ''
loadThumb(ctx, st, it, keyAt(i)).then((u) => { if (u && my === token) { img.src = u; curUrl = u } }).catch(() => {})
}
fullOf(i).then((u) => { if (u && my === token) { img.src = u; curUrl = u } }).catch(() => {})
count.textContent = (i + 1) + ' / ' + total
name.textContent = (it && it.name) || ('图 ' + (i + 1))
if (total > 1) { fullOf(i + 1).catch(() => {}); fullOf(i - 1).catch(() => {}) }
}
const go = (delta) => { cur = ((cur + delta) % total + total) % total; paint(cur) }
const close = () => closeViewer(st)
img.addEventListener('pointerdown', (e) => e.stopPropagation())
img.addEventListener('click', (e) => e.stopPropagation())
for (const [btn, delta] of [[btnPrev, -1], [btnNext, 1]]) {
btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btn.addEventListener('click', (e) => { e.stopPropagation(); go(delta) })
}
// 复制 / 下载:宿主预览层原本有这两个按钮,不能因为换成自建查看器就丢掉
const flash = (msg) => {
hint.textContent = msg
clearTimeout(flash.timer)
flash.timer = setTimeout(() => { hint.textContent = '点击空白处或按 Esc 关闭 · ← → 切换' }, 1800)
}
const toPngBlob = (url) => new Promise((resolve, reject) => {
const im = new Image()
im.onload = () => {
try {
const cv = document.createElement('canvas')
cv.width = im.naturalWidth || 1; cv.height = im.naturalHeight || 1
cv.getContext('2d').drawImage(im, 0, 0)
cv.toBlob((b) => b ? resolve(b) : reject(new Error('toBlob 失败')), 'image/png')
} catch (e) { reject(e) }
}
im.onerror = () => reject(new Error('图片加载失败'))
im.src = url
})
for (const btn of [btnCopy, btnDl]) btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btnDl.addEventListener('click', (e) => {
e.stopPropagation()
if (!curUrl) return
try {
const a = document.createElement('a')
a.href = curUrl
a.download = (pick(cur) && pick(cur).name) || ('image-' + (cur + 1) + '.png')
document.body.appendChild(a); a.click()
if (a.parentNode) a.parentNode.removeChild(a)
} catch (err) { flash('下载失败:' + String((err && err.message) || err)) }
})
btnCopy.addEventListener('click', async (e) => {
e.stopPropagation()
if (!curUrl) return
try {
const png = await toPngBlob(curUrl)
if (navigator.clipboard && typeof navigator.clipboard.write === 'function' && typeof ClipboardItem !== 'undefined') {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
} else {
// WKWebView 常没有 ClipboardItem ⇒ 走宿主的原生 arboard 通道(与图库预览同一实现)
const D = window.IWBDesktop
if (!D || !D.clipboardWriteImage || !(await D.clipboardWriteImage(png))) throw new Error('当前环境不支持图片剪贴板')
}
flash('已复制图片到剪贴板(PNG)')
} catch (err) { flash('复制失败:' + String((err && err.message) || err)) }
})
// 整个浮层吃掉指针事件:否则点空白会把画布的「取消选中/框选」一起触发
root.addEventListener('pointerdown', (e) => { e.stopPropagation(); if (e.target === root || e.target === bar) close() })
root.addEventListener('click', (e) => e.stopPropagation())
root.addEventListener('pointerup', (e) => e.stopPropagation())
root.addEventListener('dblclick', (e) => e.stopPropagation())
// 键盘:捕获阶段吃掉,避免宿主把 ← → 当成「微调节点」
const onKey = (e) => {
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close() }
else if (e.key === 'ArrowLeft') { e.preventDefault(); e.stopPropagation(); go(-1) }
else if (e.key === 'ArrowRight') { e.preventDefault(); e.stopPropagation(); go(1) }
}
// 滚轮也切(大图查看器的通用手势);40ms 节流,避免一次滑到底翻好几张
let wheelLock = 0
const onWheel = (e) => {
if (total < 2) return
e.preventDefault(); e.stopPropagation()
const now = Date.now()
if (now - wheelLock < 40) return
const d = Math.abs(e.deltaY) > Math.abs(e.deltaX) ? e.deltaY : e.deltaX
if (Math.abs(d) < 2) return
wheelLock = now
go(d > 0 ? 1 : -1)
}
document.body.appendChild(root)
paint(cur)
window.addEventListener('keydown', onKey, true)
window.addEventListener('wheel', onWheel, { passive: false, capture: true })
st.viewer = { root, onKey, onWheel }
}
// ── 一键清空 ────────────────────────────────────────────
function clearAll (ctx, st) {
const items = itemsOf(st.node)
if (!items.length) return
st.thumbs.clear(); st.pending.clear(); st.missing.clear()
st.checkedMissing = false // 清空后再导入要重新做一次失联检测
closeViewer(st) // 正在看大图时清空 ⇒ 先把浮层收掉(别留个没有数据的空查看器)
update(st.props, st.node, { items: [], page: 0, pageRange: null }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
}
// ── 导入:选择器 / 文件夹 / 拖入 / 固化 / 重新定位 ──────────
async function pickFiles (ctx, st, host, directory) {
if (st.busy) return
const items = itemsOf(st.node).slice()
// 桌面端:系统选择器给绝对路径 ⇒ 只引用(不复制字节)
if (ctx.images && ctx.images.canReference()) {
st.busy = '选择中…'; st.sig = ''; sync(ctx, st, st.node, st.props)
try {
const picked = await ctx.images.pick({ multiple: true, directory: !!directory })
st.busy = ''
if (!picked.length) { st.sig = ''; sync(ctx, st, st.node, st.props); return }
// 目录要展开成图片文件:pick 返回目录路径本身不是图片,之前直接过滤 ⇒ 「文件夹」点了没反应
let paths = []
if (directory) {
for (const dir of picked) {
try { const got = await ctx.images.listImages(dir); for (const f of (got || [])) paths.push(f) } catch (e) { /* 单个目录失败不阻断 */ }
}
} else paths = picked.slice()
if (!paths.length) { st.sig = ''; sync(ctx, st, st.node, st.props); return }
await addPaths(ctx, st, paths)
} catch (e) { st.busy = ''; st.sig = ''; sync(ctx, st, st.node, st.props) }
return
}
// 网页版:没有路径 ⇒ 退回文件选择 + 复制进画布存储
const input = document.createElement('input')
input.type = 'file'; input.accept = 'image/*'; input.multiple = true
input.style.display = 'none'
document.body.appendChild(input)
input.addEventListener('change', () => {
const files = Array.from(input.files || [])
document.body.removeChild(input)
if (files.length) importDropped(ctx, st, files)
})
input.click()
}
async function addPaths (ctx, st, paths) {
const list = paths.filter(isImagePath)
const items = itemsOf(st.node).slice()
for (let i = 0; i < list.length; i++) {
st.busy = '导入 ' + (i + 1) + '/' + list.length; st.sig = ''; sync(ctx, st, st.node, st.props)
const ref = await ctx.images.reference(list[i])
if (!ref || !ref.ok) continue
items.push({ src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
}
st.busy = ''
st.checkedMissing = false // 新图要重新做一次失联检测(否则清空后再导入,检测永远不再跑)
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
// 顺序预生成缩略图(避免一次读几十张原图造成内存尖峰)。
// 1.1.0:进度写进「+ 添加图片」按钮(旧实现 busy 在这里已经清空 ⇒ 导入 500 张时界面像卡死);
// 只改按钮文字、不重置 sig ⇒ 不触发整块宫格重建(重建 500 次比读盘本身还慢)。
for (let i = 0; i < items.length; i++) {
const it = items[i]
const key = thumbKeyOf(it)
if (!key || st.thumbs.has(key)) continue
st.busy = '缩略图 ' + (i + 1) + '/' + items.length
st.btnAdd.textContent = st.busy
await loadThumb(ctx, st, it, key)
}
st.busy = ''
st.btnAdd.textContent = '+ 添加图片'
st.sig = ''
sync(ctx, st, st.node, st.props)
}
async function importDropped (ctx, st, files) {
const items = itemsOf(st.node).slice()
for (let i = 0; i < files.length; i++) {
const f = files[i]
if (!f || !/^image\//i.test(f.type || '')) continue
st.busy = '复制 ' + (i + 1) + '/' + files.length; st.sig = ''; sync(ctx, st, st.node, st.props)
const dataUrl = await new Promise((resolve) => {
try { const r = new FileReader(); r.onload = () => resolve(String(r.result || '')); r.onerror = () => resolve(''); r.readAsDataURL(f) } catch (e) { resolve('') }
})
if (!dataUrl) continue
let res = null
try { res = await ctx.images.importDataUrl(dataUrl, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) }) } catch (e) { res = null }
if (!res || !res.ok) continue
const src = res.ref || res.data
if (!src) continue
const name = f.name || ('图 ' + (items.length + 1))
items.push({ src, name: name, size: f.size || 0, on: true })
const thumb = await makeThumb(dataUrl)
// 键必须和 cellOf / loadThumb 完全一致(thumbKeyOf),否则写进缓存也命中不到
if (thumb) {
const key = thumbKeyOf(items[items.length - 1])
st.thumbs.set(key, thumb)
try { if (ctx.files) await ctx.files.put(thumbNameOf(key), thumb) } catch (e) { /* ignore */ }
}
}
st.busy = ''
st.checkedMissing = false
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
}
// 固化:把 __file 引用换成宿主存储引用(删源文件/分享画布前用)
async function settleAll (ctx, st) {
const items = itemsOf(st.node).slice()
let done = 0
for (let i = 0; i < items.length; i++) {
const it = items[i]
const path = fileRefOf(it && it.src)
if (!path) continue
st.busy = '固化 ' + (++done) + '…'; st.sig = ''; sync(ctx, st, st.node, st.props)
try {
const res = await ctx.images.importPath(path, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) })
if (res && res.ok && (res.ref || res.data)) items[i] = Object.assign({}, it, { src: res.ref || res.data })
} catch (e) { /* 单张失败不打断整批 */ }
}
st.busy = ''
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
}
async function checkMissing (ctx, st, items) {
let changed = false
for (const it of items) {
const path = fileRefOf(it && it.src)
if (!path) continue
try {
const r = await ctx.images.stat(path)
const missing = !(r && r.ok && r.exists)
if (missing && !st.missing.has(path)) { st.missing.add(path); changed = true }
if (!missing && st.missing.has(path)) { st.missing.delete(path); changed = true }
} catch (e) { /* 检测失败按存在处理 */ }
}
return changed
}
// 失联重定位:点失联格 → 选一张同名/任意图片替换
async function relocate (ctx, st, index) {
if (!ctx.images || !ctx.images.canReference()) return
const items = itemsOf(st.node).slice()
const cur = items[index]
if (!cur) return
const paths = await ctx.images.pick({ multiple: false })
if (!paths || !paths.length) return
const ref = await ctx.images.reference(paths[0])
if (!ref || !ref.ok) return
const oldPath = fileRefOf(cur.src)
st.missing.delete(oldPath)
items[index] = Object.assign({}, cur, { src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime })
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
loadThumb(ctx, st, items[index], thumbKeyOf(items[index])).then(() => { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } })
}
// ── 注册 ────────────────────────────────────────────────
global.IWBPluginHost.register({
id: 'album',
name: '相册',
version: '1.1.2',
apiVersion: 1,
capabilities: ['nodeTypes', 'images', 'files'],
settings: {
keepOriginal: { type: 'boolean', label: '默认保留原图(不压缩)', desc: '开启后导入不进 1600 长边压缩,分辨率不损失(占用更高)。节点内可单独改。', default: true },
},
}, function (ctx) {
ctx.nodes.register({
id: 'album',
title: '相册',
icon: 'puzzle',
width: 300,
height: 470,
ports: { in: true, out: true },
defaults: { outKind: 'images', items: [], albumMode: 'per-image', density: 'S', page: 0, onlyPage: false, keepOriginal: ctx.settings.get('keepOriginal') !== false },
render: function (node, props, host) {
// 自愈(2026-11-26):旧版本/兜底路径建出来的节点可能没有 outKind,
// 那样连线规则会把相册当普通插件节点(只能连中继)。这里补写一次默认值。
try {
const d0 = node && node.data
if (d0 && d0.outKind !== 'images') {
props.onUpdate(node.id, { outKind: 'images', items: Array.isArray(d0.items) ? d0.items : [] })
}
} catch (e) { /* ignore */ }
let st = STATE.get(host)
if (!st || st.nodeId !== node.id) { st = buildShell(ctx, node, props, host); STATE.set(host, st) }
try { sync(ctx, st, node, props) } catch (e) {
// 渲染失败降级成一行可读文本(绝不让整块画布白屏)
try { host.textContent = ''; const tip = document.createElement('div'); tip.className = 'iwb-hint'; tip.textContent = '相册渲染失败:' + String((e && e.message) || e); host.appendChild(tip) } catch (e2) { /* ignore */ }
}
},
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
+82
View File
@@ -0,0 +1,82 @@
/* 相册节点体(2026-11-26)
* 宿主只给一块空容器(.iwb-plugin-node-body),所有排版由这里决定。
* 尺寸全部用像素而不是 rem:节点宽度是可拖拽的(264~600),rem 会跟着宿主字号漂移。
*/
.iwb-album { position: relative; display: flex; flex-direction: column; height: 100%; overflow: hidden; font-size: 11px; color: var(--iwb-node-text); }
.iwb-album-bar, .iwb-album-tools, .iwb-album-pager, .iwb-album-onepage {
display: flex; align-items: center; gap: var(--iwb-space-6); padding: var(--iwb-space-4) var(--iwb-space-8); flex: 0 0 auto;
}
.iwb-album-bar { border-bottom: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; }
.iwb-album-tools { padding-top: var(--iwb-space-2); padding-bottom: var(--iwb-space-2); }
.iwb-album-toggle { display: inline-flex; align-items: center; gap: var(--iwb-space-4); font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); white-space: nowrap; cursor: pointer; }
.iwb-album-track { width: 22px; height: 12px; border-radius: 999px; background: var(--iwb-border); position: relative; flex: 0 0 auto; transition: background .15s; }
.iwb-album-track i { position: absolute; top: 1.5px; left: 1.5px; width: 9px; height: 9px; border-radius: 50%; background: var(--iwb-panel); transition: left .15s; }
.iwb-album-track.on { background: var(--iwb-brand); }
.iwb-album-track.on i { left: 11.5px; }
.iwb-album-count { margin-left: auto; font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.iwb-album-count b { color: var(--iwb-node-text); font-weight: 600; }
.iwb-album-btn { height: 21px; padding: 0 var(--iwb-space-8); border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-chip); background: var(--iwb-panel); color: var(--iwb-node-text2); font-size: var(--iwb-font-2xs); display: inline-flex; align-items: center; gap: var(--iwb-space-4); cursor: pointer; white-space: nowrap; }
.iwb-album-btn:hover { border-color: var(--iwb-brand); color: var(--iwb-node-text); }
.iwb-album-btn.on { border-color: var(--iwb-brand); color: var(--iwb-node-text); }
/* 清空:常驻在顶栏最右,只有相册里有图时才出现。hover 转红是为了和「添加」一类中性操作区分开。 */
.iwb-album-clear { flex: 0 0 auto; padding: 0 var(--iwb-space-6); }
.iwb-album-clear:hover { border-color: #c0392b; color: #c0392b; }
.iwb-album-seg { margin-left: auto; display: inline-flex; border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-chip); overflow: hidden; }
.iwb-album-seg span { width: 21px; height: 21px; display: inline-flex; align-items: center; justify-content: center; font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); background: var(--iwb-panel); cursor: pointer; }
.iwb-album-seg span.on { background: var(--iwb-brand); color: var(--iwb-on-brand); }
.iwb-album-grid { display: grid; gap: var(--iwb-space-4); padding: var(--iwb-space-2) var(--iwb-space-8) var(--iwb-space-6); overflow: hidden; align-content: start; flex: 1 1 auto; min-height: 0; }
/* 格子固定正方形(2026-11-26):此前高度由图片比例决定 —— 4 张 16:9 宽图会变成 22px 细条、
竖图撑到 167px,和 capacityOf() 按方形算的容量是两套账(最后一行常被裁一半)。
aspect-ratio 让每一格高 = 宽,容量因此可精确预测,宫格也终于整齐。
padding:0 必须显式写:<button> 的 UA 默认内边距会把图顶出边框。 */
.iwb-album-cell { position: relative; aspect-ratio: 1 / 1; padding: 0; border-radius: var(--iwb-radius-chip); overflow: hidden; background: color-mix(in srgb, var(--iwb-border) 55%, transparent); border: 1px solid var(--iwb-border); cursor: grab; }
.iwb-album-cell img { width: 100%; height: 100%; object-fit: cover; display: block; -webkit-user-drag: none; }
.iwb-album-cell.off img { opacity: .38; }
/* 选中线 2px → 1px(用户:太粗)。1px 在浅底上仍分得清「选中」与「描边」。 */
.iwb-album-cell.sel { outline: 1px solid var(--iwb-brand); outline-offset: -1px; }
.iwb-album-cell.missing { outline: 1px dashed #c0392b; outline-offset: -1px; }
.iwb-album-cell.missing::after { content: '失联'; position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: var(--iwb-font-2xs); color: #c0392b; background: rgba(255,255,255,.72); }
.iwb-album-cell.dragging { opacity: .45; }
.iwb-album-cell.dropbefore { box-shadow: -3px 0 0 0 var(--iwb-brand); }
.iwb-album-idx { position: absolute; left: var(--iwb-space-2); top: var(--iwb-space-2); min-width: 14px; height: 14px; padding: 0 var(--iwb-space-4); border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-size: var(--iwb-font-2xs); display: flex; align-items: center; justify-content: center; }
/* 批次角标已移除(2026-11-26):顶栏「N 张 → M 个任务」已经说清楚,每格右上角再挂个「1」是重复信息。
位置让给删除按钮:右下角要留给放大镜。 */
.iwb-album-del { position: absolute; right: var(--iwb-space-2); top: var(--iwb-space-2); width: 15px; height: 15px; border-radius: 50%; background: var(--iwb-panel); color: var(--iwb-node-text2); font-size: 11px; line-height: 1; display: flex; align-items: center; justify-content: center; opacity: 0; cursor: pointer; }
.iwb-album-cell:hover .iwb-album-del { opacity: 1; }
/* 放大镜:右下角,hover 才出现(静息态不抢视觉,和 × 一致)。
17px 圆 / 12px 图标:再小镜片就缩成一团白点。
z-index 高于图与角标:1.1.0 时它被节点内预览层(z-index 9)盖住 ⇒ 用户反馈「滑过去就点不到」,
那层已在 1.1.1 删除;这里仍显式抬一层,避免以后再加浮层时重犯。 */
.iwb-album-zoom { position: absolute; right: var(--iwb-space-2); bottom: var(--iwb-space-2); z-index: 3; width: 17px; height: 17px; border-radius: 50%; background: var(--iwb-panel); color: var(--iwb-node-text2); display: flex; align-items: center; justify-content: center; opacity: 0; cursor: zoom-in; transition: opacity .12s; }
.iwb-album-cell:hover .iwb-album-zoom, .iwb-album-cell:focus-within .iwb-album-zoom { opacity: 1; }
.iwb-album-zoom:hover { color: var(--iwb-brand); }
.iwb-album-zoom svg { width: 12px; height: 12px; display: block; }
/* 全屏查看器(1.1.2):挂在 document.body 上,所以是 position: fixed + 自备层级。
810 = 宿主图片预览层(--iwb-z-preview: 800)之上一层,盖住画布但不抢系统弹窗。
为什么不用宿主 onPreview:那个接口只收「已解析好的 URL 列表」,整本相册要一次全转 dataURL。 */
.iwb-album-fs { position: fixed; inset: 0; z-index: 810; display: flex; align-items: center; justify-content: center; background: rgba(10, 12, 18, .92); cursor: zoom-out; }
.iwb-album-fs img { max-width: 92vw; max-height: 88vh; width: auto; height: auto; object-fit: contain; display: block; border-radius: 8px; box-shadow: 0 8px 40px rgba(0, 0, 0, .5); cursor: default; }
.iwb-album-fs-nav { position: fixed; top: 50%; transform: translateY(-50%); width: 46px; height: 64px; padding: 0; border: none; border-radius: 8px; background: rgba(255, 255, 255, .1); color: #fff; font-size: 30px; line-height: 1; display: flex; align-items: center; justify-content: center; cursor: pointer; }
.iwb-album-fs-nav:hover { background: rgba(255, 255, 255, .22); }
.iwb-album-fs-nav.prev { left: 18px; }
.iwb-album-fs-nav.next { right: 18px; }
.iwb-album-fs.single .iwb-album-fs-nav { display: none; }
/* 计数条要放「复制/下载」按钮,所以本身吃事件;点条上空白仍然算点外部(关闭) */
.iwb-album-fs-bar { position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%); display: flex; align-items: center; gap: 10px; max-width: 80vw; padding: 6px 14px; border-radius: 999px; background: rgba(255, 255, 255, .12); color: #fff; font-size: 12px; }
.iwb-album-fs-btn { height: 22px; padding: 0 9px; border: 1px solid rgba(255, 255, 255, .22); border-radius: 999px; background: rgba(255, 255, 255, .08); color: #fff; font-size: 11px; cursor: pointer; flex: 0 0 auto; }
.iwb-album-fs-btn:hover { background: rgba(255, 255, 255, .22); }
.iwb-album-fs-count { font-variant-numeric: tabular-nums; }
.iwb-album-fs-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; opacity: .72; }
.iwb-album-fs-hint { position: fixed; left: 50%; bottom: 6px; transform: translateX(-50%); color: rgba(255, 255, 255, .45); font-size: 11px; white-space: nowrap; pointer-events: none; }
.iwb-album-add { border: 1px dashed var(--iwb-border); background: transparent; color: var(--iwb-node-text2); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--iwb-space-2); font-size: var(--iwb-font-2xs); border-radius: var(--iwb-radius-chip); cursor: pointer; }
.iwb-album-add b { font-size: 15px; line-height: 1; font-weight: 600; }
.iwb-album-pager { border-top: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; }
.iwb-album-onepage { border-top: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; color: var(--iwb-node-text2); font-size: var(--iwb-font-2xs); }
.iwb-album-pg { display: inline-flex; align-items: center; border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-chip); background: var(--iwb-panel); }
.iwb-album-pg span { width: 17px; height: 17px; display: flex; align-items: center; justify-content: center; font-size: var(--iwb-font-2xs); cursor: pointer; color: var(--iwb-node-text2); }
.iwb-album-pg b { font-weight: 600; color: var(--iwb-node-text); padding: 0 2px; font-size: var(--iwb-font-2xs); }
.iwb-album-mini { display: inline-flex; align-items: center; gap: var(--iwb-space-4); margin-left: auto; font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); white-space: nowrap; }
.iwb-album-hint { margin: 0 8px 4px; padding: 4px 6px; border-radius: var(--iwb-radius-chip); background: rgba(107,114,128,.10); border: 1px solid rgba(107,114,128,.22); color: var(--iwb-node-text2); font-size: var(--iwb-font-2xs); line-height: 1.45; }
.iwb-album-hint b { color: var(--iwb-node-text); }
.iwb-album-empty { flex: 1 1 auto; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--iwb-space-6); color: var(--iwb-node-text2); font-size: 11px; text-align: center; padding: 0 var(--iwb-space-12); }
.iwb-album-empty .box { width: 66px; height: 50px; border: 1.5px dashed var(--iwb-border); border-radius: var(--iwb-radius-chip); display: flex; align-items: center; justify-content: center; font-size: var(--iwb-font-xl); color: var(--iwb-node-text2); }
+206
View File
@@ -0,0 +1,206 @@
#!/usr/bin/env node
/* album 插件自测(v1.1.0,2026-11-26)
*
* 为什么要有它:这个插件此前**零自动化测试**(宿主侧 tests/album-task-graph-test.js 只覆盖任务展开)。
* 而 1.1.0 动的是「宫格尺寸 = 分页容量」这条最脆的链:capacityOf() 里的常量必须和 styles.css 逐个对齐,
* 错 1px 就会「最后一行被裁一半」,而那种错误肉眼要盯很久才发现。这里把它变成断言。
*
* 两部分:
* 一、静态断言:源码 / 样式里的关键实现必须还在(防回归,不依赖浏览器)
* 二、算术断言:把常量段 + capacityOf / thumbKeyOf 从 IIFE 里抽出来,在 vm 里真跑
*
* 浏览器渲染验证(方形格子、裁切、点击放大)不在这里 —— 那需要 playwright,
* 跨仓依赖不适合当门禁。跑法见 README「验证」一节。
*/
import fs from 'node:fs'
import path from 'node:path'
import vm from 'node:vm'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const ROOT = path.resolve(HERE, '..')
const src = fs.readFileSync(path.join(ROOT, 'src/index.js'), 'utf8')
const css = fs.readFileSync(path.join(ROOT, 'styles.css'), 'utf8')
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
let failed = 0
const ok = (name, cond, extra) => {
if (!cond) failed++
console.log((cond ? '✓ ' : '✗ ') + name + (cond ? '' : (' » ' + (extra == null ? '' : extra))))
}
// ── 一、版本与注册契约 ───────────────────────────────────────
ok('package.json version = 1.1.2', pkg.version === '1.1.2', pkg.version)
ok('manifest.version = 1.1.2', /version:\s*'1\.1\.2'/.test(src))
ok('id = album', /id:\s*'album'/.test(src))
ok('capabilities 含 nodeTypes / images / files',
/capabilities:\s*\['nodeTypes',\s*'images',\s*'files'\]/.test(src))
ok('默认 outKind = images(宿主靠它认「多图源」,决定连线白名单 + 任务展开)',
/defaults:\s*\{[^}]*outKind:\s*'images'/.test(src))
ok('端口 in/out 都在(相册要接提示词、要出图)', /ports:\s*\{\s*in:\s*true,\s*out:\s*true\s*\}/.test(src))
// ── 二、容量常量必须与 styles.css 对齐 ────────────────────────
// 宿主全局 * { box-sizing: border-box },所以 CSS 的 height 已含 padding;JS 侧照抄即可。
const cssGap = /\.iwb-album-grid\s*\{[^}]*gap:\s*var\(--iwb-space-4\)/.test(css) ? 4 : -1
ok('宫格 gap = 4px(CSS 用 --iwb-space-4)', cssGap === 4)
ok('JS GAP 与 CSS 一致(4)', /const GAP = 4\b/.test(src))
ok('PAD_X = 16(左右各 --iwb-space-8)', /const PAD_X = 16\b/.test(src))
ok('PAD_Y = 8(宫格 padding 2 + 6)', /const PAD_Y = 8\b/.test(src))
ok('BAR_H = 26(顶栏 height: 26px)', /const BAR_H = 26\b/.test(src))
ok('TOOLS_H = 25(工具条 padding 2+2 + 按钮 21)', /const TOOLS_H = 25\b/.test(src))
ok('PAGER_H = 26(分页条 height: 26px)', /const PAGER_H = 26\b/.test(src))
ok('HINT_H = 28(提示行 24 + margin-bottom 4)', /const HINT_H = 28\b/.test(src))
ok('顶栏确实 height: 26px', /\.iwb-album-bar\s*\{[^}]*height:\s*26px/.test(css))
ok('分页条确实 height: 26px', /\.iwb-album-pager\s*\{[^}]*height:\s*26px/.test(css))
// ── 三、把纯逻辑抽出来在 vm 里真跑 ────────────────────────────
const from = src.indexOf(' const DENSITY')
const to = src.indexOf(' // ── 数据读写')
ok('能定位到常量段与 capacityOf(抽出来跑算术)', from > 0 && to > from, from + '/' + to)
let sandbox = {}
if (from > 0 && to > from) {
// const / 箭头函数在 vm 顶层是词法的,不会自动挂到 sandbox 上 ⇒ 显式导出一份
const code = src.slice(from, to) + '\n;globalThis.__album = { DENSITY: DENSITY, capacityOf: capacityOf, thumbKeyOf: thumbKeyOf, thumbNameOf: thumbNameOf }\n'
sandbox = { document: { createElement: () => ({ style: {}, appendChild() {} }) }, setTimeout, clearTimeout, Math, String, Number, Array, Object, Map, Set, Promise, JSON, RegExp, console, window: {} }
vm.createContext(sandbox)
vm.runInContext(code, sandbox, { filename: 'album-slice.js' })
Object.assign(sandbox, sandbox.__album || {})
}
const cap = sandbox.capacityOf
const DENSITY = sandbox.DENSITY
ok('DENSITY 三档严格递增(旧值 M:48 < S:64 是 bug:中格比小格还小)',
DENSITY && DENSITY.S < DENSITY.M && DENSITY.M < DENSITY.L, JSON.stringify(DENSITY))
if (typeof cap === 'function') {
// 默认节点 300×470(DEFAULT_H),这是用户最常看到的那一档
const s = cap(300, 470, 'S', false)
const m = cap(300, 470, 'M', false)
const l = cap(300, 470, 'L', false)
ok('300×470 小格 = 4 列(实测渲染 4 列 68px)', s.cols === 4, JSON.stringify(s))
ok('每页容量随档位递减 S > M > L(旧的 M 反而最多)',
s.capacity > m.capacity && m.capacity > l.capacity,
[s.capacity, m.capacity, l.capacity].join(' / '))
ok('小格每页 20 张(批量导入的常见预期值)', s.capacity === 20, String(s.capacity))
// 关键几何不变量:cols 个 cell + (cols-1) 个 gap 必须装得进内容宽度,
// rows 个 cell + (rows-1) 个 gap 必须装得进内容高度。差 1px 就会让最后一行被裁。
const fits = (w, h, d, hint) => {
const c = cap(w, h, d, hint)
const innerW = w - 4 - 16
const innerH = h - 4 - 26 - 25 - 26 - (hint ? 28 : 0) - 8
const needW = c.cols * c.cell + (c.cols - 1) * 4
const needH = c.rows * c.cell + (c.rows - 1) * 4
return { c, okW: needW <= innerW, okH: needH <= innerH, needW, needH, innerW, innerH }
}
let allFit = true
const misses = []
for (const w of [264, 280, 300, 360, 420, 520, 600]) {
for (const h of [300, 380, 470, 560, 700]) {
for (const d of ['S', 'M', 'L']) {
for (const hint of [false, true]) {
const r = fits(w, h, d, hint)
if (!r.okW || !r.okH) { allFit = false; misses.push(w + 'x' + h + ' ' + d + (hint ? '+hint ' : ' ') + JSON.stringify([r.needW, r.innerW, r.needH, r.innerH])) }
}
}
}
}
ok('35 种节点尺寸 × 3 档 × 有无提示行:算出的容量都能装进可视区(不会裁掉最后一行)',
allFit, misses.slice(0, 3).join(' | '))
const min = cap(180, 160, 'S', true)
ok('极小节点也不返回 0 列 0 行(否则宫格空白)', min.cols >= 1 && min.rows >= 1 && min.capacity >= 1, JSON.stringify(min))
}
// thumbKeyOf:固化后(src 变成 {__blob})不能退化成纯文件名(否则同名文件串味)
const tk = sandbox.thumbKeyOf
if (typeof tk === 'function') {
const a1 = tk({ src: { __file: '/a/1.png' }, name: '1.png' })
const a2 = tk({ src: { __file: '/b/1.png' }, name: '1.png' })
ok('同名不同目录的本地图 → 不同键(旧实现两处都是 "1.png",缩略图互相覆盖)', a1 !== a2, a1 + ' vs ' + a2)
const b1 = tk({ src: { __blob: 'x1' }, name: '1.png' })
const b2 = tk({ src: { __blob: 'x2' }, name: '1.png' })
ok('固化后按 __blob id 取键,不退化到文件名', b1 !== b2 && b1.indexOf('b:') === 0, b1 + ' vs ' + b2)
ok('同一引用取键稳定(拖拽排序后不会重建缩略图)', tk({ src: { __file: '/a/1.png' }, name: '1.png' }) === a1)
ok('键做成了文件安全的形式(t-<hash8>.jpg,符合插件文件白名单)',
/^[a-z0-9][a-z0-9_-]{0,63}\.jpg$/.test(sandbox.thumbNameOf(a1)), sandbox.thumbNameOf(a1))
} else ok('thumbKeyOf 可被抽取执行', false)
// ── 四、交互:清空 / 放大镜 / 固定方形 / 细边线 ────────────────
ok('有「清空」按钮', /className:\s*'iwb-album-btn iwb-album-clear'/.test(src))
ok('清空走快照(⌘Z 能整体撤销)',
/function clearAll[\s\S]{0,700}update\(st\.props, st\.node, \{ items: \[\], page: 0, pageRange: null \}, true\)/.test(src))
ok('清空只在有图时出现', /st\.btnClear\.style\.display = items\.length \? '' : 'none'/.test(src))
ok('清空后重置失联检测(否则清空再导入永远不检测)', /function clearAll[\s\S]{0,600}st\.checkedMissing = false/.test(src))
ok('格子固定正方形(aspect-ratio: 1 / 1)', /\.iwb-album-cell\s*\{[^}]*aspect-ratio:\s*1 \/ 1/.test(css))
ok('格子显式 padding: 0(button 默认内边距会把图顶出边框)', /\.iwb-album-cell\s*\{[^}]*padding:\s*0;/.test(css))
ok('选中线 1px(用户:2px 太粗)', /\.iwb-album-cell\.sel\s*\{[^}]*outline:\s*1px solid/.test(css))
ok('失联虚线同步 1px', /\.iwb-album-cell\.missing\s*\{[^}]*outline:\s*1px dashed/.test(css))
ok('放大镜元素存在(右下角)', /className:\s*'iwb-album-zoom'/.test(src))
// 1.1.1 用户裁定:hover 方案(A)实测把放大镜盖住了 ⇒ 只留「点击看大图」。
ok('不再有 hover 预览(pointerenter 触发 showPreview)', !/pointerenter'[\s\S]{0,80}showPreview/.test(src))
ok('showPreview / hidePreview / 节点内预览层代码彻底删除', !/function showPreview|function hidePreview|iwb-album-preview/.test(src + css))
ok('CSS 里没有节点内预览层(.iwb-album-preview)', !/iwb-album-preview/.test(css))
ok('放大镜 z-index 高于图片与角标(不再被任何浮层压住)',
/\.iwb-album-zoom\s*\{[^}]*z-index:\s*[1-9]/.test(css))
ok('放大镜在键盘聚焦时也可见(focus-within,不只 hover)',
/\.iwb-album-cell:focus-within \.iwb-album-zoom/.test(css))
ok('放大镜点击开查看器并带上 item 下标(整本相册可切换)',
/zoom\.addEventListener\('click',[\s\S]{0,120}openFull\(ctx, st, index\)/.test(src))
// 1.1.2:自带全屏查看器(宿主 onPreview 只收现成 URL 列表 ⇒ 整本要全转 dataURL,内存顶不住)
ok('查看器挂在 document.body(节点有 transform,inside 节点的 fixed 会错位)',
/document\.body\.appendChild\(root\)/.test(src))
ok('查看器自带左右按钮 + ← → 键盘切换',
/className:\s*'iwb-album-fs-nav prev'/.test(src) &&
/className:\s*'iwb-album-fs-nav next'/.test(src) &&
/e\.key === 'ArrowLeft'[\s\S]{0,120}go\(-1\)/.test(src) &&
/e\.key === 'ArrowRight'[\s\S]{0,120}go\(1\)/.test(src))
ok('循环切换(首尾相连,不会卡在最后一张)', /const go = \(delta\) => \{ cur = \(\(cur \+ delta\) % total \+ total\) % total/.test(src))
ok('点空白 / Esc 关闭', /if \(e\.target === root \|\| e\.target === bar\) close\(\)/.test(src) && /e\.key === 'Escape'[\s\S]{0,80}close\(\)/.test(src))
ok('原图只留 3 张(当前 + 左右预取),不整本缓存 4K dataURL',
/const FS_KEEP = 3/.test(src) && /cache\.size|keep = new Set\(\[keyAt\(cur\), keyAt\(cur \+ 1\), keyAt\(cur - 1\)\]\)/.test(src))
ok('先用缩略图占位再换原图(切页不闪黑)', /const thumb = st\.thumbs\.get\(keyAt\(i\)\) \|\| ''/.test(src))
ok('切页与预取并发去重(pending 表)', /const flight = pending\.get\(key\)/.test(src))
ok('键盘在捕获阶段吃掉(否则宿主把 ← → 当微调节点)',
/window\.addEventListener\('keydown', onKey, true\)/.test(src))
ok('关闭时摘掉键盘/滚轮监听(不残留全局监听)',
/removeEventListener\('keydown', v\.onKey, true\)/.test(src) && /removeEventListener\('wheel', v\.onWheel, true\)/.test(src))
ok('查看器层级在宿主预览层(800)之上', /\.iwb-album-fs\s*\{[^}]*z-index:\s*8[1-9][0-9]/.test(css))
ok('查看器带「复制 / 下载」(不因换查看器丢掉宿主预览原有能力)',
/iwb-album-fs-btn'/.test(src) && /'复制'/.test(src) && /'下载'/.test(src))
ok('复制转 PNG + 无 ClipboardItem 时走宿主原生通道',
/cv\.toBlob\([\s\S]{0,80}'image\/png'\)/.test(src) && /IWBDesktop[\s\S]{0,120}clipboardWriteImage/.test(src))
ok('查看器不再依赖宿主 props.onPreview(那接口要一次性给全 URL 列表)',
!/props\.onPreview\(/.test(src))
// ── 五、已修复的老 bug 必须有防回归断言 ───────────────────────
ok('批次角标彻底移除(右上角那个「1」是重复信息)',
!src.includes('iwb-album-batch') && !css.includes('iwb-album-batch'))
ok('不再有 img.src = \'\'(会向页面 URL 发空请求,控制台报 ERR_UNKNOWN_URL_SCHEME)',
!/\.src = ''/.test(src.split('\n').filter((l) => l.trim().indexOf('//') !== 0).join('\n')))
ok('跨页拖拽用「每页容量」换算,不用「本页格子数」',
/pageStart = pageNow \* capNow\.capacity/.test(src) && !/page \* cellCount/.test(src))
ok('删除不再硬编码跳回第 1 页', !/\{ items, page: 0 \}/.test(src) && /page: Math\.min\(pageNow, pagesNow - 1\)/.test(src))
ok('空节点不再显示「全部 0 张一页展示」(压着空态提示的废话)',
/const showOne = !showPager && items\.length > 0/.test(src))
ok('「文件夹」按钮不再 canReference() || true(网页版点了没反应)',
!/\|\| true \? '' : 'none'/.test(src))
ok('addPaths 里没有 keep 死变量', !/const keep = \(st\.node\.data/.test(src))
ok('缩略图请求并发去重(st.pending,否则导入 30 张要解 60 次原图)',
/const flight = st\.pending && st\.pending\.get\(key\)/.test(src))
ok('缩略图预生成有进度(500 张导入时不会看起来卡死)', /st\.busy = '缩略图 '/.test(src))
ok('新导入后重置 checkedMissing', /function addPaths[\s\S]{0,900}st\.checkedMissing = false/.test(src))
// ── 六、宿主契约不能碰 ───────────────────────────────────────
ok('仍然只写 items / page / pageRange 这几个字段给宿主(不新增宿主不认识的键)',
/outKind: 'images'/.test(src) && /pageRange: wantRange/.test(src))
ok('只引用不复制:本地图仍写 { __file: 路径 }', /\{ __file: ref\.item\.path \}/.test(src))
ok('缩略图仍存宿主插件沙箱(ctx.files),不塞进节点数据',
/ctx\.files\.put\(name, thumb\)/.test(src) && !/thumbs[\s\S]{0,40}onUpdate/.test(src))
ok('没有引入 import/export(必须是经典脚本 IIFE,CSP script-src self)',
!/^\s*(import|export)\s/m.test(src) && /^;\(function \(global\)/m.test(src))
ok('样式只能 JS 内联注入之外的地方没有新增 <style> 标签', !/<style/.test(src))
console.log('\n' + (failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env node
/* album 全屏查看器「真浏览器」冒烟(1.1.2)
*
* 为什么要单独跑:查看器是挂在 document.body 上的全局浮层 + 全局键盘/滚轮监听,
* 静态断言只能证明「代码里有这些字符串」,证明不了点开、切页、Esc/空白关闭真的能跑。
* 这里用 Chromium 装一个合成宿主,加载插件源码本体,走完整交互。
*
* 运行:node album/tools/viewer-e2e.mjs
* 依赖 playwright(宿主仓 node_modules;或 IWB_PLAYWRIGHT_ROOT 指定目录)。
* 不进 npm test:跨仓依赖,CI 上不一定装得齐。
*/
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const ROOT = path.resolve(HERE, '..')
const src = readFileSync(path.join(ROOT, 'src/index.js'), 'utf8')
const css = readFileSync(path.join(ROOT, 'styles.css'), 'utf8')
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT,
'/Users/qiqi/open/github/image-workbench-desktop',
'/Users/qiqi/open/github/image-workbench-web', ROOT]) {
if (!base) continue
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch (e) { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright:请安装,或设 IWB_PLAYWRIGHT_ROOT=/path/to/repo')
process.exit(2)
}
let failed = 0
const ok = (name, cond, extra) => {
if (!cond) failed++
console.log((cond ? '✓ ' : '✗ ') + name + (cond ? '' : (' » ' + (extra == null ? '' : extra))))
}
const browser = await chromium.launch({ headless: true })
const page = await browser.newPage({ viewport: { width: 1100, height: 800 } })
page.on('pageerror', (e) => { failed++; console.log('✗ 页面脚本异常 » ' + e.message) })
await page.setContent('<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0"><div id="host" style="width:300px;height:470px;position:relative"></div></body></html>')
await page.addStyleTag({ content: css })
await page.evaluate(() => {
const colors = ['#e57373', '#81c784', '#64b5f6', '#ffd54f', '#ba68c8']
window.__urls = colors.map((c) => 'data:image/svg+xml;base64,' + btoa(
'<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" fill="' + c + '"/></svg>'))
window.__items = window.__urls.map((u, i) => ({ src: u, name: '图' + (i + 1) + '.svg', on: true }))
window.IWBPluginHost = {
register (meta, factory) {
window.__meta = meta
const ctx = {
nodes: { register (spec) { window.__spec = spec } },
images: {
canReference: () => false,
dataUrl: async (v) => String(v || ''),
thumb: () => '',
pick: async () => [],
stat: async () => ({ ok: true, exists: true }),
listImages: async () => [],
},
files: { get: async () => ({ ok: false }), put: async () => ({ ok: true }) },
settings: { get: () => true },
}
window.__ctx = ctx
factory(ctx)
},
}
})
await page.addScriptTag({ content: src })
await page.evaluate(() => {
window.__render = (items) => {
// 不清 host:宿主每次重渲染复用同一个容器,插件靠 STATE 增量更新;
// 这里手动清空会把插件的 root 摘掉,STATE 还拿着游离节点 ⇒ 界面空白(测试自身不能造这种场景)
const host = document.getElementById('host')
const node = { id: 'n1', w: 300, h: 470, data: { outKind: 'images', items: items, albumMode: 'per-image', density: 'S', page: 0, onlyPage: false } }
const props = { onUpdate () {}, onSnapshot () {}, onPreview (u) { window.__hostPreview = u } }
window.__spec.render(node, props, host)
}
window.__render(window.__items)
})
try {
await page.waitForFunction(() => document.querySelectorAll('.iwb-album-cell').length >= 5, null, { timeout: 10000 })
} catch (e) {
console.log('DEBUG host =', (await page.evaluate(() => document.getElementById('host').innerHTML)).slice(0, 1200))
console.log('DEBUG meta =', await page.evaluate(() => JSON.stringify(window.__meta)))
console.log('DEBUG spec =', await page.evaluate(() => String(window.__spec && window.__spec.id)))
throw e
}
// 1) 点放大镜 → 全屏查看器
await page.locator('.iwb-album-zoom').first().click({ force: true })
await page.waitForFunction(() => document.querySelectorAll('.iwb-album-fs').length === 1)
ok('点放大镜开出全屏查看器', true)
ok('计数显示 1 / 5', await page.locator('.iwb-album-fs-count').textContent() === '1 / 5')
ok('原图异步换上(不是只显示缩略图)', await page.waitForFunction(
() => { const im = document.querySelector('.iwb-album-fs img'); return !!im && (im.getAttribute('src') || '').indexOf('data:image/svg+xml') === 0 },
null, { timeout: 5000 }).then(() => true).catch(() => false))
ok('左右箭头按钮都渲染出来了', await page.locator('.iwb-album-fs-nav').count() === 2)
// 2) 键盘切换(含首尾循环)
await page.keyboard.press('ArrowRight')
ok('→ 切到第 2 张', await page.locator('.iwb-album-fs-count').textContent() === '2 / 5')
await page.keyboard.press('ArrowLeft')
await page.keyboard.press('ArrowLeft')
ok('← 从第 1 张循环到最后一张', await page.locator('.iwb-album-fs-count').textContent() === '5 / 5')
await page.keyboard.press('ArrowRight')
ok('再从最后一张循环回第 1 张', await page.locator('.iwb-album-fs-count').textContent() === '1 / 5')
// 3) 按钮 / 滚轮切换
await page.locator('.iwb-album-fs-nav.next').click()
ok('下一张按钮生效', await page.locator('.iwb-album-fs-count').textContent() === '2 / 5')
await page.mouse.move(550, 400)
await page.mouse.wheel(0, 120)
await page.waitForTimeout(80)
ok('滚轮向下切一张', await page.locator('.iwb-album-fs-count').textContent() === '3 / 5')
// 3b) 宿主预览原有的「复制 / 下载」能力不能丢
ok('查看器带复制 / 下载按钮', await page.locator('.iwb-album-fs-btn').count() === 2)
await page.locator('.iwb-album-fs-btn').nth(1).click()
ok('点下载不会把查看器关掉', await page.locator('.iwb-album-fs').count() === 1)
await page.locator('.iwb-album-fs-btn').first().click()
await page.waitForTimeout(120)
ok('点复制不会报错 / 不关闭(无剪贴板权限时也只给提示)', await page.locator('.iwb-album-fs').count() === 1)
// 4) 点空白关闭;键盘监听要摘干净(关掉后再按 → 不能影响画布)
await page.mouse.click(8, 8)
ok('点图片外的空白关闭', await page.locator('.iwb-album-fs').count() === 0)
ok('关闭后画布没有被误删格子', await page.locator('.iwb-album-cell').count() === 6)
await page.locator('.iwb-album-zoom').first().click({ force: true })
await page.keyboard.press('Escape')
ok('Esc 关闭', await page.locator('.iwb-album-fs').count() === 0)
await page.keyboard.press('ArrowRight')
ok('关闭后不再残留键盘监听(→ 不报错、不重建浮层)', await page.locator('.iwb-album-fs').count() === 0)
// 5) 只有一张图时不显示左右按钮
await page.evaluate(() => window.__render([window.__items[0]]))
try {
await page.waitForFunction(() => document.querySelectorAll('.iwb-album-cell').length === 2, null, { timeout: 5000 })
} catch (e) {
console.log('DEBUG single host =', (await page.evaluate(() => document.getElementById('host').innerHTML)).slice(0, 600))
console.log('DEBUG cells =', await page.evaluate(() => document.querySelectorAll('.iwb-album-cell').length))
throw e
}
await page.locator('.iwb-album-zoom').first().click({ force: true })
const single = await page.evaluate(() => {
const root = document.querySelector('.iwb-album-fs')
const nav = document.querySelector('.iwb-album-fs-nav')
return { cls: root && root.className, display: nav ? getComputedStyle(nav).display : 'missing' }
})
ok('单图查看器隐藏左右按钮', (single.cls || '').indexOf('single') >= 0 && single.display === 'none', JSON.stringify(single))
ok('单图计数 1 / 1', await page.locator('.iwb-album-fs-count').textContent() === '1 / 1')
await page.mouse.click(8, 8)
// 6) 查看器挂到 body(不是节点里),事件不会穿透到画布
const inBody = await page.evaluate(() => {
window.__render(window.__items)
document.querySelector('.iwb-album-zoom').click()
const root = document.querySelector('.iwb-album-fs')
return !!root && root.parentNode === document.body
})
ok('浮层挂在 document.body(不受节点 transform 影响)', inBody)
ok('开启查看器没有走宿主 props.onPreview', await page.evaluate(() => typeof window.__hostPreview === 'undefined'))
await page.keyboard.press('Escape')
await browser.close()
console.log('\n' + (failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+140
View File
@@ -0,0 +1,140 @@
# 批量出图(插件)
在资源中心新增一个「批量出图」面板:勾选画布上的 `ref` 节点,串行跑
**(可选)本机抠图 → 白底/透明合成 → 单版或双版本编码(≤ 上限自动降质)**,
全部跑完打包成一个 ZIP 下载;也可以**直接在行尾点 JPG / PNG 单张下载**(1.2.0)。
**不往画布写节点** —— 20 张 × 双版本 = 40 个节点会把画布铺满,批量的产物本来就该是文件。
## 与 `white-bg-800` 的关系
合成几何(`fitRect`)与编码/降质逻辑**与 `white-bg-800` 同源**,两边各带一份:
- 宿主硬约束是**插件彼此独立**(不得依赖加载顺序,不得调其它插件),所以 `batch-export` 不能 import `white-bg-800`。
- 抠图也没「调用 xianyi-cutout 插件」—— 它是直接 `POST {apiUrl}/rmbg?crop=true` 打本机服务(同一个契约),
跟那个插件存不存在无关。
- ⚠️ **改一边要同步另一边**,尤其是 `fitRect`、体积上限二分、`TYPE_EXT` 命名规则。
## 入口
宿主「资源中心」侧栏 →「批量出图」tab(由 `panels` 能力注入,宿主在首次显示时调用 `mount`)。
## 面板字段
| 字段 | 默认 | 说明 |
|---|---|---|
| 尺寸 | 800 | 800 / 1000 / 1200 / 1600 / 2000,正方形边长 |
| 版本 | 双版本 PNG + JPG | 双版本 / 仅白底 JPG / 仅透明 PNG |
| 内容占比 % | 80 | 内容等比缩放后占边长百分比(80 = 640/800),10–100 |
| 体积上限 KB | 500 | 0 = 不限;有损格式超限自动降质(下限质量 20),仍超则**该行失败**而不是缩尺寸 |
| 文件名前缀 | 空 | 如 `DQ_` → `DQ_菜单A_800x800.jpg` |
| 走本地鲜艺抠图 | 关 | 勾上则每张先过 `localhost:30092/rmbg`;已抠好的图别勾(二次抠图会伤边缘且慢一倍) |
面板参数存 `ctx.storage.namespace('opts').panel`,刷新/切 tab 后保留。
抠图服务地址与超时在宿主「设置 → 插件 → 批量出图」里(环境配置不放面板)。
**列表区**:配置区与列表之间是一条灰底小节头(「待处理节点 共 N 个」+ 全选 / 清空 / 刷新),
明细行是 `勾选 · 30px 缩略图 · 文件名 · 状态 · JPG · PNG`。缩略图未跑时显示源图、跑完换成产物(绿框),
点任意缩略图可放大;缩略图在页内缩到 64px 长边再存 dataURL,几十张也不会把内存顶起来。
行尾的两个格式按钮(1.2.0)**常驻可点**,有无产物靠亮/灰区分,不靠悬停:
| 行状态 | 产物 | 按钮表现 |
|---|---|---|
| 待处理 / 处理中 | 无 | 两个都灰,提示「处理完成后可下载」 |
| 失败 | 无 | 两个都灰,提示「点重试成功后即可下载」 |
| 完成 · 双版本 | .jpg + .png | 两个都亮,提示带真实文件名与体积 |
| 完成 · 仅白底 JPG | .jpg | JPG 亮、PNG 灰,提示「本次设置不产出 PNG」 |
| 完成 · 仅透明 PNG | .png | PNG 亮、JPG 灰 |
亮/灰的判据是 **`item.files` 里真实存在的扩展名,不是当前「版本」设置**:跑完双版本再把版本改成
仅 JPG,那些旧 PNG 依然在内存里、依然该能下;反过来按设置判断会出现「亮着但点下去没文件」。
## 队列行为
- **串行**:一次一张,避免几十张大图同时解码爆内存。800×800 单张约 50–150ms。
- **单张失败不中断**:该行标红并显示原因,后续继续;行尾出现「重试」,只重跑这一张(不影响其它已完成项)。
- 进度条按「已结算 / 勾选总数」走,`done` 与 `fail` 都算结算。
- 生产产出的 `files` 挂在内存里,**改参数重跑会覆盖**;「导出 ZIP」总是打包当前所有 `done` 行。
- **单张下载不走 ZIP、不重新编码**:行尾点 JPG / PNG 直接复用同一条 Blob 落盘
(`downloadBlob` 建 URL,10s 后 revoke),所以不增加内存、也不用等打包。
文件名沿用 ZIP 里那套(前缀 + 原图名 + 尺寸),唯一化逻辑一致。
- **产物只进 ZIP,不写入画布**(20 张 × 2 版本 = 40 个节点会把画布铺满)。跑完每行会显示
**产物缩略图**(点击放大预览)、列表下方出现绿色提示条「已生成 N 个文件 · X KB,点「导出 ZIP」下载到本机(不写入画布)」,
并把「导出 ZIP」按钮转成绿色主按钮;导出后提示条改为「已下载 batch_xxx.zip」。
—— 这三处都是 1.0.2 补的:第一版只有一行「2 个文件 · 22KB」,用户跑完以为没产出。
- **面板打开期间会自己跟进画布**:每 2s 比对一次节点签名(id + 文件名),有新拖入的 `ref` 就刷新列表;运行中不打断。
宿主没有画布变更事件,`ctx.canvas` 也只能读,所以只能这样轮询(成本是内存数组比较)。
## ZIP 实现
自写 STORE(无压缩)写入器,零依赖:
- **为什么不用 JSZip**:桌面宿主 CSP 是 `script-src 'self' blob:`,CDN 动态插 script 会被拦死(宿主 `storage-zip.js` 记着这条教训)。
- **为什么 STORE**:图片本身已是 PNG/JPEG,DEFLATE 几乎不减体积,还白花 CPU。
- **文件名 UTF-8**:写 general purpose bit 11(`0x0800`),中文名在 Windows 资源管理器 / macOS 归档实用工具里正常。
⚠️ **macOS 命令行 `unzip`(Info-ZIP 6.0)不认这个标志位**,会解成乱码并报 `Illegal byte sequence` —— 是那个老工具的锅,
用 `python3 -m zipfile -e`、`bsdtar`、或双击归档实用工具都正常。
- **CRC 流式算**:分 1MB 片读 blob 算 CRC,图片字节始终留在浏览器 blob 存储里,不进 JS 堆(20 张大图也不会顶爆内存)。
## CSP / 权限
- 只声明 `panels` + `canvas`(只读),**不要 `canvasWrite`** —— 本插件不写画布。
- 抠图请求打到 `apiUrl`,桌面宿主 CSP 只放行 `127.0.0.1` / `localhost` 的 `30092`;改别的地址会被拦。
- `createObjectURL` 下载走 `a.click()`;`img-src` 放行 `blob:`,解码用 blob URL 并即时释放。
## 验证(开发用)
```bash
node batch-export/tools/harness.mjs
```
mock 宿主 + 真实 Chromium,覆盖:manifest / 面板注册与挂载 / 列表过滤(只 `ref` 且有图)/ 默认参数 /
队列跑通 / **ZIP 用系统 `unzip -t` 验结构与 CRC + python3 zipfile 验中文名与 8 个条目 + PNG/JPEG magic** /
抠图分支(mock `/rmbg`)/ 失败行内提示 / 参数持久化 / 静态检查(无 eval、无 `fetch(data:)`)。
需要 Playwright(可从桌面仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定)+ 系统 `unzip`、`python3`,不进 CI。
**发布后必须再跑一次真机**(mock 抓不到宿主 CSS / 真实 CSP / 真实面板挂载):
```bash
node batch-export/tools/e2e-site.mjs
```
覆盖:市场安装加载 + SRI + 资源中心 tab 出现 + 面板挂载 + 列表 2 行 +
**勾选框与文字同行(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)** +
队列跑通 + 下载 ZIP + python3 校验 4 条目 / CRC / PNG·JPEG magic / UTF-8 名。
## 发布
本仓只产出 `src/index.js`(手写单文件 IIFE)。发布走桌面仓的市场链路,见根 README「发布到市场」:
```bash
npm run validate
# 桌面仓:node scripts/sync-plugins-from-repo.js && node scripts/gen-market.js
# 再把 market/ 上传到 NAS(market.maqiart.eu.org)
```
桌面仓同步脚本按白名单一次重建全部插件清单。改版本时同步 `package.json` 的 `version`
与 `src/index.js` 里 manifest 的 `version`。发布后回读市场索引确认版本与哈希已更新,再在客户端市场安装验证。
## 版本记录
- **1.2.0**:行内单张下载 —— 每行尾部常驻 **JPG / PNG** 两个小按钮,产物生成前灰掉、生成后亮起,
点一下直接落盘(复用同一条 Blob,不重新编码、不打包、不增加内存);亮/灰按 `item.files` 里
真实存在的扩展名判断,而不是当前「版本」设置,避免「亮着却点不出文件」;
灰态提示区分四种原因(未处理 / 处理中 / 失败 / 本次设置不产出该格式)。
顺带把 `.iwb-bx-name` 的 `min-width` 从 0 改为 70px、`.iwb-bx-tag` 补 `min-width:0`,
否则窄面板里名称会被挤成 0 宽(加按钮后行内空间变紧才暴露)。
- **1.1.0**:交互与布局 ——
抠图开关文案改为「走本地鲜艺抠图(localhost:30092)」;配置区下方加灰底小节头(「待处理节点 共 N 个」+
全选/清空/刷新),隔断明显、操作按钮归位到列表区;
列表行常驻 **30px 缩略图**(未跑显示原图、跑完换产物并描绿框,点击放大,页内缩到 64px 长边存储);
**修「清空」不生效**:`el()` 用 `setAttribute('checked','false')` 处理布尔属性,属性有值即视为勾选,
改为走 property;**修切到「图库 / 节点组」时面板串页**:宿主复用同一 div 渲染其它 tab,插件用
MutationObserver 监听容器,一旦容器不再归属插件或混入别人的子节点就自行摘除(切回来自动重新挂载)。
- **1.0.3**:修 `.iwb-bx-btn-hot` 被后定义的 `.iwb-bx-btn` 覆盖(同特异性)导致导出按钮不高亮;改用双类选择器。
- **1.0.2**:产物可见性 —— 行内缩略图(点击放大)、绿色完成提示条、导出按钮高亮、导出后显示文件名;
面板每 2s 同步新拖入的节点;空列表文案改为「把图片拖进画布后点刷新」。
- **1.0.1**:修 `.iwb-bx-f input{width:100%}` 把抠图勾选框撑满整行、标签被挤到最右。
- **1.0.0**:首个版本(面板 + 串行队列 + 双版本 + ZIP)。
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/batch-export",
"private": true,
"version": "1.2.2",
"description": "批量出图:资源中心面板里勾选 ref 节点,串行跑(可选本机抠图)→ 白底/透明合成 → 双版本编码 → 打包 ZIP 下载;行内可单张下载 JPG/PNG",
"ibwPlugin": {
"id": "batch-export",
"entry": "src/index.js",
"apiVersion": 1
}
}
File diff suppressed because it is too large. Load diff
+282
View File
@@ -0,0 +1,282 @@
// 真实站点端到端(开发用,不进 CI)—— batch-export「批量出图」。
//
// 为什么需要它:harness.mjs 用的是 mock 宿主,面板样式与真实宿主 CSS 变量、真实 CSP、真实
// 画布桥都不会被执行到。发布后跑一遍这个脚本,能抓到 mock 里永远绿的问题 ——
// 例如 `.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行、把标签挤到面板最右(1.0.0 首次发布即中招)。
//
// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)+ 真实资源中心面板挂载。
//
// 运行(需要 Playwright + python3):
// node batch-export/tools/e2e-site.mjs # 默认测试站
// IWB_BASE_URL=https://iwb.maqiart.eu.org node batch-export/tools/e2e-site.mjs # 正式站
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
import { createRequire } from 'node:module'
import { execFileSync } from 'node:child_process'
import { readFileSync, existsSync, statSync } from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/batch-export/tools
const REPO = path.resolve(HERE, '../..') // <repo>
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node batch-export/tools/e2e-site.mjs')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'batch-export/package.json'), 'utf8')).version
const ZIP_OUT = path.join(os.tmpdir(), 'iwb-batch-e2e.zip')
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
// 造两张 200×120 的参考图(非正方形,等比缩放/居中被真正练到)
await page.goto('about:blank')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 200; c.height = 120
const x = c.getContext('2d')
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 200, 120)
return c.toDataURL('image/png')
})
// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], canvas: {} }))
const ws = {
workspaces: [{
id: 'w1', name: 'W',
nodes: [
{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: '菜单A.png', localName: null } },
{ id: 'r2', type: 'ref', x: 460, y: 140, data: { url: '', data: d.png, name: '菜单B.png', localName: null } },
],
edges: [], groups: [],
}],
activeId: 'w1', rev: 1,
}
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ 'batch-export': { enabled: true, settings: {}, data: {} } }))
}, { png: PNG })
// ---------- 1) 站点可达 ----------
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
// ---------- 2) 真实 KV 加载 + 启用 ----------
await page.waitForFunction(() => window.IWBPluginHost && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
await page.waitForFunction(() => window.IWBPluginHost.list().some((x) => x.id === 'batch-export'), null, { timeout: 20000 })
const info = await page.evaluate(() => {
const p = window.IWBPluginHost.list().find((x) => x.id === 'batch-export')
return p ? { version: p.version, enabled: p.enabled, active: p.active, capabilities: p.capabilities, error: p.error } : null
})
check('从真实 KV 加载并启用(active)', Boolean(info && info.active && info.enabled && !info.error), JSON.stringify(info))
check('线上版本 = batch-export/package.json(' + WANT_VERSION + ')', Boolean(info && info.version === WANT_VERSION), info && info.version)
// ---------- 3) 面板 tab ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('画布打开、2 个 ref 节点', (await page.locator('.iwb-node[data-node-id^="r"]').count()) === 2)
await page.locator('button[title^="资源中心"]').first().click()
const tab = page.locator('.iwb-res-tab', { hasText: '批量出图' })
check('资源中心出现「批量出图」tab', (await tab.count()) >= 1)
await tab.first().click()
await page.waitForTimeout(1200)
const mounted = await page.locator('.iwb-full-panel-plugin').count()
check('面板已挂载(真实宿主容器)', mounted >= 1)
// 宿主 .iwb-full-main 是 flex 行容器,只给图库/节点组容器 width:100%;插件容器不撑满就会按内容收缩
const widthInfo = await page.evaluate(() => {
const main = document.querySelector('.iwb-full-main')
const box = document.querySelector('.iwb-bx')
return {
main: main ? Math.round(main.clientWidth) : 0,
box: box ? Math.round(box.clientWidth) : 0,
}
})
check('面板撑满内容区宽度(不按内容收缩)',
widthInfo.main > 0 && widthInfo.box >= widthInfo.main - 2, JSON.stringify(widthInfo))
const rows = await page.locator('.iwb-bx-item').count()
check('面板列出 2 个 ref 节点', rows === 2, 'rows=' + rows)
// 1.0.0 首发的真实 bug:checkbox 被 .iwb-bx-f input{width:100%} 撑满整行,标签被挤到最右
const chk = await page.evaluate(() => {
const lab = document.querySelector('.iwb-bx-rowchk')
if (!lab) return null
const input = lab.querySelector('input[type=checkbox]')
const span = lab.querySelector('span')
if (!input || !span) return null
const a = input.getBoundingClientRect()
const b = span.getBoundingClientRect()
return { gap: Math.round(b.left - a.right), sameLine: Math.abs(a.top - b.top) < 12, inputW: Math.round(a.width) }
})
check('「走本地鲜艺抠图」勾选框与文字同行且紧邻', Boolean(chk && chk.sameLine && chk.gap >= 0 && chk.gap <= 12 && chk.inputW <= 24), JSON.stringify(chk))
const cutLabel = await page.evaluate(() => {
const s = document.querySelector('.iwb-bx-rowchk span')
return s ? s.textContent.trim() : ''
})
check('抠图开关文案写明「本地鲜艺抠图」+ 端口', /鲜艺/.test(cutLabel) && /30092/.test(cutLabel), cutLabel)
// 1.1.0:配置区与列表之间要有明显的隔断(灰底小节头),操作按钮归到列表区
const sec = await page.evaluate(() => {
const s = document.querySelector('.iwb-bx-sec')
if (!s) return null
const bar = document.querySelector('.iwb-bx-bar')
const a = s.getBoundingClientRect()
const b = bar.getBoundingClientRect()
return {
text: (s.textContent || '').trim().slice(0, 24),
btns: Array.from(s.querySelectorAll('button')).map((x) => x.textContent.trim()),
bg: getComputedStyle(s).backgroundColor,
belowConfig: a.top >= b.bottom - 1,
}
})
check('隔断:「待处理节点」小节头在配置区正下方,带灰底 + 全选/清空/刷新',
Boolean(sec && sec.belowConfig && sec.text.indexOf('待处理节点') === 0 &&
JSON.stringify(sec.btns) === JSON.stringify(['全选', '清空', '刷新']) && sec.bg !== 'rgba(0, 0, 0, 0)'),
JSON.stringify(sec))
// 1.1.0:缩略图必须**跑之前**就在(30px 显示 / 64px 源图)
if (rows) {
const preThumb = await page.evaluate(() => {
const imgs = Array.from(document.querySelectorAll('.iwb-bx-item img.iwb-bx-thumb'))
return { n: imgs.length, w: imgs[0] ? imgs[0].naturalWidth : 0, cssW: imgs[0] ? Math.round(imgs[0].getBoundingClientRect().width) : 0 }
})
check('列表行首常驻源图缩略图(2 张、64px 位图 / 30px 显示)',
preThumb.n === 2 && preThumb.w === 64 && preThumb.cssW === 30, JSON.stringify(preThumb))
// 1.1.0 的 bug:「清空」后勾选框视觉上仍勾着(el() 用 setAttribute('checked','false'))
await page.getByRole('button', { name: '清空', exact: true }).click()
const cleared = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
check('「清空」真的取消勾选', cleared.length === 2 && cleared.every((v) => v === false), JSON.stringify(cleared))
await page.getByRole('button', { name: '全选', exact: true }).click()
}
// ---------- 4) 跑队列 ----------
if (!rows) {
console.log('\n' + (await page.locator('.iwb-full-panel-plugin').first().innerText()))
} else {
await page.getByRole('button', { name: '全选', exact: true }).click()
await page.getByRole('button', { name: '开始出图', exact: true }).click()
await page.waitForFunction(() => {
const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP')
return b && !b.disabled
}, null, { timeout: 120000 })
const fails = await page.locator('.iwb-bx-item', { hasText: '失败' }).count()
check('队列跑完、无失败项', fails === 0, 'fail=' + fails)
// 跑完必须「看得见图」:行内缩略图 + 一条说明产物在哪的提示条(1.0.1 之前只有一行文字,用户以为没产出)
const thumbs = await page.locator('.iwb-bx-thumb').count()
check('行内显示产物缩略图(2 张)', thumbs === 2, 'thumbs=' + thumbs)
const thumbOk = thumbs ? await page.evaluate(() => {
const im = document.querySelector('.iwb-bx-thumb')
return { src: String(im.getAttribute('src') || '').slice(0, 5), w: im.naturalWidth, h: im.naturalHeight }
}) : null
check('缩略图是真解码出来的位图(800×800)', Boolean(thumbOk && thumbOk.src === 'blob:' && thumbOk.w === 800 && thumbOk.h === 800), JSON.stringify(thumbOk))
// ---------- 4.5) 行内单张下载(1.2.0):不依赖 ZIP,产物在内存里直接落盘 ----------
const dlState = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-dl')).map((b) => ({
text: b.textContent, disabled: b.disabled, title: b.title,
})))
check('行内下载:每行 JPG / PNG 各一个(2 行 = 4 个)',
dlState.length === 4 && dlState[0].text === 'JPG' && dlState[1].text === 'PNG',
JSON.stringify(dlState.map((b) => b.text)))
check('行内下载:双版本跑完后全部可点', dlState.every((b) => b.disabled === false), JSON.stringify(dlState.map((b) => b.disabled)))
const [jpgDl] = await Promise.all([
page.waitForEvent('download', { timeout: 30000 }),
page.locator('.iwb-bx-item').first().locator('.iwb-bx-dl').first().click(),
])
check('行内下载:点 JPG 直接下载单张(不必先导出 ZIP)',
/\.jpg$/.test(jpgDl.suggestedFilename()), jpgDl.suggestedFilename())
const doneText = await page.locator('.iwb-bx-done').first().innerText()
check('完成提示条说明「已生成 → 点导出 ZIP」(不写入画布)', /已生成 4 个文件/.test(doneText) && /导出 ZIP/.test(doneText) && /不写入画布/.test(doneText), doneText)
// 1.0.2 的坑:.iwb-bx-btn-hot 与 .iwb-bx-btn 同特异性且定义在前,背景被覆盖 → 高亮没生效
const zipBg = await page.evaluate(() => {
const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP')
return b ? getComputedStyle(b).backgroundColor : ''
})
check('导出按钮转为高亮(rgb(29,158,117))', zipBg === 'rgb(29, 158, 117)', zipBg)
// ---------- 5) 导出 ZIP 并用 python3 校验(系统 unzip 对 UTF-8 名会乱码,见 README) ----------
const [download] = await Promise.all([
page.waitForEvent('download', { timeout: 60000 }),
page.getByRole('button', { name: '导出 ZIP', exact: true }).click(),
])
await download.saveAs(ZIP_OUT)
check('ZIP 已下载', existsSync(ZIP_OUT), existsSync(ZIP_OUT) ? statSync(ZIP_OUT).size + ' bytes' : '缺失')
const doneAfter = await page.locator('.iwb-bx-done').first().innerText()
check('导出后提示条显示已下载的文件名', /已下载 batch_.*\.zip/.test(doneAfter), doneAfter)
try {
const report = execFileSync('python3', ['-c', `
import zipfile, sys
z = zipfile.ZipFile(sys.argv[1])
assert z.testzip() is None, 'CRC 损坏'
for i in z.infolist():
b = z.read(i.filename)
ext = i.filename.rsplit('.', 1)[-1]
ok = b[:4] == b'\\x89PNG' if ext == 'png' else b[:3] == b'\\xff\\xd8\\xff'
print('%-28s %7dB %s %s' % (i.filename, i.file_size, '格式OK' if ok else '格式BAD', 'utf8' if i.flag_bits & 0x800 else 'nomb'))
`, ZIP_OUT], { encoding: 'utf8' })
console.log(report.trim())
const lines = report.trim().split('\n').filter(Boolean)
check('ZIP 4 个条目(2 张 × 双版本)', lines.length === 4, 'entries=' + lines.length)
check('ZIP 条目格式与 UTF-8 文件名标记正确', lines.every((l) => /格式OK/.test(l) && /utf8/.test(l)))
check('双版本命名 <原名>_800x800.png/.jpg', lines.some((l) => /菜单A_800x800\.png/.test(l)) && lines.some((l) => /菜单A_800x800\.jpg/.test(l)))
} catch (e) {
check('ZIP 结构校验(python3)', false, String((e && e.stdout) || (e && e.message)).slice(0, 200))
}
}
// ---------- 6) 切到「图库 / 节点组」时不得串页(1.1.0) ----------
// 真机现象:切到「图库」后批量面板还压在图片上方 —— 宿主两端都渲染成 div 且无 key,
// React 复用同一 DOM 节点,只清理自己管理的子节点,插件 mount 进去的根节点留在原地。
const clickedGallery = await page.evaluate(() => {
const t = Array.from(document.querySelectorAll('.iwb-res-tab')).find((x) => /图库/.test(x.textContent))
if (t) t.click()
return Boolean(t)
})
await page.waitForTimeout(1200)
const gallery = await page.evaluate(() => ({
historyMounted: document.querySelectorAll('.iwb-history-embedded').length,
panelsInDom: document.querySelectorAll('.iwb-bx').length,
panelInsideHistory: Boolean(document.querySelector('.iwb-history-embedded .iwb-bx')),
}))
check('切到「图库」:批量面板自动摘除,图库内不再混入插件 DOM',
clickedGallery && gallery.historyMounted >= 1 && gallery.panelsInDom === 0 && gallery.panelInsideHistory === false,
JSON.stringify(gallery))
await page.locator('.iwb-res-tab', { hasText: '批量出图' }).first().click()
await page.waitForTimeout(1500)
const backRows = await page.locator('.iwb-bx-item').count()
const backThumbs = await page.locator('.iwb-bx-item img.iwb-bx-thumb').count()
check('切回「批量出图」:面板自动重新挂载、列表与缩略图仍在',
backRows === 2 && backThumbs === 2, 'rows=' + backRows + ' thumbs=' + backThumbs)
// ---------- 7) 无 CSP / SRI 拦截、无页面错误 ----------
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+465
View File
@@ -0,0 +1,465 @@
// 批量出图插件本地端到端(开发用,不进 CI)。
//
// 为什么需要它:面板 UI + 串行队列 + Canvas 编码 + ZIP 打包都是浏览器行为,node 侧测不了。
// 这里装一个合成宿主(可注入的 ctx + panels 容器),addScriptTag 加载插件源码本体,在真实 Chromium 里验证
// 注册 / 面板挂载 / 节点过滤 / 队列 / 双版本出图 / ZIP 结构与系统可解压性 / 抠图分支 / 失败行内提示 / 参数持久化。
//
// 运行:
// node batch-export/tools/harness.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)+ 系统 unzip(校验 ZIP)
import { createRequire } from 'node:module'
import { writeFileSync, mkdtempSync } from 'node:fs'
import { execFileSync } from 'node:child_process'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/batch-export/tools
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node batch-export/tools/harness.mjs')
process.exit(2)
}
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const poll = async (fn, timeout = 30000, step = 100) => {
const end = Date.now() + timeout
for (;;) {
let v
try { v = await fn() } catch { v = false }
if (v) return v
if (Date.now() > end) return false
await new Promise((r) => setTimeout(r, step))
}
}
// ---------- 页内环境:合成宿主 + 记录器(__H__)+ 源图 ----------
const HOST_SETUP = () => {
const H = {
manifest: null,
panels: [],
nodes: [],
images: {},
settings: {},
defaults: {},
storage: {},
logs: [],
rmbgCalls: 0,
zip: null,
}
const ctx = {
ui: { registerPanel: (p) => { H.panels.push(p); return true } },
canvas: {
getNodes: () => H.nodes,
listNodeTypes: () => [],
getSelectedNode: () => null,
getNodeImage: async (id) => H.images[id] || null,
},
settings: { get: (k) => (Object.prototype.hasOwnProperty.call(H.settings, k) ? H.settings[k] : H.defaults[k]) },
storage: {
namespace: (ns) => {
const key = String(ns === undefined || ns === null ? '' : ns)
if (!H.storage[key]) H.storage[key] = {}
return {
get: (k) => H.storage[key][String(k)],
set: (k, v) => { H.storage[key][String(k)] = v },
remove: (k) => { delete H.storage[key][String(k)] },
keys: () => Object.keys(H.storage[key]),
}
},
},
log: Object.assign(function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) }, {
info: function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) },
warn: function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) },
error: function () { H.logs.push(Array.prototype.slice.call(arguments).join(' ')) },
}),
events: { on() {}, off() {}, emit() {} },
}
window.IWBPluginHost = {
register(manifest, factory) {
H.manifest = manifest
H.defaults = {}
for (const k of Object.keys(manifest.settings || {})) H.defaults[k] = manifest.settings[k].default
factory(ctx)
},
}
window.__H__ = H
// 拦下 createObjectURL 拿 ZIP(about:blank 下不依赖真实下载事件)
const origCreate = URL.createObjectURL.bind(URL)
URL.createObjectURL = function (blob) {
if (blob && String(blob.type) === 'application/zip') H.zip = blob
return origCreate(blob)
}
}
console.log('目标:本地 mock 页(about:blank)+ 插件源码 ' + PLUGIN_ENTRY)
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
await page.addInitScript(HOST_SETUP)
await page.goto('about:blank')
await page.addScriptTag({ path: PLUGIN_ENTRY })
// ---------- 源图与假节点 ----------
await page.evaluate(async () => {
const H = window.__H__
const make = (w, h, color) => {
const c = document.createElement('canvas')
c.width = w; c.height = h
const x = c.getContext('2d')
x.fillStyle = color; x.fillRect(0, 0, w, h)
return c.toDataURL('image/png')
}
const makeBlob = (w, h, color) => new Promise((resolve) => {
const c = document.createElement('canvas')
c.width = w; c.height = h
const x = c.getContext('2d')
x.fillStyle = color; x.fillRect(0, 0, w, h)
c.toBlob(resolve, 'image/png')
})
const rect = make(400, 200, '#2f6fed')
const square = make(300, 300, '#e8a13c')
const noise = (() => {
const c = document.createElement('canvas')
c.width = 800; c.height = 800
const x = c.getContext('2d')
const img = x.createImageData(800, 800)
for (let i = 0; i < img.data.length; i += 4) {
img.data[i] = (Math.random() * 256) | 0
img.data[i + 1] = (Math.random() * 256) | 0
img.data[i + 2] = (Math.random() * 256) | 0
img.data[i + 3] = 255
}
x.putImageData(img, 0, 0)
return c.toDataURL('image/png')
})()
H.nodes = [
{ id: 'n1', type: 'ref', x: 0, y: 0, data: { name: '菜单A.png', data: rect } },
{ id: 'n2', type: 'ref', x: 0, y: 0, data: { name: '菜单B.png', data: square } },
{ id: 'n3', type: 'ref', x: 0, y: 0, data: { name: 'DQ_主图.png', data: rect } },
{ id: 'n4', type: 'ref', x: 0, y: 0, data: { name: '空节点', data: '' } },
{ id: 'n5', type: 'gen', x: 0, y: 0, data: { name: '生图结果', data: rect } },
{ id: 'n6', type: 'ref', x: 0, y: 0, data: { name: '噪声图.png', data: noise } },
]
H.images = {
n1: { dataUrl: rect },
n2: { dataUrl: square },
n3: { dataUrl: rect },
n6: { dataUrl: noise },
}
// rmbg mock:返回一张 200×100 的 PNG 字节(抠图服务契约:二进制进、PNG 字节出)
window.__RMBG_BLOB__ = await makeBlob(200, 100, '#2fbf71')
const origFetch = window.fetch
window.fetch = function (url) {
if (String(url).indexOf('/rmbg') >= 0) {
H.rmbgCalls++
return Promise.resolve(new Response(window.__RMBG_BLOB__, { status: 200, headers: { 'Content-Type': 'image/png' } }))
}
return origFetch.apply(this, arguments)
}
})
// ---------- 1) manifest / 注册 ----------
const m = await page.evaluate(() => window.__H__.manifest)
check('manifest:id = batch-export', m && m.id === 'batch-export', String(m && m.id))
check('manifest:name = 批量出图', m && m.name === '批量出图', String(m && m.name))
// 版本号从 package.json 读,不在测试里钉死 —— 否则每次发版都要记得改测试(1.2.0 这次就漏了)
const PKG_VERSION = createRequire(import.meta.url)('../package.json').version
check('manifest:version = package.json(' + PKG_VERSION + ')', m && m.version === PKG_VERSION, String(m && m.version))
check('manifest:apiVersion = 1', m && m.apiVersion === 1, String(m && m.apiVersion))
check('manifest:capabilities = [panels, canvas](只读画布,不写节点)',
m && JSON.stringify(m.capabilities) === JSON.stringify(['panels', 'canvas']), JSON.stringify(m && m.capabilities))
check('manifest:settings = apiUrl / timeoutMs',
m && JSON.stringify(Object.keys(m.settings || {}).sort()) === JSON.stringify(['apiUrl', 'timeoutMs']),
JSON.stringify(Object.keys(m.settings || {})))
const panels = await page.evaluate(() => window.__H__.panels.map((p) => ({ id: p.id, title: p.title, hasMount: typeof p.mount === 'function' })))
check('面板:恰好注册 1 个(batch-panel / 批量出图 / 有 mount)',
panels.length === 1 && panels[0].id === 'batch-panel' && panels[0].title === '批量出图' && panels[0].hasMount,
JSON.stringify(panels))
// ---------- 2) 挂载 + 列表 ----------
await page.evaluate(() => {
const host = document.createElement('div')
host.className = 'iwb-full-panel-plugin'
host.style.height = '700px'
document.body.appendChild(host)
window.__PANEL__ = host
window.__H__.panels[0].mount(host)
})
check('挂载:面板根节点已注入(.iwb-bx)', await page.evaluate(() => Boolean(document.querySelector('.iwb-bx'))))
const rows = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item')).map((r) => r.querySelector('.iwb-bx-name').textContent))
const rowCount = await page.evaluate(() => document.querySelectorAll('.iwb-bx-item').length)
check('列表:只列 ref 且有图的节点(4 行:过滤空 ref 与 gen)', rowCount === 4, String(rowCount))
check('列表:顺序与节点一致', JSON.stringify(await rows()) === JSON.stringify(['菜单A.png', '菜单B.png', 'DQ_主图.png', '噪声图.png']),
JSON.stringify(await rows()))
// ---------- 2b) 隔断 / 缩略图 / 全选清空 ----------
const sec = await page.evaluate(() => {
const s = document.querySelector('.iwb-bx-sec')
if (!s) return null
return { text: (s.textContent || '').trim(), btns: Array.from(s.querySelectorAll('button')).map((b) => b.textContent.trim()) }
})
check('隔断:配置区下方有「待处理节点」小节头,操作按钮归到列表区',
Boolean(sec) && sec.text.indexOf('待处理节点') === 0 && JSON.stringify(sec.btns) === JSON.stringify(['全选', '清空', '刷新']),
JSON.stringify(sec))
const thumbInfo = await poll(() => page.evaluate(() => {
const imgs = Array.from(document.querySelectorAll('.iwb-bx-item img.iwb-bx-thumb'))
return imgs.length === 4 && imgs.every((i) => i.complete && i.naturalWidth > 0)
? { n: imgs.length, w: imgs[0].naturalWidth, h: imgs[0].naturalHeight }
: false
}))
check('缩略图:每行都有源图缩略图且已解码(缩到 64px 长边)',
Boolean(thumbInfo) && thumbInfo.w === 64, JSON.stringify(thumbInfo))
// 清空必须真的取消勾选:1.1.0 前 el() 用 setAttribute('checked','false'),属性有值 ⇒ 视觉上仍勾着
await page.getByRole('button', { name: '清空', exact: true }).click()
const afterClear = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
check('清空:点击后勾选框全部取消(checked 属性为 false)', afterClear.every((v) => v === false), JSON.stringify(afterClear))
await page.getByRole('button', { name: '全选', exact: true }).click()
const afterAll = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
check('全选:点击后勾选框全部勾上', afterAll.length === 4 && afterAll.every((v) => v === true), JSON.stringify(afterAll))
const dflt = await page.evaluate(() => ({
size: document.querySelectorAll('.iwb-bx-bar select')[0].value,
mode: document.querySelectorAll('.iwb-bx-bar select')[1].value,
ratio: document.querySelector('.iwb-bx-bar input[type=number]').value,
max: document.querySelectorAll('.iwb-bx-bar input[type=number]')[1].value,
cutout: document.querySelector('.iwb-bx-bar input[type=checkbox]').checked,
}))
check('默认参数:800 / dual / 80% / 500KB / 抠图未勾',
dflt.size === '800' && dflt.mode === 'dual' && dflt.ratio === '80' && dflt.max === '500' && dflt.cutout === false,
JSON.stringify(dflt))
// ---------- 2.5) 行内单张下载:未处理时必须灰 ----------
const dlButtons = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-dl')).map((b) => ({
text: b.textContent, disabled: b.disabled, title: b.title,
})))
const idleDl = await dlButtons()
check('下载按钮:每行都有 JPG / PNG 两个(4 行 = 8 个)',
idleDl.length === 8 && idleDl[0].text === 'JPG' && idleDl[1].text === 'PNG',
JSON.stringify(idleDl.slice(0, 2)))
check('下载按钮:未处理时全部灰不可点', idleDl.every((b) => b.disabled === true), JSON.stringify(idleDl.map((b) => b.disabled)))
check('下载按钮:未处理时提示「处理完成后可下载」',
idleDl.every((b) => b.title.indexOf('处理完成后可下载') === 0), idleDl[0].title)
// ---------- 3) 跑队列 ----------
const clickBtn = (text) => page.evaluate((t) => {
const btn = Array.from(document.querySelectorAll('.iwb-bx-foot button')).find((b) => b.textContent === t)
if (btn) btn.click()
return Boolean(btn)
}, text)
check('队列:找到「开始出图」按钮', await clickBtn('开始出图'))
await poll(() => page.evaluate(() => document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent === '4/4'))
const afterRun = await page.evaluate(() => ({
progress: document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent,
tags: Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag')).map((t) => t.textContent),
}))
check('队列:进度 4/4', afterRun.progress === '4/4', afterRun.progress)
check('队列:每行「2 个文件」(双版本)', afterRun.tags.every((t) => t.indexOf('2 个文件') === 0), JSON.stringify(afterRun.tags))
// ---------- 3.5) 双版本跑完后:两个按钮都亮,点击能真的触发下载 ----------
const doneDl = await dlButtons()
check('下载按钮:双版本跑完后 JPG / PNG 全部可点', doneDl.every((b) => b.disabled === false), JSON.stringify(doneDl.map((b) => b.disabled)))
check('下载按钮:提示里带真实文件名与体积',
/\.jpg([\d.]+KB)/.test(doneDl[0].title) && /\.png([\d.]+KB)/.test(doneDl[1].title),
doneDl[0].title + ' | ' + doneDl[1].title)
// 拦截 a.click 记录 download 属性:jsdom 不会真下载,但能验证「点了哪个文件」
await page.evaluate(() => {
window.__DL__ = []
const orig = HTMLAnchorElement.prototype.click
HTMLAnchorElement.prototype.click = function () {
if (this.download) window.__DL__.push(this.download)
return orig.apply(this, arguments)
}
})
await page.evaluate(() => {
const btn = document.querySelectorAll('.iwb-bx-item')[0].querySelectorAll('.iwb-bx-dl')
btn[0].click() // JPG
btn[1].click() // PNG
})
const dlNames = await page.evaluate(() => window.__DL__)
check('下载按钮:点 JPG / PNG 各触发一次下载,扩展名与按钮一致',
dlNames.length === 2 && /\.jpg$/.test(dlNames[0]) && /\.png$/.test(dlNames[1]),
JSON.stringify(dlNames))
// ---------- 4) ZIP ----------
check('ZIP:找到「导出 ZIP」按钮', await clickBtn('导出 ZIP'))
await poll(() => page.evaluate(() => Boolean(window.__H__.zip)))
const zipB64 = await page.evaluate(async () => {
const buf = await window.__H__.zip.arrayBuffer()
const u8 = new Uint8Array(buf)
let bin = ''
for (let i = 0; i < u8.length; i += 0x8000) bin += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000))
return btoa(bin)
})
const tmp = mkdtempSync(path.join(tmpdir(), 'iwb-batch-'))
const zipPath = path.join(tmp, 'out.zip')
writeFileSync(zipPath, Buffer.from(zipB64, 'base64'))
check('ZIP:非空', Buffer.from(zipB64, 'base64').length > 1000, Buffer.from(zipB64, 'base64').length + ' bytes')
let zipTest = ''
try {
zipTest = execFileSync('unzip', ['-t', zipPath], { encoding: 'utf8' })
} catch (error) {
zipTest = String(error.stdout || error.message)
}
check('ZIP:系统 unzip -t 校验通过(结构与 CRC 合法)', /No errors detected/.test(zipTest), zipTest.trim().split('\n').pop())
// 命名与条目内容用 python3 的 zipfile 验 —— macOS 自带的 Info-ZIP 6.0 不认 ZIP 的 UTF-8 标志位(bit 11),
// 会把中文名按本地编码解成乱码并报 "Illegal byte sequence";那是验证工具的锅,不是 ZIP 的。
// python3 zipfile / Windows 资源管理器 / macOS 归档实用工具(libarchive)都正确支持 bit 11。
const pythonProbe = `
import sys, zipfile
z = zipfile.ZipFile(sys.argv[1])
for n in z.namelist():
print("ENTRY|" + n + "|" + z.read(n)[:4].hex())
`
let probeOut = ''
try {
probeOut = execFileSync('python3', ['-c', pythonProbe, zipPath], { encoding: 'utf8' })
} catch (error) {
probeOut = 'PROBE_FAILED ' + String(error.stdout || error.message)
}
const entries = probeOut.split('\n').filter((l) => l.startsWith('ENTRY|')).map((l) => {
const [, name, magic] = l.split('|')
return { name, magic }
})
const wantNames = ['菜单A_800x800.png', '菜单A_800x800.jpg', '菜单B_800x800.png', '菜单B_800x800.jpg', 'DQ_主图_800x800.png', 'DQ_主图_800x800.jpg', '噪声图_800x800.png', '噪声图_800x800.jpg']
const matched = wantNames.filter((n) => entries.some((e) => e.name === n))
check('ZIP:8 个条目、中文名与双版本命名正确', matched.length === 8 && entries.length === 8,
entries.map((e) => e.name).join(' / ') || probeOut.slice(0, 120))
const pngOk = entries.filter((e) => e.name.endsWith('.png')).every((e) => e.magic === '89504e47')
const jpgOk = entries.filter((e) => e.name.endsWith('.jpg')).every((e) => /^ffd8ff/.test(e.magic))
check('ZIP:解出的 .png 都是 PNG 头(89504e47)、.jpg 都是 JPEG 头(ffd8ff)', pngOk && jpgOk,
entries.map((e) => e.name.split('.').pop() + '=' + e.magic).join(' '))
// ---------- 6) 抠图分支 ----------
await page.evaluate(() => {
const chk = document.querySelector('.iwb-bx-bar input[type=checkbox]')
chk.checked = true
chk.dispatchEvent(new Event('change'))
})
await clickBtn('开始出图')
await poll(() => page.evaluate(() => document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent === '4/4'))
const cutStats = await page.evaluate(() => ({ calls: window.__H__.rmbgCalls, tags: Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag')).map((t) => t.textContent) }))
check('抠图:勾选后每张都走 rmbg(4 次)', cutStats.calls === 4, String(cutStats.calls))
check('抠图:走完仍全部成功(2 个文件/行)', cutStats.tags.every((t) => t.indexOf('2 个文件') === 0), JSON.stringify(cutStats.tags))
// ---------- 7) 体积上限失败行内提示 ----------
await page.evaluate(() => {
const chk = document.querySelector('.iwb-bx-bar input[type=checkbox]')
chk.checked = false
chk.dispatchEvent(new Event('change'))
const max = document.querySelectorAll('.iwb-bx-bar input[type=number]')[1]
max.value = '1'
max.dispatchEvent(new Event('change'))
})
await clickBtn('开始出图')
await poll(() => page.evaluate(() => document.querySelector('.iwb-bx-foot .iwb-bx-tag').textContent === '4/4'))
const failTags = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag')).map((t) => t.textContent))
check('失败:maxKB=1 时行内显示失败原因(含「已压到质量 20」)',
failTags.every((t) => t.indexOf('失败 · 已压到质量 20') === 0), JSON.stringify(failTags.slice(0, 2)))
check('失败:出现「重试」按钮', await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item button')).some((b) => b.textContent === '重试')))
// ---------- 8) 参数持久化(此时已改过 cutout / maxKB,应该有落盘记录) ----------
const saved = await page.evaluate(() => (window.__H__.storage.opts ? window.__H__.storage.opts.panel : null))
check('持久化:参数写入 storage(namespace=opts),含改过的 cutout / maxKB',
Boolean(saved) && saved.cutout === false && saved.maxKB === 1 && saved.size === 800 && saved.mode === 'dual',
JSON.stringify(saved))
// ---------- 8) 静态检查 ----------
const offenders = []
const src = (await import('node:fs')).readFileSync(PLUGIN_ENTRY, 'utf8')
for (const [i, line] of src.split('\n').entries()) {
const n = i + 1
if (/fetch\(\s*(['"])data:/.test(line)) offenders.push(n + ': fetch(data:)')
if (/\beval\s*\(/.test(line)) offenders.push(n + ': eval')
if (/new\s+Function\s*\(/.test(line)) offenders.push(n + ': new Function')
if (/\bimport\b/.test(line)) offenders.push(n + ': import')
if (/\brequire\s*\(/.test(line)) offenders.push(n + ': require')
}
check('静态检查:无 fetch(data:) / eval / new Function / import / require', offenders.length === 0, offenders.slice(0, 3).join(' | '))
check('静态检查:ZIP 文件名 UTF-8 标志位(bit 11 = 0x0800)已写', /setUint16\(6,\s*0x0800/.test(src))
// ---------- 12) 宿主复用容器(切到图库/节点组)时必须自行摘除 ----------
// 真机现象:切到「图库」后批量面板仍留在上方,因为宿主两端都渲染成 div 且无 key,React 复用同一节点,
// 只清它自己管理的子节点,插件 append 的根节点留在原地。这里模拟宿主复用行为。
const switchAway = await page.evaluate(async () => {
const host = window.__PANEL__
host.className = 'iwb-history-embedded'
host.appendChild(document.createElement('div')) // 宿主渲染的图库内容
await new Promise((r) => setTimeout(r, 60))
return { hasPanel: Boolean(document.querySelector('.iwb-bx')), hostKids: host.children.length }
})
check('切换 tab:容器被复用给图库后,插件根节点自动摘除(不串页)',
switchAway.hasPanel === false, JSON.stringify(switchAway))
const switchBack = await page.evaluate(async () => {
const host = window.__PANEL__
host.className = 'iwb-full-panel-plugin'
host.textContent = '' // 宿主先卸掉图库内容,再挂载插件
await new Promise((r) => setTimeout(r, 60))
return { hasPanel: Boolean(document.querySelector('.iwb-bx')), rows: document.querySelectorAll('.iwb-bx-item').length }
})
check('切回插件 tab:面板自动重新挂载、节点列表仍在',
switchBack.hasPanel === true && switchBack.rows > 0, JSON.stringify(switchBack))
// ---------- 6) 单版本模式:不产出的格式必须灰(而不是亮着却点不出东西) ----------
await page.evaluate(() => {
const modeSel = document.querySelectorAll('.iwb-bx-bar select')[1]
modeSel.value = 'jpeg'
modeSel.dispatchEvent(new Event('change', { bubbles: true }))
const maxIn = document.querySelectorAll('.iwb-bx-bar input[type=number]')[1]
maxIn.value = '500'
maxIn.dispatchEvent(new Event('change', { bubbles: true }))
const cut = document.querySelector('.iwb-bx-bar input[type=checkbox]')
if (cut.checked) { cut.checked = false; cut.dispatchEvent(new Event('change', { bubbles: true })) }
})
await page.getByRole('button', { name: '全选', exact: true }).click()
check('仅 JPG:找到「开始出图」按钮', await clickBtn('开始出图'))
// 不能用「进度 4/4」当完成信号:上一轮结束时已经是 4/4,会立刻返回而状态还没刷新
await poll(() => page.evaluate(() => {
const tags = Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-tag'))
return tags.length === 4 && tags.every((t) => t.textContent.indexOf('1 个文件') === 0)
}))
const jpegOnly = await dlButtons()
check('仅 JPG 模式:JPG 可点、PNG 灰',
jpegOnly.length === 8 && jpegOnly.every((b, i) => (i % 2 === 0 ? b.disabled === false : b.disabled === true)),
JSON.stringify(jpegOnly.map((b) => b.disabled)))
check('仅 JPG 模式:PNG 灰态提示说明「本次设置不产出」',
jpegOnly[1] && jpegOnly[1].title.indexOf('本次设置不产出 PNG') === 0, jpegOnly[1] && jpegOnly[1].title)
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+43
View File
@@ -0,0 +1,43 @@
# 空白画布(插件)
给**空白的参考图节点**填入一张指定尺寸的**纯白图片**,作为插图 / 标注的起点。
典型用途:新建参考图节点(还没有图)→ 直接铺一张 1024×1024 白底 → 在上面标注或继续合成。
**移植自** `iwb-plaus` 仓库的 `iwb-cutout-extension`:
- 源:`src/content.js` 的 `BLANK_RATIOS`(尺寸表)、`performBlankCanvas`(合成与写回)、`showBlankMenu`(选择菜单)。
- 只有宿主胶水(`IWBPluginHost` 注册 / `ctx` 调用)是新写的;尺寸表与合成方式逐字对齐上游。
### 与上游的差异(有意为之)
- **只保留 1K 档**:上游表里有 1K/2K/4K,但菜单实际只用 1K(`sizes['1K']`)。
- **只填当前节点**:上游也是覆盖当前空节点;本插件不提供"新建节点"模式。
- **不联动编辑器**:上游建完会自动打开它自己的编辑器;这里的编辑器是另一个插件(`image-annotate`),本插件不跨插件调用。
- **入口是节点浮动栏按钮**:仅当选中**空白 ref 节点**时出现(`nodeActions.appliesTo`),不常驻。
## 入口
- 选中一个**空白参考图节点** → 节点浮动栏出现「空白画布」按钮 → 点开选尺寸 → 立即填入纯白 PNG。
## 尺寸(与宿主 `RATIOS` 的 1K 档一致)
| 比例 | 尺寸 | 比例 | 尺寸 |
|---|---|---|---|
| 1:1 方形 | 1024×1024 | 5:4 横版 | 1136×896 |
| 2:3 竖版 | 832×1248 | 9:16 竖版 | 768×1360 |
| 3:2 横版 | 1248×832 | 16:9 横版 | 1360×752 |
| 3:4 竖版 | 880×1168 | 21:9 超宽 | 1552×656 |
| 4:3 横版 | 1184×880 | 9:21 超宽竖版 | 656×1520 |
| 4:5 竖版 | 912×1136 | | |
## 实现要点
- 合成:`canvas(w,h)` → `fillStyle='#ffffff'` → `fillRect` → `toDataURL('image/png')`。
- 写回:`ctx.canvas.setNodeImage(nodeId, dataUrl)`(原地覆盖,`url` 清空)。注意宿主把 `canvasWrite` 的 API **合并进 `ctx.canvas`**,`ctx.canvasWrite` 并不存在 —— 但 manifest 的 `capabilities` 仍须同时声明 `canvas` 与 `canvasWrite`,否则拿不到写接口。
- 空白判定:`node.type === 'ref' && !data.data && !data.url`(与上游 `isEmptyRefNode` 等价)。
- 样式用宿主 CSS 变量(`--iwb-panel/--iwb-text/--iwb-border/--iwb-layer`),明暗主题自适应;桌面宿主 CSP 允许 `style-src 'unsafe-inline'`。
## 已知限制
- `setNodeImage` 不改节点名,所以不会像上游那样命名为 `<名字>_blank_<W>x<h>.png`(节点名保持不变)。若需要文件名,得宿主开放"改节点名"的写接口。
- 1K 纯白 PNG 的 dataURL 约 30–34 KB,落库时会被宿主引用化为 `{__blob}`(超过 3000 字符阈值),属正常路径。
## 发布
与其它插件一致:本仓只产出 `src/index.js`(手写单文件 IIFE),先 `npm run validate`,再走桌面仓的市场链路
(同步 → 生市场 → 上传 `market/` 到 NAS),见根 README「发布到市场」。
桌面仓同步脚本按白名单一次重建全部插件清单,改版本时同步 `package.json` 与 manifest 的 `version`。
+7
View File
@@ -0,0 +1,7 @@
{
"name": "@iwb-plugin/blank-canvas",
"private": true,
"version": "1.0.0",
"description": "空白画布:给空白的参考图节点填入指定尺寸(1K)的纯白图片,作为插图/标注的起点",
"ibwPlugin": { "id": "blank-canvas", "entry": "src/index.js", "apiVersion": 1 }
}
+137
View File
@@ -0,0 +1,137 @@
// iwb-plugin: 空白画布 —— 给「空白的参考图节点」填入指定尺寸(1K)的纯白图片,作为插图/标注的起点。
// 移植自 iwb-plaus 仓库 iwb-cutout-extension:src/content.js 的 BLANK_RATIOS / performBlankCanvas / showBlankMenu。
// 有意差异:只保留 1K 档(上游菜单实际也只用 1K);只填当前节点(不新建);不联动编辑器。
;(function (global) {
'use strict'
// 与宿主 app.js 的 RATIOS 表 1K 档逐字一致。插件不能 import 宿主内部,故照抄数值;
// 上游扩展也是这么做的(BLANK_RATIOS 抄自宿主)。
var SIZES = [
{ label: '1:1 方形', w: 1024, h: 1024 },
{ label: '2:3 竖版', w: 832, h: 1248 },
{ label: '3:2 横版', w: 1248, h: 832 },
{ label: '3:4 竖版', w: 880, h: 1168 },
{ label: '4:3 横版', w: 1184, h: 880 },
{ label: '4:5 竖版', w: 912, h: 1136 },
{ label: '5:4 横版', w: 1136, h: 896 },
{ label: '9:16 竖版', w: 768, h: 1360 },
{ label: '16:9 横版', w: 1360, h: 752 },
{ label: '21:9 超宽', w: 1552, h: 656 },
{ label: '9:21 超宽竖版', w: 656, h: 1520 },
]
var CSS = [
'.iwb-blankcanvas-menu{position:fixed;left:50%;top:64px;transform:translateX(-50%);z-index:2147483000;',
'width:312px;padding:10px;border-radius:10px;box-sizing:border-box;',
'background:var(--iwb-panel,#fff);color:var(--iwb-text,#1c2333);',
'border:1px solid var(--iwb-border,#d5d9e0);box-shadow:0 12px 32px rgba(0,0,0,.28);',
'font:12px/1.4 system-ui,-apple-system,"PingFang SC",sans-serif}',
'.iwb-blankcanvas-title{font-weight:600;margin:2px 2px 8px}',
'.iwb-blankcanvas-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px}',
'.iwb-blankcanvas-item{display:flex;flex-direction:column;align-items:center;gap:2px;padding:8px 4px;',
'border-radius:8px;border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer,#f0f1f4);',
'color:inherit;font:inherit;cursor:pointer}',
'.iwb-blankcanvas-item:hover{background:var(--iwb-layer2,#fff)}',
'.iwb-blankcanvas-item b{font-weight:600}',
'.iwb-blankcanvas-item i{font-style:normal;font-size:11px;color:var(--iwb-text2,#4d5668)}',
].join('')
global.IWBPluginHost.register({
id: 'blank-canvas',
name: '空白画布',
version: '1.0.0',
apiVersion: 1,
capabilities: ['nodeActions', 'canvas', 'canvasWrite'],
}, function (ctx) {
var STYLE_ID = 'iwb-blankcanvas-style'
var menuEl = null
var outsideHandler = null
function injectStyle() {
if (document.getElementById(STYLE_ID)) return
var style = document.createElement('style')
style.id = STYLE_ID
style.textContent = CSS
;(document.head || document.documentElement).appendChild(style)
}
// 与上游 isEmptyRefNode 等价:ref 节点且既无本地数据也无 URL({__blob}/{__cache} 引用是对象,天然为真)
function isEmptyImageNode(node) {
if (!node || node.type !== 'ref') return false
var d = node.data || {}
return !d.data && !d.url
}
function whitePng(w, h) {
var canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
var ctx2d = canvas.getContext('2d')
ctx2d.fillStyle = '#ffffff'
ctx2d.fillRect(0, 0, w, h)
return canvas.toDataURL('image/png')
}
function closeMenu() {
if (menuEl && menuEl.parentNode) menuEl.parentNode.removeChild(menuEl)
menuEl = null
if (outsideHandler) { document.removeEventListener('pointerdown', outsideHandler, true); outsideHandler = null }
document.removeEventListener('keydown', onKeyDown, true)
}
function onKeyDown(e) { if (e.key === 'Escape') closeMenu() }
function apply(nodeId, w, h) {
var nodes = (ctx.canvas && typeof ctx.canvas.getNodes === 'function') ? ctx.canvas.getNodes() : []
var target = null
for (var i = 0; i < nodes.length; i++) if (nodes[i] && nodes[i].id === nodeId) target = nodes[i]
if (!target || !isEmptyImageNode(target)) throw new Error('该节点不是空白的图片节点')
// 宿主把 canvasWrite 的 API 合并进 ctx.canvas(plugin-host.js 的 CAPABILITY_API_KEYS)⇒ 写接口在 ctx.canvas 上
if (!ctx.canvas.setNodeImage(nodeId, whitePng(w, h))) throw new Error('写入节点失败')
}
function openMenu(nodeId) {
injectStyle()
closeMenu()
var menu = document.createElement('div')
menu.className = 'iwb-blankcanvas-menu'
var title = document.createElement('div')
title.className = 'iwb-blankcanvas-title'
title.textContent = '创建空白画布(1K)'
menu.appendChild(title)
var grid = document.createElement('div')
grid.className = 'iwb-blankcanvas-grid'
SIZES.forEach(function (size) {
var btn = document.createElement('button')
btn.type = 'button'
btn.className = 'iwb-blankcanvas-item'
btn.setAttribute('data-size', size.w + 'x' + size.h)
btn.innerHTML = '<b>' + size.label + '</b><i>' + size.w + '×' + size.h + '</i>'
btn.addEventListener('pointerdown', function (e) { e.stopPropagation() })
btn.addEventListener('click', function (e) {
e.stopPropagation()
e.preventDefault()
closeMenu()
apply(nodeId, size.w, size.h)
})
grid.appendChild(btn)
})
menu.appendChild(grid)
document.body.appendChild(menu)
menuEl = menu
outsideHandler = function (e) { if (!menuEl || !menuEl.contains(e.target)) closeMenu() }
document.addEventListener('pointerdown', outsideHandler, true)
document.addEventListener('keydown', onKeyDown, true)
}
ctx.nodeActions.register({
id: 'blank-canvas-open',
title: '空白画布',
icon: 'plus',
appliesTo: function (node) { return isEmptyImageNode(node) },
run: function (node) { openMenu(node.id); return true },
})
return { dispose: closeMenu }
})
})(typeof window !== 'undefined' ? window : globalThis)
+121
View File
@@ -0,0 +1,121 @@
# browser · 应用内浏览器
两种用法,共用同一套宿主命令:
- **画布节点**:网页直接长在画布上,跟着节点平移缩放,能和参考图并排对照。
- **独立窗口**:资源中心 →「浏览器」面板,网页在单独窗口里打开,不占画布。
## 画布内的网页节点
> **需要客户端 v3.25.29+**。
> v3.25.24~26 有「一动就白」(移动/缩放节点或画布后内容消失),v3.25.29 之前
> 还有「地址栏被网页盖住」与「内容不跟着画布缩放」两个问题 —— 都已修好。
> 旧客户端上插件会直接在节点里写明需要升级,不会只留一块白板。
画布空白处**右键 →「插件: 网页」**(插件节点不进双击菜单,这是宿主的既定规则),
得到一个 560×520 的网页节点:
```
[←][→][⟳] [ 地址栏 ] [− 100% +] | [↗][✕]
┌──────────────────────────────────────────┐
│ 网页本体(原生子 webview,盖在锚点上) │
└──────────────────────────────────────────┘
```
| 控件 | 行为 |
|---|---|
| `←` `→` | 后退 / 前进(走页面自身的 history) |
| `⟳` | 刷新;**加载中变成「停止」**,点了只中断请求,不销毁视图 |
| 地址栏 | 回车加载,`Esc` 还原;**站内跳转后自动显示当前真实地址** |
| `− 100% +` | 内容缩放设定框:点百分比可直接输入(如 `150`、`150%`),回车生效;双击回 100%;范围 25%~300% |
| `↗` | 用独立窗口/浏览器面板打开当前页面(方便多屏、需要网址栏时) |
| `✕` | 关闭网页但保留节点,点 `⟳` 或重新输入网址即可恢复 |
其它行为:
- 地址存进节点数据,下次打开画布自动恢复;标题为空时自动用站点名(多个网页节点并排时分得清)。
- **内容缩放 = 该节点缩放 × 画布缩放**:缩小画布时网页像图片一样一起缩小,不会按原宽度重排。
- 节点可以像普通节点那样拖动、缩放、编组、复制。
- **拖动节点要用标题栏**:网页区域的鼠标事件由网页自己消费,这是原生子 webview 的物理属性。
- 原生视图会被裁到「节点 ∩ 画布」,且上边界不越过工具栏 —— 按钮永远点得到。
- 画布切到别的工作区、被模态遮罩挡住、节点完全移出画布时才隐藏;平移/缩放过程全程可见。
- 缩到画布 15% 以下(节点体走 LOD 降级)时节点体会被替换,网页随之回收;放大回来会重建。
## 它解决什么
画布里的网页内容有两条死路,都走不通:
- **iframe**:主窗口 CSP 是 `default-src 'self'`,外部网址被拦;就算加了 `frame-src`,百度/GitHub 等站点都发 `X-Frame-Options` / `frame-ancestors`,拒绝被嵌。实测 GitHub、站酷、Figma、Pinterest 全部拒绝,只有维基/百度/B站/花瓣这类允许。
- **`<a target=_blank>`**:桌面 webview 里点外链会把**整个应用**导航成网页(宿主 `ui-desktop-shell.js` 专门拦截了这种行为)。
正解是原生 webview:独立窗口用 `WebviewWindow`,画布节点用 `Window::add_child` 子 webview。两者加载的都是网站自己的页面,**不受主窗口 CSP 约束**,也没有任何 IPC 权限——既能正常上网,又碰不到宿主 API。
## 用法(独立窗口)
资源中心 →「浏览器」面板:
- 地址栏输入网址,`回车` 或点「打开」。没写协议自动补 `https://`。
- 点书签快捷打开。默认四个:风格库 / 百度 / 必应 / GitHub。
- 重复打开不同网址会**复用同一个窗口**:聚焦过去并导航到新地址,不会越开越多。
- 地址栏下面一排控制:`← 后退` `→ 前进` `⟳ 刷新` `✕ 关闭`,左侧圆点显示窗口是否还开着、当前在哪个站。外部页里跳走之后从这里退回来,不用重新输网址。
书签自定义:设置 → 插件 →「应用内浏览器」→ `书签`,每行一个,格式 `名称 | 网址`(网址可省略 `https://`,`#` 开头是注释)。留空恢复默认。
## 依赖宿主命令(重要)
插件调用桌面仓的命令(`__TAURI__.core.invoke`),实现在 `image-workbench-desktop/src-tauri/src/lib.rs`。
**独立窗口:**
| 命令 | 作用 |
|---|---|
| `open_browser_window` | 打开/复用独立窗口并导航(原生 `navigate`,不往外部页面注入 JS) |
| `browser_control` | `back` / `forward` / `reload` / `close` |
| `browser_state` | 返回 `{ open, url }`,面板据此显示当前站点、启用或禁用按钮 |
**画布节点:**
| 命令 | 作用 |
|---|---|
| `canvas_webview_metrics` | 返回窗口边框尺寸(渲染层据此算「原生层 vs DOM」的坐标原点差) |
| `canvas_webview_ensure` | 按节点 id 建子 webview(已存在则只校正 rect / zoom) |
| `canvas_webview_bounds` | 位置/尺寸/可见性/缩放,渲染层按需推(热路径) |
| `canvas_webview_navigate` | 导航到新地址 |
| `canvas_webview_action` | `back` / `forward` / `reload` / `stop` / `close` |
| `canvas_webview_state` | 返回 `{ open, url }` |
| `canvas_webview_close_all` | 回收全部 `cwv-*` 子 webview(切工作区/退出时) |
**位置同步的三个坑(宿主 `src/canvas-webview.js` 与 `lib.rs` 里都有注释)**:
1. 子 webview 的 `LogicalPosition` 以**窗口边框**为原点,DOM 矩形以**内容视图**为原点,
差一个标题栏高度(macOS 标准标题栏 32pt)。不补这一下,网页整体上浮压住工具栏。
2. macOS 上 `hide()` 之后再 `show()` 会静默失效(都返回 Ok,网页永久不绘制)⇒ 隐藏一律用
「挪到窗口外」。
3. `get_webview_window("main")` 在出现任何子 webview 之后永久返回 `None` ⇒ 取窗口用
`get_window("main")`。
子 webview 的 label 是 `cwv-<节点id>`,同样不在 capabilities 里 ⇒ 无 IPC 权限。
插件把状态写到锚点属性上(`data-iwb-cwv` / `-url` / `-zoom` / `-paused`),
宿主读属性驱动原生层,反向则通过 `document` 上的 `iwb-cwv-state` 事件回传加载态与真实地址。
**没有这些命令的宿主**(例如旧版客户端、或合成测试宿主):`open_browser_window` 会失败,插件自动降级到 `window.open`(系统默认浏览器),不会崩;导航按钮保持禁用。
## 契约
- manifest:`id: 'browser'`,`version: '1.4.0'`,`apiVersion: 1`,`capabilities: ['panels', 'nodeTypes']`。
- 只注册一个面板与一个节点类型(`web`,无端口,宽 560 / 高 520)。
- CSS 在脚本执行时就注入(`#iwb-browser-style`),不依赖面板 mount——避免存档直入时无样式。
- 样式用宿主 CSS 变量(`--iwb-text` / `--iwb-layer` / `--iwb-border` 等),带兜底色,明暗主题都能看。
## 开发 / 测试
手写单文件 IIFE,`src/index.js` 即产物,无需构建。
```bash
npm run validate # 契约校验
node browser/tools/harness.mjs # 本地测试(纯 node,62 项:manifest / 面板 / URL 补全 /
# 命令调用 / 回退 / 书签 / 画布节点工具栏 / 缩放框 /
# 暂停与恢复 / 状态回填 / 编辑输入不被覆盖)
```
改完从市场重新同步到桌面仓(见根 README「发布到市场」)。**新增插件要上架,必须把 `browser` 加进桌面仓 `sync-plugins-from-repo.js` 的白名单,并在 `plugins/meta.json` 补展示信息**;只在本地开发者模式用则不用。
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/browser",
"private": true,
"version": "1.7.1",
"description": "应用内浏览器:独立窗口打开网页,或在画布节点里内嵌网页(跟随画布缩放,可单独调内容缩放)",
"ibwPlugin": {
"id": "browser",
"entry": "src/index.js",
"apiVersion": 1
}
}
+1191
View File
File diff suppressed because it is too large. Load diff
+523
View File
@@ -0,0 +1,523 @@
// 应用内浏览器插件的本地契约测试(纯 node,不依赖 playwright / 真浏览器)。
//
// 用最小 DOM / window stub 跑真实 src/index.js(IIFE),验证:
// manifest 字段 / 面板注册 / CSS 脚本执行时就注入 / URL 补全与校验 /
// 地址栏提交与书签点击都走 open_browser_window 命令 / 命令失败回退 window.open /
// 无 Tauri 回退 / 书签自定义解析 /
// 导航控制按钮的启用-禁用 / 后退走 browser_control / 状态行显示当前网址 /
// 反复 mount 不累积 settings 订阅。
//
// 运行:node browser/tools/harness.mjs (退出码 0 = 全过)
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import vm from 'node:vm'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const ENTRY = path.resolve(HERE, '../src/index.js')
const source = readFileSync(ENTRY, 'utf8')
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
// 深度按 class 找节点:书签条现在包在 .iwb-browser-bmwrap 里,不再是面板根的子节点
const findClass = (root, cls) => {
if (!root) return null
const queue = [root]
while (queue.length) {
const n = queue.shift()
if (n.className === cls) return n
if (Array.isArray(n.children)) queue.push(...n.children)
}
return null
}
// ---------- 极简 DOM stub(带可触发的事件监听) ----------
function makeNode(tag) {
const node = {
tagName: String(tag || 'div').toUpperCase(),
style: {},
attrs: {},
children: [],
className: '',
_text: '',
_listeners: {},
classList: {
_set: new Set(),
add(c) { this._set.add(c) },
remove(c) { this._set.delete(c) },
contains(c) { return this._set.has(c) },
},
set textContent(v) { this._text = String(v) },
get textContent() { return this._text },
setAttribute(k, v) { this.attrs[k] = String(v) },
getAttribute(k) { return this.attrs[k] },
removeAttribute(k) { delete this.attrs[k] },
appendChild(c) { this.children.push(c); return c },
addEventListener(name, fn) { (this._listeners[name] || (this._listeners[name] = [])).push(fn) },
fire(name, ev) {
const e = Object.assign({ preventDefault() {}, stopPropagation() {}, key: '' }, ev || {})
;(this._listeners[name] || []).forEach((fn) => fn(e))
},
value: '',
focus() { this._focused = true },
blur() { this._focused = false },
select() { this._selected = true },
set innerHTML(v) { if (v === '') this.children = [] }
}
return node
}
function makeDom() {
const styles = new Map()
return {
_styles: styles,
createElement(tag) { return makeNode(tag) },
createTextNode(t) { return { _text: String(t), nodeType: 3 } },
_listeners: {},
activeElement: null,
addEventListener(name, fn) { (this._listeners[name] || (this._listeners[name] = [])).push(fn) },
dispatchEvent(ev) { (this._listeners[ev.type] || []).forEach((fn) => fn(ev)); return true },
getElementById(id) { return styles.get(id) || null },
head: { appendChild(n) { styles.set(n.id, n) } },
documentElement: { appendChild(n) { styles.set(n.id, n) } }
}
}
function runPlugin({ invokeImpl, prefs, canvas } = {}) {
const calls = []
const doc = makeDom()
let registered = null
let panel = null
let nodeType = null
const settings = Object.assign({}, prefs || {})
const settingsListeners = []
let unsubscribed = 0
const hostObj = {
IWBPluginHost: {
register(manifest, factory) {
registered = manifest
factory({
log() {},
settings: {
get(k) { return settings[k] },
onChange(fn) {
settingsListeners.push(fn)
return function () { unsubscribed++ }
}
},
ui: {
registerPanel(p) { panel = p }
},
nodes: {
register(v) { nodeType = v; return true }
},
// 旧宿主没有 canvasWrite:不传 canvas 就是那条路径(ctx.canvas 为 undefined)
...(canvas ? { canvas } : {})
})
}
},
__TAURI__: invokeImpl
? { core: { invoke: (name, args) => { calls.push({ name, args }); return invokeImpl(name, args) } } }
: undefined,
open(url) { calls.push({ name: 'window.open', args: { url } }); return null },
URL
}
const sandbox = {
window: hostObj, globalThis: hostObj,
document: doc, URL, console, Promise, setTimeout, clearTimeout
}
vm.runInNewContext(source, sandbox, { filename: 'browser/src/index.js' })
return {
registered, panel, calls, doc, nodeType,
get unsubscribed() { return unsubscribed },
fireSetting: (name) => settingsListeners.forEach((fn) => fn(name)),
setSetting: (k, v) => { settings[k] = v }
}
}
function mountPanel(panel, doc) {
const root = doc.createElement('div')
panel.mount(root)
return root
}
const openCalls = (r) => r.calls.filter((c) => c.name === 'open_browser_window')
const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
// 默认:打开成功、browser_state 报「窗口未打开」
const okInvoke = () => (name) => {
if (name === 'browser_state') return Promise.resolve({ open: false, url: '' })
return Promise.resolve(true)
}
// ---------- manifest / 注册 / CSS ----------
{
const { registered, panel, doc } = runPlugin()
check('manifest id = browser', registered && registered.id === 'browser')
// 版本号只在一处维护(package.json),断言改为一致性检查,免得每次发版手工改测试
const pkgVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
check('manifest version 与 package.json 一致(' + pkgVersion + ')',
registered && registered.version === pkgVersion, registered && registered.version)
check('manifest apiVersion = 1', registered && registered.apiVersion === 1)
check('manifest capabilities = panels + nodeTypes + canvasWrite', registered && JSON.stringify(registered.capabilities) === '["panels","nodeTypes","canvasWrite"]',
registered && JSON.stringify(registered.capabilities))
check('manifest 声明 bookmarks 设置', registered && !!registered.settings.bookmarks)
check('注册了面板 browser-panel', !!panel && panel.id === 'browser-panel' && typeof panel.mount === 'function')
check('CSS 在脚本执行时就注入(未 mount 已存在)', doc.getElementById('iwb-browser-style') !== null)
}
// ---------- 面板 = 内嵌浏览器(结构) ----------
{
const { panel, doc } = runPlugin()
let mountOk = true
let root
try { root = mountPanel(panel, doc) } catch (e) { mountOk = false; console.error(e) }
check('mount 成功', mountOk)
const bar = root && root.children.find((c) => c.className === 'iwb-cwv-bar')
const stage = root && root.children.find((c) => c.className === 'iwb-cwv-stage')
check('面板换成浏览器工具栏 + 内容区', !!bar && !!stage)
const anchorOf = (r) => {
const s = r.children.find((c) => c.className === 'iwb-cwv-stage')
return s && s.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
}
const anchor = anchorOf(root)
check('内容区里有原生网页锚点 panel:browser', !!anchor)
check('锚点标记 scope=panel(不跟画布缩放)', anchor && anchor.attrs['data-iwb-cwv-scope'] === 'panel')
check('未输入网址时锚点不带 url(不建视图)', anchor && anchor.attrs['data-iwb-cwv-url'] === undefined)
const strip = findClass(root, 'iwb-browser-strip')
const chips = strip ? strip.children.filter((c) => c.className === 'iwb-browser-chip') : []
check('底部书签条默认 4 个 chip', chips.length === 4, '实际 ' + chips.length)
const closeBtn = bar.children.find((c) => c.attrs.title && c.attrs.title.indexOf('关闭这个网页') >= 0)
check('面板隐藏「✕ 关闭这个网页」(关掉面板就等于关闭)', !!closeBtn && closeBtn.style.display === 'none')
}
// ---------- 地址栏提交:写锚点属性(不再开独立窗口) ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const root = mountPanel(r.panel, r.doc)
const bar = root.children.find((c) => c.className === 'iwb-cwv-bar')
const input = bar.children.find((c) => c.tagName === 'INPUT')
const stage = root.children.find((c) => c.className === 'iwb-cwv-stage')
const anchor = stage.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
input.value = 'www.baidu.com'
input.fire('keydown', { key: 'Enter' })
check('回车不再调用 open_browser_window(内嵌,不开窗口)', openCalls(r).length === 0, JSON.stringify(r.calls))
check('URL 自动补 https 且写进锚点', anchor.attrs['data-iwb-cwv-url'] === 'https://www.baidu.com/',
anchor.attrs['data-iwb-cwv-url'])
input.value = 'javascript:alert(1)'
input.fire('keydown', { key: 'Enter' })
check('非法协议被拒(锚点仍是上一个合法地址)',
anchor.attrs['data-iwb-cwv-url'] === 'https://www.baidu.com/', anchor.attrs['data-iwb-cwv-url'])
}
// ---------- 书签点击:导航当前内嵌浏览器 ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const root = mountPanel(r.panel, r.doc)
const strip = findClass(root, 'iwb-browser-strip')
const chips = strip.children.filter((c) => c.className === 'iwb-browser-chip')
const stage = root.children.find((c) => c.className === 'iwb-cwv-stage')
const anchor = stage.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
chips[0].fire('click', {})
check('书签点击写锚点 url', !!anchor.attrs['data-iwb-cwv-url'] && /^https:\/\//.test(anchor.attrs['data-iwb-cwv-url']),
anchor.attrs['data-iwb-cwv-url'])
check('书签点击同样不开独立窗口', openCalls(r).length === 0, JSON.stringify(r.calls))
}
// ---------- 面板「↗」:把当前页放到画布上(canvasWrite) ----------
{
const created = []
const r = runPlugin({
invokeImpl: okInvoke(),
canvas: { createNode: (type, x, y, data) => { created.push({ type, x, y, data }); return 'n-1' } }
})
const root = mountPanel(r.panel, r.doc)
const bar = root.children.find((c) => c.className === 'iwb-cwv-bar')
const input = bar.children.find((c) => c.tagName === 'INPUT')
const stage = root.children.find((c) => c.className === 'iwb-cwv-stage')
const anchor = stage.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
const outBtn = bar.children.find((c) => c.attrs.title && c.attrs.title.indexOf('画布上打开') >= 0)
check('面板工具栏有「在画布上打开」按钮', !!outBtn)
input.value = 'pinterest.com'
input.fire('keydown', { key: 'Enter' })
outBtn.fire('click', {})
check('点击后创建了 web 节点', created.length === 1 && created[0].type === 'web',
JSON.stringify(created.map((c) => c.type)))
check('新节点带上当前网址', created.length === 1 && created[0].data.url === 'https://pinterest.com/',
created.length ? created[0].data.url : '(无)')
check('新节点不带 paused(默认直接加载)', created.length === 1 && created[0].data.paused === false)
check('放到画布时不再开独立窗口', openCalls(r).length === 0, JSON.stringify(r.calls))
}
// ---------- 旧宿主(没有 canvasWrite):↗ 回退独立窗口,不报错 ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const root = mountPanel(r.panel, r.doc)
const bar = root.children.find((c) => c.className === 'iwb-cwv-bar')
const input = bar.children.find((c) => c.tagName === 'INPUT')
const outBtn = bar.children.find((c) => c.attrs.title && c.attrs.title.indexOf('画布上打开') >= 0)
input.value = 'example.com'
input.fire('keydown', { key: 'Enter' })
let threw = false
try { outBtn.fire('click', {}) } catch (e) { threw = true }
check('旧宿主点 ↗ 不抛异常', !threw)
check('旧宿主点 ↗ 退回独立窗口', openCalls(r).length === 1, JSON.stringify(r.calls.map((c) => c.name)))
}
// ---------- 无 Tauri:面板仍可用(内嵌视图由客户端建,插件只写属性) ----------
{
const r = runPlugin() // 无 __TAURI__
const root = mountPanel(r.panel, r.doc)
const bar = root.children.find((c) => c.className === 'iwb-cwv-bar')
const input = bar.children.find((c) => c.tagName === 'INPUT')
const stage = root.children.find((c) => c.className === 'iwb-cwv-stage')
const anchor = stage.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
input.value = 'example.com'
input.fire('keydown', { key: 'Enter' })
check('无 Tauri 时地址栏仍写入锚点(不弹系统浏览器)',
anchor.attrs['data-iwb-cwv-url'] === 'https://example.com/' && r.calls.length === 0,
JSON.stringify(r.calls))
}
// ---------- 反复 mount 不累积设置订阅 ----------
{
const r = runPlugin()
mountPanel(r.panel, r.doc)
mountPanel(r.panel, r.doc)
mountPanel(r.panel, r.doc)
check('重复 mount 会解掉上一个设置订阅(3 次 mount ⇒ 解绑 2 次)', r.unsubscribed === 2, '实际 ' + r.unsubscribed)
}
// ---------- 书签数据层(分组 / 排序 / 兼容旧文本) ----------
{
const r = runPlugin()
const spec = r.registered.settings.bookmarks
check('书签设置声明为 custom(交给插件自己渲染)', spec.type === 'custom' && typeof spec.render === 'function')
const api = spec.api
check('插件暴露了书签纯函数(供 harness 断言)', !!api && typeof api.parse === 'function')
// 空值 ⇒ 默认书签,且落在「常用」一个分组里
const d0 = api.parse('')
check('空值给默认书签', d0.groups.length === 1 && d0.groups[0].items.length === 4,
JSON.stringify(d0.groups.map((g) => g.items.length)))
// 旧文本(老客户端/老用户)⇒ 自动迁成分组,不丢数据
const d1 = api.parse('MDN | developer.mozilla.org\n# 注释行\n\nOpenAI|openai.com')
check('旧文本格式迁成一个分组', d1.groups.length === 1 && d1.groups[0].items.length === 2,
JSON.stringify(d1.groups.map((g) => g.items.length)))
check('迁移后自动补协议', d1.groups[0].items[0].url === 'https://developer.mozilla.org/',
d1.groups[0].items[0].url)
// 新 JSON 结构
const src = {
v: 2,
groups: [
{ id: 'g1', name: '设计', items: [{ id: 'i1', title: '花瓣', url: 'huaban.com' }, { id: 'i2', title: 'Behance', url: 'https://www.behance.net/' }] },
{ id: 'g2', name: '空组', items: [] }
]
}
const d2 = api.parse(JSON.stringify(src))
check('JSON 分组解析(保留空分组)', d2.groups.length === 2 && d2.groups[1].items.length === 0)
check('JSON 里的地址也走 normalizeUrl', d2.groups[0].items[0].url === 'https://huaban.com/', d2.groups[0].items[0].url)
check('按分组取书签', api.items(d2, 'g1').length === 2 && api.items(d2, 'g2').length === 0)
check('取全部书签', api.items(d2, '').length === 2)
// 空地址是「没填完的草稿行」:留在设置里,但不出现在面板
const d3 = api.normalize({ groups: [{ id: 'g', name: 'x', items: [{ id: 'a', title: '待填', url: '' }, { id: 'b', title: '有', url: 'a.com' }] }] })
check('空地址草稿行保留在数据里', d3.groups[0].items.length === 2)
check('空地址草稿行不进面板', api.items(d3, '').length === 1)
// 排序算法
const arr = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]
check('拖动排序:前移到后', api.move(arr.slice(), 0, 2).map((x) => x.id).join('') === 'bca')
check('拖动排序:后移到前', api.move(arr.slice(), 2, 0).map((x) => x.id).join('') === 'cab')
check('拖动排序:越界不动', api.move(arr.slice(), 0, 9).map((x) => x.id).join('') === 'abc')
check('stringify 后再 parse 结构不丢', api.parse(api.stringify(d2)).groups[0].items.length === 2)
}
// ---------- 面板:分组 chip 切换 ----------
{
const r = runPlugin()
const twoGroups = {
v: 2,
groups: [
{ id: 'g1', name: '设计', items: [{ id: 'i1', title: '花瓣', url: 'huaban.com' }] },
{ id: 'g2', name: '工具', items: [{ id: 'i2', title: 'MDN', url: 'developer.mozilla.org' }, { id: 'i3', title: 'GitHub', url: 'github.com' }] }
]
}
r.setSetting('bookmarks', JSON.stringify(twoGroups))
const root = mountPanel(r.panel, r.doc)
const gbar = findClass(root, 'iwb-browser-groups')
const gchips = gbar ? gbar.children.filter((c) => String(c.className).indexOf('iwb-browser-gchip') === 0) : []
check('多分组时出现分组条(全部 + 2 组)', gchips.length === 3, '实际 ' + gchips.length)
const strip = findClass(root, 'iwb-browser-strip')
const countChips = () => strip.children.filter((c) => c.className === 'iwb-browser-chip').length
check('默认显示全部书签', countChips() === 3, '实际 ' + countChips())
gchips[2].fire('click', {})
check('点分组只显示该组书签', countChips() === 2, '实际 ' + countChips())
gchips[1].fire('click', {})
check('切到另一组', countChips() === 1, '实际 ' + countChips())
gchips[0].fire('click', {})
check('回到「全部」', countChips() === 3, '实际 ' + countChips())
}
// ---------- 面板:只有一个分组时不显示分组条 ----------
{
const r = runPlugin()
const root = mountPanel(r.panel, r.doc)
const gbar = findClass(root, 'iwb-browser-groups')
check('单分组隐藏分组条', !!gbar && gbar.style.display === 'none')
}
// ---------- 画布内网页节点 ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const nt = r.nodeType
check('注册了画布节点类型 web', !!nt && nt.id === 'web' && nt.title === '网页')
check('节点类型无端口(网页节点不参与连线)', JSON.stringify(nt.ports) === '{"in":false,"out":false}')
check('节点类型默认数据含 url/zoom/paused',
nt.defaults && 'url' in nt.defaults && nt.defaults.zoom === 1 && nt.defaults.paused === false,
JSON.stringify(nt.defaults))
check('节点类型带自定义渲染函数', typeof nt.render === 'function')
const updates = []
const props = { onUpdate(id, patch) { updates.push({ id, patch }) } }
const host = r.doc.createElement('div')
const node = { id: 'n1', data: { url: '' } }
nt.render(node, props, host)
check('节点体切成 flex 列布局(iwb-cwv-body)', host.classList.contains('iwb-cwv-body'))
const bar = host.children.find((c) => c.className === 'iwb-cwv-bar')
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
check('节点体含工具栏与内容区', !!bar && !!stage)
check('工具栏在内容区之前(原生视图只盖内容区,不会压住按钮)',
host.children.indexOf(bar) === 0 && host.children.indexOf(stage) === 1)
const anchor = stage && stage.children.find((c) => c.className === 'iwb-cwv-anchor')
check('内容区有原生 webview 锚点', !!anchor)
check('锚点带节点 id(宿主据此摆位置)', anchor && anchor.attrs['data-iwb-cwv'] === 'n1',
anchor && JSON.stringify(anchor.attrs))
check('空地址时不写锚点 url', anchor && anchor.attrs['data-iwb-cwv-url'] === undefined)
const input = bar.children.find((c) => c.tagName === 'INPUT')
const navBtns = bar.children.filter((c) => c.tagName === 'BUTTON')
check('工具栏 5 个动作按钮(← → ⟳ ↗ ✕)', navBtns.length === 5, '实际 ' + navBtns.length)
check('地址栏初始禁用全部动作按钮', navBtns.every((b) => b.disabled === true))
// 缩放设定框:− [100%] +,百分比是可输入的
const zoomBox = bar.children.find((c) => c.className === 'iwb-cwv-zoom')
const zpct = zoomBox && zoomBox.children.find((c) => c.tagName === 'INPUT')
const zoomBtns = zoomBox ? zoomBox.children.filter((c) => c.tagName === 'BUTTON') : []
check('工具栏有缩放设定框「− 100% +」',
!!zpct && zpct.value === '100%' && zoomBtns.length === 2, zpct && zpct.value)
check('缩放框排在地址栏之后、关闭按钮之前',
bar.children.indexOf(input) < bar.children.indexOf(zoomBox)
&& bar.children.indexOf(zoomBox) < bar.children.indexOf(navBtns[4]))
check('锚点默认缩放 1', anchor.attrs['data-iwb-cwv-zoom'] === '1', JSON.stringify(anchor.attrs))
// 输入网址回车 → 写节点数据 + 立刻更新锚点(不等 React 重渲染)
input.value = 'baidu.com'
input.fire('keydown', { key: 'Enter' })
check('回车提交写回节点 data.url', updates.length === 1 && updates[0].patch.url === 'https://baidu.com/',
JSON.stringify(updates))
check('空标题时自动用站点名(多个网页节点才分得清)',
updates[0] && updates[0].patch.title === 'baidu.com', JSON.stringify(updates[0] && updates[0].patch))
check('回车后锚点 url 同步(宿主下一帧即可导航)',
anchor.attrs['data-iwb-cwv-url'] === 'https://baidu.com/', JSON.stringify(anchor.attrs))
check('填了网址后动作按钮启用', navBtns.every((b) => b.disabled === false))
// 控制按钮 → 发 canvas_webview_action(不是 browser_control)
navBtns[0].fire('click', {})
const acts = r.calls.filter((c) => c.name === 'canvas_webview_action')
check('后退按钮走 canvas_webview_action(back)',
acts.length === 1 && acts[0].args.action === 'back' && acts[0].args.id === 'n1', JSON.stringify(acts))
// 缩放:+ 按钮一次 +10%,并把值写回节点;锚点属性立刻更新(宿主下一帧推 zoom)
zoomBtns[1].fire('click', {})
check('放大按钮把缩放调到 110%', zpct.value === '110%' && anchor.attrs['data-iwb-cwv-zoom'] === '1.1',
zpct.value + ' / ' + anchor.attrs['data-iwb-cwv-zoom'])
check('缩放值写回节点数据', updates.some((u) => u.patch.zoom === 1.1), JSON.stringify(updates))
zoomBtns[0].fire('click', {})
check('缩小按钮把缩放调回 100%', zpct.value === '100%', zpct.value)
// 直接输入百分比
zpct.value = '150%'
zpct.fire('keydown', { key: 'Enter' })
check('缩放框支持直接输入百分比', anchor.attrs['data-iwb-cwv-zoom'] === '1.5', anchor.attrs['data-iwb-cwv-zoom'])
zpct.value = '900%'
zpct.fire('keydown', { key: 'Enter' })
check('缩放上限 300%', anchor.attrs['data-iwb-cwv-zoom'] === '3', anchor.attrs['data-iwb-cwv-zoom'])
zpct.value = '10%'
zpct.fire('keydown', { key: 'Enter' })
check('缩放下限 25%', anchor.attrs['data-iwb-cwv-zoom'] === '0.25', anchor.attrs['data-iwb-cwv-zoom'])
// ✕ 暂停:写 paused 到锚点与节点数据(宿主要看到它才不会立刻重建视图)
const closeBtn = navBtns[4]
closeBtn.fire('click', {})
check('✕ 把节点标记为 paused(宿主据此关掉视图并保持关闭)',
anchor.attrs['data-iwb-cwv-paused'] === '1'
&& updates.some((u) => u.patch.paused === true), JSON.stringify(anchor.attrs))
check('✕ 之后给出可继续的提示', /已关闭/.test(stage.children.find((c) => c.className === 'iwb-cwv-empty')._text))
// 暂停态点 ⟳:恢复加载(先解除 paused,再让宿主重建)
const beforeResume = r.calls.filter((c) => c.name === 'canvas_webview_action').length
navBtns[2].fire('click', {})
check('暂停态点 ⟳ 恢复加载(不向已关闭的视图发命令)',
anchor.attrs['data-iwb-cwv-paused'] === undefined
&& updates.some((u) => u.patch.paused === false)
&& r.calls.filter((c) => c.name === 'canvas_webview_action').length === beforeResume,
JSON.stringify(updates.slice(-2)))
// 宿主回报状态:站内跳转后的真实地址要回填地址栏,加载中 ⟳ 变成「停止」
r.doc.dispatchEvent({ type: 'iwb-cwv-state', detail: { id: 'n1', loading: true, url: 'https://baidu.com/s?wd=x' } })
check('站内跳转后地址栏跟着页面地址走', input.value === 'https://baidu.com/s?wd=x', input.value)
check('加载中 ⟳ 变「停止」', navBtns[2].getAttribute('data-act') === 'stop',
navBtns[2].getAttribute('data-act'))
r.doc.dispatchEvent({ type: 'iwb-cwv-state', detail: { id: 'n1', loading: false, url: 'https://baidu.com/s?wd=x' } })
check('加载完成 ⟳ 复原', navBtns[2].getAttribute('data-act') === 'reload')
// 重渲染不能覆盖正在编辑的输入框(否则每敲一个字都被顶回去)
node.data.url = 'https://www.baidu.com/'
input.value = 'zhihu.com' // 用户正在输入,还没回车
r.doc.activeElement = input
nt.render(node, props, host)
check('重渲染不覆盖正在编辑的输入', input.value === 'zhihu.com', input.value)
// 非法地址:标红且不写数据
r.doc.activeElement = null
const before = updates.length
input.value = 'javascript:alert(1)'
input.fire('keydown', { key: 'Enter' })
check('非法协议被拒绝且不写回', updates.length === before && input.attrs['aria-invalid'] === 'true',
JSON.stringify(input.attrs))
}
// ---------- 无 Tauri 时节点给出明确提示 ----------
{
const r = runPlugin()
const nt = r.nodeType
const host = r.doc.createElement('div')
nt.render({ id: 'n2', data: { url: 'https://www.baidu.com/' } }, { onUpdate() {} }, host)
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
const empty = stage.children.find((c) => c.className === 'iwb-cwv-empty')
check('网页版节点显示「需要桌面客户端」提示', /桌面客户端/.test(empty._text), empty._text)
}
// ---------- 旧客户端(有 Tauri、但没有画布 webview 引擎)必须提示升级 ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const nt = r.nodeType
const host = r.doc.createElement('div')
nt.render({ id: 'n3', data: { url: 'https://www.baidu.com/' } }, { onUpdate() {} }, host)
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
const empty = stage.children.find((c) => c.className === 'iwb-cwv-empty')
check('旧客户端(无 canvas-webview 引擎)提示升级而不是白屏',
/v3\.25\.24|更新客户端/.test(empty._text), empty._text)
}
console.log('\n[harness] ' + (failed === 0 ? '全部通过' : failed + ' 项失败'))
process.exit(failed === 0 ? 0 : 1)
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@iwb-plugin/gallery",
"private": true,
"version": "1.7.0",
"description": "图库:右栏图片墙(筛选/多选/预览/插入画布/下载/删除),数据由宿主 gallery 能力提供",
"ibwPlugin": {
"id": "gallery",
"entry": "src/index.js",
"apiVersion": 1,
"style": "styles.css"
}
}
+606
View File
@@ -0,0 +1,606 @@
// iwb-plugin: 图库 —— 右栏「图库」面板(宿主只提供 ctx.gallery 数据能力,界面全部在插件里)
//
// 依赖客户端能力:gallery(list/thumb/preview/download/insert/remove/onChanged)+ panels。
// 数据:插件自己的配置(插入尺寸/图幅/时间筛选)存 ctx.data,不塞 settings。
// 视觉:复用宿主的 .iwb-gal-* / .iwb-history-* 类名(宿主 style.css 保留这些样式)。
//
// v1.7.0(2026-11-24):
// ① 订阅 ctx.gallery.onChanged —— 出图途中宿主每归档一张就通知,面板立刻长出新图;
// 此前只有「面板重新可见且距上次拉取 >5s」一个入口,而生成时面板一直可见 ⇒ 永远不刷。
// ② 格子「插入」补 insertK(与右键/顶部一致,尺寸档不再被忽略)。
// ③ 插入/删除补「插入中…」状态,删除改成等宿主删完再重拉(固定 250ms 会拉到未删完的清单)。
// 注:搜索框在 v1.6.1 已按用户意见移除,不再加回。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
var PANEL_ID = 'gallery-panel'
var DEF = { insertK: '1k', tile: 110, range: '' }
// v1.6.2:图幅=**实际显示宽度上限**(此前只当「算列数」用,独列时会被拉到撑满面板,选「小」也很大)
// v1.6.3:新增「极小」64px 档(面板窄时想一行看更多图)
var TILES = [[64, '极小'], [80, '小'], [110, '中'], [150, '大'], [200, '特大']]
var KS = [['orig', '原图'], ['2k', '2K'], ['1k', '1K'], ['0.5k', '0.5K']]
var RANGES = [['', '全部'], ['today', '今天'], ['7d', '7 天'], ['30d', '30 天']]
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) }
// v1.4.1:底栏按钮改用图标(窄栏里「刷新/设置」会被挤成竖排两行)
var SVG_NS = 'http://www.w3.org/2000/svg'
function iconBtn (label, build, title) {
var b = el('button', { class: 'iwb-btn iwb-btn-sm iwb-gal-icobtn', title: title || label, 'aria-label': label })
var svg = document.createElementNS(SVG_NS, 'svg')
svg.setAttribute('viewBox', '0 0 16 16')
svg.setAttribute('width', '14')
svg.setAttribute('height', '14')
svg.setAttribute('fill', 'none')
svg.setAttribute('stroke', 'currentColor')
svg.setAttribute('stroke-width', '1.5')
svg.setAttribute('stroke-linecap', 'round')
svg.setAttribute('stroke-linejoin', 'round')
svg.setAttribute('aria-hidden', 'true')
build(svg)
b.appendChild(svg)
return b
}
function svgPath (svg, d) {
var p = document.createElementNS(SVG_NS, 'path')
p.setAttribute('d', d)
svg.appendChild(p)
return p
}
function sel (options, value) {
var s = el('select', { class: 'iwb-input iwb-select-compact' })
for (var i = 0; i < options.length; i++) {
var o = el('option', { value: String(options[i][0]), text: options[i][1] })
if (String(options[i][0]) === String(value)) o.selected = true
s.appendChild(o)
}
return s
}
function mount (host, ctx) {
clear(host)
host.classList.add('iwb-plugin-node-body')
host.style.minHeight = '0'
var cfg = Object.assign({}, DEF)
var items = []
var thumbCache = {}
var thumbPending = {} // 进行中的缩略图请求(v1.6.9)
var total = 0
var limit = 100
var picked = {}
var gridW = 320
var raf = 0
var failed = {} // v1.6.0:缩略图仍失败的 name 集合(据此显示「N 张失败」+ 全部重试)
var head = el('div', { class: 'iwb-gal-head' })
var actions = el('div', { class: 'iwb-gal-actions' })
head.appendChild(actions)
var grid = el('div', { class: 'iwb-history-grid' })
var empty = el('div', { class: 'iwb-hint', text: '暂无图片 · 运行生图后会出现在这里' })
var more = el('div', { class: 'iwb-history-more' })
// v1.1.0:底部横栏 —— 左边张数/已选,右边三个设定(右对齐)
var countEl = el('span', { class: 'iwb-gal-count', text: '0 / 0 张' })
var pickedEl = el('span', { class: 'iwb-gal-sel', text: '' })
var statusEl = el('span', { class: 'iwb-gal-status', text: '' })
var failEl = el('span', { class: 'iwb-gal-fail', text: '' })
failEl.style.display = 'none'
failEl.addEventListener('click', function () { retryAll() })
var refreshBtn = iconBtn('刷新', function (svg) {
svgPath(svg, 'M13.2 6.4A5.4 5.4 0 1 0 13.4 9.4')
svgPath(svg, 'M13.2 2.6v3.8H9.4')
}, '刷新:重新向宿主拉取图库(图床恢复/外部改动后点这里)')
refreshBtn.addEventListener('click', function () { load(true) })
// v1.4.0:三个下拉不再占用前台(窄栏放不下、也显乱)——收进「设置」浮层,点按钮才展开。
var setBtn = iconBtn('设置', function (svg) {
var c1 = document.createElementNS(SVG_NS, 'circle')
c1.setAttribute('cx', '8'); c1.setAttribute('cy', '8'); c1.setAttribute('r', '4.2')
svg.appendChild(c1)
var c2 = document.createElementNS(SVG_NS, 'circle')
c2.setAttribute('cx', '8'); c2.setAttribute('cy', '8'); c2.setAttribute('r', '1.6')
svg.appendChild(c2)
for (var i = 0; i < 8; i++) {
var a = i * Math.PI / 4
var x1 = (8 + Math.cos(a) * 4.2).toFixed(2)
var y1 = (8 + Math.sin(a) * 4.2).toFixed(2)
var x2 = (8 + Math.cos(a) * 5.6).toFixed(2)
var y2 = (8 + Math.sin(a) * 5.6).toFixed(2)
svgPath(svg, 'M' + x1 + ' ' + y1 + 'L' + x2 + ' ' + y2)
}
}, '图库设置:插入尺寸 / 图幅 / 时间范围')
setBtn.classList.add('iwb-gal-setbtn')
setBtn.setAttribute('aria-expanded', 'false')
var settings = el('div', { class: 'iwb-gal-settings', role: 'dialog', 'aria-label': '图库设置' })
settings.style.display = 'none'
// 2026-11-24:底栏加「打开本地图库目录」图标(文件夹),放在设置图标左边;只桌面端可用。
var folderBtn = iconBtn('打开本地目录', function (svg) {
svgPath(svg, 'M2 4.5h4l1.5 2H14v6.5H2z')
}, '在系统文件管理器里打开本地图库目录(images/gallery)')
folderBtn.addEventListener('click', function (e) {
e.stopPropagation()
if (!ctx.gallery || typeof ctx.gallery.openFolder !== 'function') { setStatus('仅桌面端可打开本地目录'); return }
Promise.resolve(ctx.gallery.openFolder()).then(function (r) {
if (r && r.ok === false) setStatus('打开失败:' + ((r && r.error) || '仅桌面端可用'))
}).catch(function (err) { setStatus('打开失败:' + ((err && err.message) || err)) })
})
folderBtn.style.display = (typeof window !== 'undefined' && window.__TAURI__ && window.__TAURI__.core) ? '' : 'none'
// v1.4.2:刷新与设置同放右侧工具组(此前刷新在左侧信息区,空间不足时会向右溢出、压住设置图标)
var tools = el('div', { class: 'iwb-gal-tools' }, refreshBtn, folderBtn, setBtn)
var foot = el('div', { class: 'iwb-gal-foot' },
el('div', { class: 'iwb-gal-foot-left' }, countEl, pickedEl, failEl, statusEl), tools)
var wrap = el('div', { class: 'iwb-history-embedded' }, [head, grid, more, empty, foot, settings])
function setOpen (open) {
settings.style.display = open ? '' : 'none'
setBtn.setAttribute('aria-expanded', open ? 'true' : 'false')
setBtn.classList.toggle('iwb-gal-setbtn-on', !!open)
if (open) document.addEventListener('pointerdown', onDocDown, true)
else document.removeEventListener('pointerdown', onDocDown, true)
}
function onDocDown (e) {
if (settings.contains(e.target) || setBtn.contains(e.target)) return
setOpen(false)
}
setBtn.addEventListener('click', function (e) { e.stopPropagation(); setOpen(settings.style.display === 'none') })
host.appendChild(wrap)
function count () { return Object.keys(picked).length }
// ---- v1.6.0 右键菜单:单张操作(插入 / 下载 / 预览 / 复制文件名 / 删除)----
var menuEl = null
function closeMenu () {
if (menuEl && menuEl.parentNode) menuEl.parentNode.removeChild(menuEl)
menuEl = null
document.removeEventListener('pointerdown', onMenuDown, true)
document.removeEventListener('keydown', onMenuKey, true)
}
function onMenuDown (e) { if (menuEl && !menuEl.contains(e.target)) closeMenu() }
function onMenuKey (e) { if (e.key === 'Escape') closeMenu() }
function openMenu (e, it) {
e.preventDefault(); e.stopPropagation()
closeMenu()
var menu = el('div', { class: 'iwb-ctxmenu iwb-gal-menu', style: 'left:' + e.clientX + 'px;top:' + e.clientY + 'px' })
menu.appendChild(el('div', { class: 'iwb-ctx-title', text: it.name }))
function item (label, fn) {
var b = el('button', { class: 'iwb-ctx-item', text: label })
b.addEventListener('click', function (ev) { ev.stopPropagation(); closeMenu(); fn() })
menu.appendChild(b)
}
item('插入画布', function () {
setStatus('插入中…(取本地原图 → 按插入尺寸压缩)')
Promise.resolve(ctx.gallery.insert([it.name], { insertK: cfg.insertK || '1k' }))
.then(function () { setStatus('已插入:' + it.name) })
.catch(function () { setStatus('插入失败') })
})
item('下载', function () { doDownload([it.name]) })
item('预览大图', function () { try { ctx.gallery.preview(it.name) } catch (err) { /* ignore */ } })
item('复制文件名', function () {
try {
var p = global.navigator && global.navigator.clipboard && global.navigator.clipboard.writeText(it.name)
if (p && p.then) p.then(function () { setStatus('已复制文件名') }).catch(function () { setStatus('复制失败(剪贴板不可用)') })
else setStatus('复制失败(剪贴板不可用)')
} catch (err) { setStatus('复制失败(剪贴板不可用)') }
})
item('删除这张', function () {
var C = global.IWBUIConfirm
var ask = (C && C.askOrNative) ? C.askOrNative('删除「' + it.name + '」?不可恢复。', { title: '删除图片', okText: '删除' }) : Promise.resolve(global.confirm('删除「' + it.name + '」?'))
ask.then(function (ok) {
if (!ok) return
// 先本地摘掉,避免删除后还渲染一格「图片已丢失」
items = items.filter(function (x) { return x.name !== it.name })
total = Math.max(0, total - 1)
delete picked[it.name]
render()
// v1.7.0:等宿主真的删完再重拉(旧写法固定 setTimeout 250ms,磁盘慢/多张时会拉到还没删完的清单,
// 格子里出现「图片已丢失」,用户以为删坏了)
return Promise.resolve(ctx.gallery.remove([it.name])).then(function () { return load() }).catch(function () {})
}).catch(function () {})
})
document.body.appendChild(menu)
menuEl = menu
setTimeout(function () {
document.addEventListener('pointerdown', onMenuDown, true)
document.addEventListener('keydown', onMenuKey, true)
}, 0)
}
// ---- v1.6.0 多选拖入画布:宿主 drop 只认单张,这里在捕获阶段接管整批 ----
// 仅当 dataTransfer 带 application/x-iwb-gallery-batch 时生效,其余拖放行为完全不变。
function onDocDrop (e) {
var raw = ''
try { raw = (e.dataTransfer && e.dataTransfer.getData('application/x-iwb-gallery-batch')) || '' } catch (err) { return }
if (!raw) return
var names = []
try { names = JSON.parse(raw) } catch (err) { return }
if (!names || names.length < 2) return
e.preventDefault(); e.stopPropagation()
setStatus('插入中…(' + names.length + ' 张)')
Promise.resolve(ctx.gallery.insert(names, { insertK: cfg.insertK || '1k' })).then(function (r) {
if (r && r.ok === false) { setStatus('批量插入失败'); return }
setStatus('已插入 ' + names.length + ' 张')
}).catch(function () { setStatus('批量插入失败') })
}
document.addEventListener('drop', onDocDrop, true)
// v1.6.0:失败计数集中在底栏;点它 = 全部重试(整墙重挂,重新向宿主取缩略图)
function updateFail () {
var n = Object.keys(failed).length
if (!n) { failEl.style.display = 'none'; failEl.textContent = ''; return }
failEl.style.display = ''
failEl.textContent = n + ' 张失败 · 重试'
failEl.title = '点击重新加载这 ' + n + ' 张的缩略图'
}
function retryAll () {
failed = {}
updateFail()
setStatus('重试中…')
render()
}
function pickedNames () { return Object.keys(picked) }
function renderHead () {
clear(actions)
countEl.textContent = items.length + ' / ' + total + ' 张'
pickedEl.textContent = count() ? ('已选 ' + count()) : ''
var n = count()
function btn (label, title0, fn, need, danger) {
var b = el('button', { class: 'iwb-btn iwb-btn-sm' + (danger ? ' iwb-btn-danger' : '') + (need && !n ? ' iwb-gal-off' : ''), text: label, title: need && !n ? '先选中图片' : title0 })
b.addEventListener('click', function () { if (need && !n) return; fn() })
return b
}
actions.appendChild(btn('全选', '全选当前筛选结果', function () { for (var i = 0; i < items.length; i++) picked[items[i].name] = 1; render() }))
actions.appendChild(btn('反选', '反选当前筛选结果', function () { for (var i = 0; i < items.length; i++) { var k = items[i].name; if (picked[k]) delete picked[k]; else picked[k] = 1 } render() }))
actions.appendChild(btn('插入', '把选中的图片插入画布(尺寸按「设置 → 插入尺寸」)', function () {
var names = pickedNames()
var k = cfg.insertK || '1k'
setStatus('插入中…(' + names.length + ' 张)')
Promise.resolve(ctx.gallery.insert(names, { insertK: k })).then(function (r) {
if (r && r.ok === false) { setStatus('插入失败'); return }
setStatus('已插入 ' + names.length + ' 张(' + String(k).toUpperCase() + ')')
}).catch(function () { setStatus('插入失败') })
}, true))
actions.appendChild(btn('下载', '下载选中的图片', function () { doDownload(pickedNames()) }, true))
actions.appendChild(btn('删除', '删除选中的图片(不可恢复)', function () {
var C = global.IWBUIConfirm
var ask = C && C.askOrNative ? C.askOrNative('删除选中的 ' + n + ' 张图片?不可恢复。', { title: '删除图片', okText: '删除' }) : Promise.resolve(global.confirm('删除选中的 ' + n + ' 张图片?'))
var names = pickedNames()
ask.then(function (ok) {
if (!ok) return
// 先本地摘掉,避免删除后还渲染一格「图片已丢失」;随后再向宿主重拉(等它删完+刷新)
items = items.filter(function (x) { return names.indexOf(x.name) < 0 })
total = Math.max(0, total - names.length)
picked = {}
render()
return Promise.resolve(ctx.gallery.remove(names)).then(function () {
return load() // v1.7.0:等宿主真删完再重拉(固定延时会拉到未删完的清单)
})
}).catch(function () {})
}, true, true))
}
// 设置浮层内容只建一次(不随每次 render 重建,避免下拉被重置)
function buildSettings () {
clear(settings)
settings.appendChild(el('div', { class: 'iwb-gal-settings-title', text: '图库设置' }))
function row (key, options, label, hint) {
var s = sel(options, cfg[key])
s.title = hint || label
s.setAttribute('aria-label', label)
s.addEventListener('change', function () {
cfg[key] = s.value
saveCfg()
if (key === 'range') { limit = 100; load() } else if (key === 'tile') render()
})
return el('label', { class: 'iwb-gal-setrow' }, el('span', { class: 'iwb-gal-setlabel', text: label }), s)
}
settings.appendChild(row('insertK', KS, '插入尺寸', '插入画布时的图片尺寸'))
settings.appendChild(row('tile', TILES, '图幅', '图库图片显示宽度'))
settings.appendChild(row('range', RANGES, '时间范围', '按生成时间筛选'))
}
function renderGrid () {
clear(grid)
var gap = 6
// 每次重排都重新量一次宽度:面板显隐/停靠栏展开时 gridW 可能是旧值,
// 只靠 ResizeObserver 会在「变成 0 再回来」期间漏掉,导致必须拖宽度才出图。
var liveW = availableW()
if (liveW > 0 && Math.abs(liveW - gridW) > 1) gridW = liveW
if (!gridW) gridW = 320
var tileW = Math.max(40, Number(cfg.tile) || 110)
var n = Math.max(1, Math.floor((gridW + gap) / (tileW + gap)))
// v1.6.6:列宽 = 均分宽度(铺满面板),图幅只决定「列数」——
// 以前 min(图幅, 均分) 会留下右侧空白,看起来像没补齐。
var colW = Math.max(40, (gridW - gap * (n - 1)) / n)
var cols = []
var heights = []
for (var c = 0; c < n; c++) { cols.push([]); heights.push(0) }
for (var i = 0; i < items.length; i++) {
var it = items[i]
var ratio = (it.w && it.h) ? (it.h / it.w) : 1
var min = 0
for (var j = 1; j < n; j++) if (heights[j] < heights[min]) min = j
cols[min].push(it)
heights[min] += colW * ratio + gap
}
for (var ci = 0; ci < cols.length; ci++) {
var col = el('div', { class: 'iwb-history-col', style: 'width:' + Math.round(colW) + 'px;flex:0 0 auto' })
for (var k = 0; k < cols[ci].length; k++) col.appendChild(itemNode(cols[ci][k]))
grid.appendChild(col)
}
empty.style.display = items.length ? 'none' : ''
clear(more)
if (total > items.length) {
var b = el('button', { class: 'iwb-btn iwb-btn-sm', text: '显示更多(' + (total - items.length) + ' 张)' })
b.addEventListener('click', function () { limit += 100; load() })
more.appendChild(b)
}
}
function itemNode (it) {
var on = !!picked[it.name]
var box = el('div', { class: 'iwb-history-item' + (count() ? ' iwb-history-managed' : '') + (on ? ' iwb-history-selected' : '') })
// 缩略图是**异步**的(ctx.gallery.thumb 返回 Promise):先占位,拿到地址再挂 img。
// v1.2.0:加载失败自动重试 2 次(图片还没落盘/临时不可读),仍失败才显示可点击重试的占位。
box.title = it.name + '(单击单选 · Shift+单击多选 · 双击放大 · 拖到画布=参考图节点)'
var holder = el('div', { class: 'iwb-history-missing', text: '加载中…' })
box.appendChild(holder)
var tries = 0
function fail (text) {
tries = 999
holder.textContent = text || '缩略图加载失败(点击重试)'
holder.style.cursor = 'pointer'
holder.onclick = function () { failed[it.name] = 1; tries = 0; boot() }
failed[it.name] = 1
updateFail()
}
function boot () {
if (tries >= 999) return
holder.style.cursor = ''
holder.onclick = null
holder.textContent = '加载中…'
// v1.6.9:缩略图地址按名字缓存,且进行中的请求共享同一 Promise ——
// 重排/重测会重建 DOM,不共享就会对同一张图重复取 N 次。
var key = it.name
if (thumbCache[key]) { var u0 = thumbCache[key]; Promise.resolve().then(function () { paint(u0) }).catch(function () { /* ignore */ }); return }
if (!thumbPending[key]) {
thumbPending[key] = Promise.resolve(ctx.gallery.thumb(key)).then(function (url) {
if (url && typeof url === 'string') thumbCache[key] = url
delete thumbPending[key]
return url
}, function (e) { delete thumbPending[key]; throw e })
}
thumbPending[key].then(paint).catch(function () { fail('缩略图加载失败(点击重试)') })
}
function paint (url) {
if (!url || typeof url !== 'string') { fail('图片已丢失'); return }
if (!box.isConnected) return
var img = el('img', { src: url, alt: '', loading: 'eager', draggable: 'true' })
if (it.w && it.h) img.setAttribute('style', 'aspect-ratio:' + it.w + ' / ' + it.h)
img.addEventListener('load', function () {
// naturalWidth=0 说明拿到的是坏图(空 data URL / 截断文件):按失败处理,别留白块
if (!img.naturalWidth) { tries++; if (tries <= 2) { setTimeout(boot, 400 * tries); return } if (img.parentNode === box) box.replaceChild(holder, img); fail('缩略图加载失败(点击重试)'); return }
if (holder.parentNode === box) box.replaceChild(img, holder)
if (failed[it.name]) { delete failed[it.name]; updateFail() }
})
img.addEventListener('error', function () {
tries++
if (tries <= 2) { setTimeout(boot, 400 * tries); return }
if (img.parentNode === box) box.replaceChild(holder, img)
fail('缩略图加载失败(点击重试)')
})
img.addEventListener('click', function (e) { pick(it.name, !!(e && e.shiftKey)) })
img.addEventListener('dblclick', function () { ctx.gallery.preview(it.name) })
img.addEventListener('dragstart', function (e) {
try {
var names = (picked[it.name] && count() > 1) ? pickedNames() : [it.name]
e.dataTransfer.setData('application/x-iwb-localref', names[0])
e.dataTransfer.setData('application/x-iwb-gallery-orig', names[0])
// 多选:额外带一批名字,由本插件在 document 捕获阶段接管(宿主 drop 只认单张)
if (names.length > 1) {
e.dataTransfer.setData('application/x-iwb-gallery-batch', JSON.stringify(names))
setStatus('拖动 ' + names.length + ' 张')
}
e.dataTransfer.effectAllowed = 'copy'
} catch (err) { /* ignore */ }
})
img.style.display = 'none'
box.appendChild(img)
// v1.6.9:坏图/超时兜底 —— 某些坏字节既不触发 load 也不触发 error,700ms 后直接判定失败(可点击重试)
setTimeout(function () {
try {
if (!img.parentNode) return
if (img.naturalWidth > 0) return
if (img.parentNode === box) box.replaceChild(holder, img)
fail('缩略图加载失败(点击重试)')
} catch (e) { /* ignore */ }
}, 2000)
// 加载成功后再替换占位(避免破图标 + 长 title 占满格子)
if (img.complete && img.naturalWidth > 0) { img.style.display = ''; if (holder.parentNode === box) box.replaceChild(img, holder) }
else if (img.complete && !img.naturalWidth) { /* 立即失败(坏图)*/ tries++; if (tries <= 2) setTimeout(boot, 400 * tries); else { if (img.parentNode === box) box.replaceChild(holder, img); fail('缩略图加载失败(点击重试)') } }
}
boot()
box.addEventListener('contextmenu', function (e) { openMenu(e, it) })
var acts = el('div', { class: 'iwb-history-actions' })
function act (label, title, fn) {
var b = el('button', { class: 'iwb-btn iwb-btn-sm', text: label, title: title })
b.addEventListener('click', function (e) { e.stopPropagation(); fn() })
return b
}
acts.appendChild(act('插入', '插入到画布(参考图节点 · 尺寸按「设置 → 插入尺寸」)', function () {
// v1.7.0:格子里的「插入」此前没带 insertK,宿主按默认 1k 处理 —— 与右键菜单/顶部「插入」不一致
setStatus('插入中…')
ctx.gallery.insert([it.name], { insertK: cfg.insertK || '1k' }).then(function () {
setStatus('已插入:' + it.name)
}).catch(function () { setStatus('插入失败') })
}))
acts.appendChild(act('下载', '下载到本地', function () { doDownload([it.name]) }))
box.appendChild(acts)
return box
}
var statusTimer = 0
function setStatus (text) {
statusEl.textContent = text || ''
clearTimeout(statusTimer)
if (text) statusTimer = setTimeout(function () { statusEl.textContent = '' }, 4000)
}
function doDownload (names) {
setStatus('下载中…')
return Promise.resolve(ctx.gallery.download(names)).then(function (r) {
var failed = (r && r.failed) || []
var ok = (r && r.count) || 0
if (failed.length) setStatus(failed.length + ' 张下载失败,可再点一次重试')
else setStatus(ok ? ('已下载 ' + ok + ' 张') : '没有可下载的图片')
}).catch(function () { setStatus('下载失败,可再点一次重试') })
}
function pick (name, shift) {
if (shift) { if (picked[name]) delete picked[name]; else picked[name] = 1 } else { picked = {}; picked[name] = 1 }
render()
}
function render () { renderHead(); renderGrid(); global.requestAnimationFrame(function () { try { measure() } catch (e) {} }); setTimeout(function () { try { measure() } catch (e) {} }, 150) }
function load (force) {
if (force) setStatus('刷新中…')
return Promise.resolve(ctx.gallery.list({ range: cfg.range, limit: limit })).then(function (r) {
items = (r && r.items) || []
total = (r && r.total) || items.length
lastLoadAt = Date.now()
failed = {}
render()
}).catch(function () { items = []; total = 0; render() })
}
var saveTimer = 0
function saveCfg () {
clearTimeout(saveTimer)
saveTimer = setTimeout(function () {
try { var p = ctx.data && ctx.data.patch({ cfg: cfg }); if (p && p.catch) p.catch(function () {}) } catch (e) { /* 配置存不下不影响使用 */ }
}, 200)
}
// 宽度测量:列数只由「面板宽 / 图幅」决定
// v1.6.5:面板刚挂载时 grid 宽度可能是 0,而 grid 宽度又取决于列宽 → RO 不会触发,图库一直空白。
function availableW () {
// v1.6.6:优先量「会随面板拉伸的外层容器」,而不是 grid 自身
// (grid 现在是 flex-start + 内容宽度,面板变宽它不会变宽 → RO 不触发 → 列数永不补齐)
var w = wrap ? wrap.clientWidth : 0
if (!w && wrap && wrap.parentNode) w = wrap.parentNode.clientWidth
if (!w) w = grid.clientWidth
return w || 0
}
function measure () {
var w = availableW()
if (w > 0 && Math.abs(w - gridW) > 1) { gridW = w; renderGrid() }
}
var ro = typeof ResizeObserver === 'function' ? new ResizeObserver(function () { measure() }) : null
if (ro) { if (wrap) ro.observe(wrap); if (wrap && wrap.parentNode) ro.observe(wrap.parentNode); ro.observe(grid) }
measure()
var tries = 0
function retry () {
if (gridW > 0 || tries++ > 40) { if (gridW <= 0) { gridW = Math.max(160, Number(cfg.tile) || 110) * 2; renderGrid() } return }
measure()
if (gridW <= 0) global.requestAnimationFrame(retry)
}
global.requestAnimationFrame(retry)
// v1.6.7:再补几次延时重测(停靠栏展开动画、首帧布局未完成时能在 1s 内自愈)
;[120, 400, 900].forEach(function (ms) { setTimeout(function () { try { measure(); if (gridW > 0) renderGrid() } catch (e) { /* ignore */ } }, ms) })
// v1.3.0:自动恢复 —— 面板重新可见(切回 tab / 窗口聚焦 / 后台回来)且距上次拉取 >5s 时重拉一次,
// 这样图床恢复、后台补图后不必手动刷新;同时保留底部「刷新」按钮做即时重试。
// v1.7.0:这只是**兜底**。主通道改成宿主主动通知(下面 onChanged)—— 生成途中面板一直是可见的,
// 靠「可见性变化」触发永远等不到,用户看到的就是「生图完成但图库没图」。
var lastLoadAt = 0
var autoRefresh = function () {
if (Date.now() - lastLoadAt < 5000) return
load()
}
var unsubChanged = null
var changedTimer = 0
try {
var G = ctx.gallery
if (G && typeof G.onChanged === 'function') {
unsubChanged = G.onChanged(function () {
// 合并同一批的连续通知(一张图会触发「归档完成」一次),260ms 内只重拉一次
clearTimeout(changedTimer)
changedTimer = setTimeout(function () { load() }, 260)
})
}
} catch (e) { /* 旧宿主没有 onChanged:退回可见性刷新 + 手动刷新 */ }
try {
if (typeof IntersectionObserver === 'function') {
var io = new IntersectionObserver(function (entries) {
for (var i = 0; i < entries.length; i++) {
if (entries[i].isIntersecting) {
// v1.6.7:面板真正可见后再量一次宽度并重排(首帧可能还是 0 宽)
try { measure(); renderGrid() } catch (e) { /* ignore */ }
autoRefresh()
}
}
}, { threshold: 0.15 })
io.observe(wrap)
}
document.addEventListener('visibilitychange', function () { if (!document.hidden) autoRefresh() })
window.addEventListener('focus', autoRefresh)
} catch (e) { /* 环境不支持则只保留手动刷新 */ }
// 先读配置,再拉列表
Promise.resolve(ctx.data && ctx.data.read ? ctx.data.read() : {}).then(function (d) {
if (d && d.cfg) cfg = Object.assign({}, DEF, d.cfg)
buildSettings() // 设置浮层里的下拉要反映读到的配置
return load()
}).catch(function () { buildSettings(); load() })
return function dispose () {
if (ro) { try { ro.disconnect() } catch (e) { /* ignore */ } }
clearTimeout(changedTimer)
try { if (typeof unsubChanged === 'function') unsubChanged() } catch (e) { /* ignore */ }
try { document.removeEventListener('pointerdown', onMenuDown, true) } catch (e) { /* ignore */ }
try { document.removeEventListener('keydown', onMenuKey, true) } catch (e) { /* ignore */ }
try { document.removeEventListener('drop', onDocDrop, true) } catch (e) { /* ignore */ }
closeMenu()
}
}
global.IWBPluginHost.register({
id: 'gallery',
name: '图库',
version: '1.7.0',
apiVersion: 1,
capabilities: ['panels', 'gallery'],
data: { schemaVersion: 1, maxBytes: 65536 },
}, function (ctx) {
ctx.ui.registerPanel({
id: PANEL_ID,
title: '图库',
icon: 'ref',
mount: function (host) { return mount(host, ctx) },
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
+79
View File
@@ -0,0 +1,79 @@
/* 图库插件样式(v1.5.0)
* 为什么放插件里:宿主 style.css 只在客户端发版时更新,而这里是「设置浮层/图标按钮/紧凑间距」这类
* 高频视觉调整——随插件更新即可生效,不必重发桌面端。选择器均带 .iwb-gal-* / .iwb-history-* 前缀,
* 且比宿主同名规则更具体(.iwb-gal-foot .iwb-gal-icobtn),宿主旧样式不会盖回来。
*/
/* ---- 面板留白:边缘收小,避免窄栏里浪费空间 ---- */
.iwb-history-embedded { padding: 6px 6px 4px; gap: 6px; }
.iwb-history-embedded .iwb-history-grid { gap: 6px; padding: 0 0 2px; justify-content: flex-start; }
/* 列宽由插件按「图幅」写死(style width),这里禁用宿主的 flex:1 拉伸 */
.iwb-history-embedded .iwb-history-col { flex: 0 0 auto; gap: 6px; }
/* ---- 顶栏 ---- */
.iwb-gal-head { display: flex; align-items: center; gap: 6px; min-height: 0; }
.iwb-gal-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
.iwb-gal-actions .iwb-btn-sm { padding: 2px 6px; }
/* ---- 底栏:左信息 / 右工具组 ---- */
.iwb-gal-foot {
display: flex; align-items: center; justify-content: space-between; gap: 6px;
min-width: 0; padding-top: 6px; border-top: 1px solid var(--iwb-border);
}
.iwb-gal-foot-left { display: flex; align-items: center; gap: 6px; min-width: 0; flex: 0 1 auto; overflow: hidden; }
.iwb-gal-count { font-size: 11px; color: var(--iwb-text2); white-space: nowrap; }
.iwb-gal-sel { font-size: 11px; color: var(--iwb-brand); white-space: nowrap; }
.iwb-gal-status { font-size: 11px; color: var(--iwb-text2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 0 1 auto; max-width: none; }
.iwb-gal-tools { display: flex; align-items: center; gap: 0; flex: 0 0 auto; margin-left: auto; }
/* ---- 图标按钮:无外框、无底色,只在悬停时给一点反馈 ---- */
.iwb-gal-foot .iwb-gal-icobtn,
.iwb-gal-foot .iwb-gal-icobtn:hover,
.iwb-gal-foot .iwb-gal-icobtn:active {
width: 20px; height: 20px; min-width: 20px; padding: 0; box-sizing: border-box;
display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto;
border: 0; box-shadow: none; background: transparent; border-radius: 6px;
color: var(--iwb-text2); line-height: 1; transform: none;
}
.iwb-gal-foot .iwb-gal-icobtn svg { display: block; pointer-events: none; }
.iwb-gal-foot .iwb-gal-icobtn:hover { background: var(--iwb-layer2); color: var(--iwb-text); }
.iwb-gal-foot .iwb-gal-icobtn:focus-visible { outline: 2px solid color-mix(in srgb, var(--iwb-brand) 60%, transparent); outline-offset: 1px; }
.iwb-gal-setbtn-on { color: var(--iwb-brand); background: var(--iwb-layer2); }
/* ---- 设置浮层(三个下拉不占前台) ---- */
.iwb-gal-settings {
position: absolute; right: 8px; bottom: 34px; z-index: 30; width: 176px; max-width: calc(100% - 16px);
display: flex; flex-direction: column; gap: 8px; padding: 8px 10px;
background: var(--iwb-layer); border: 1px solid var(--iwb-border); border-radius: 8px;
box-shadow: 0 6px 18px rgba(0, 0, 0, .14);
}
.iwb-gal-settings-title { font-size: 11px; font-weight: 600; color: var(--iwb-text2); }
.iwb-gal-setrow { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 11px; color: var(--iwb-text2); }
.iwb-gal-setlabel { flex: 0 0 auto; }
.iwb-gal-setrow select { flex: 1 1 auto; width: auto; min-width: 58px; max-width: 92px; height: 22px; font-size: 11px; padding: 0 2px 0 4px; }
/* ---- 图片墙 ---- */
.iwb-history-grid { overscroll-behavior: contain; }
.iwb-history-embedded .iwb-history-item { position: relative; flex: none; width: 100%; }
.iwb-history-embedded .iwb-history-item img {
width: 100%; height: auto; display: block; object-fit: contain; margin: 0 auto;
border-radius: 6px; border: 1px solid var(--iwb-border); background: var(--iwb-layer2); cursor: pointer;
}
.iwb-history-missing {
display: flex; align-items: center; justify-content: center; text-align: center;
min-height: 84px; padding: 8px; border-radius: 6px; border: 1px dashed var(--iwb-border);
font-size: 11px; color: var(--iwb-text2); background: var(--iwb-layer2); word-break: break-all;
}
.iwb-history-actions { display: flex; gap: 4px; padding: 4px 2px 0; }
.iwb-history-actions .iwb-btn-sm { padding: 2px 6px; font-size: 11px; }
.iwb-history-more { display: flex; justify-content: center; padding: 4px 0 2px; }
/* 只作用于图库自己的空态提示:不加前缀会泄漏到设置页等使用 .iwb-hint 的地方(文字被居中) */
.iwb-history-embedded .iwb-hint { font-size: 11px; color: var(--iwb-text2); text-align: center; padding: 12px 6px; }
/* ---- v1.6.0:失败统计 / 右键菜单标题(v1.6.1 去掉搜索框)---- */
.iwb-gal-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.iwb-gal-fail {
font-size: 11px; color: var(--iwb-err); cursor: pointer; white-space: nowrap;
text-decoration: underline dotted; text-underline-offset: 2px;
}
.iwb-gal-fail:hover { color: var(--iwb-err); opacity: .85; }
.iwb-gal-menu .iwb-ctx-title { max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/grouplib",
"private": true,
"version": "1.0.5",
"description": "节点组:左栏收藏的节点组列表(分组/改名/删除/拖入画布实例化),数据由宿主 grouplib 能力提供",
"ibwPlugin": {
"id": "grouplib",
"entry": "src/index.js",
"apiVersion": 1
}
}
+455
View File
@@ -0,0 +1,455 @@
// 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)
var loadError = '' // '' = 正常;否则是给用户看的原因(据此区分「真没收藏」和「能力没拿到」)
function load () {
if (typeof api.list !== 'function') {
loadError = '节点组能力未就绪(客户端需 ≥ 3.25.56)'
list = []; ggroups = []
render()
return Promise.resolve(false)
}
return Promise.resolve(api.list()).then(function (r) {
loadError = ''
list = (r && r.groups) || []
ggroups = (r && r.groupGroups) || []
render()
return true
}).catch(function (e) {
loadError = '读取失败:' + ((e && e.message) || e || '未知错误')
list = []; ggroups = []
render()
return false
})
}
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)
var refresh = el('button', { class: 'iwb-btn iwb-btn-sm', title: '重新向宿主拉取节点组', text: '↻' })
refresh.addEventListener('click', function () { load() })
topRow.appendChild(refresh)
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)
// 分类胶囊:宿主 .iwb-lib-chips 是 nowrap(配 .iwb-lib-chips-scroll 才单行滚动),
// 分组多时右侧胶囊会被面板宽度裁掉看不见 ⇒ 这里改成「适应面板宽度自动换行」,
// 换行规则在插件自带 styles.css 的 .iwb-glp-chips 里(样式随插件发,不用等客户端发版)
var chips = el('div', { class: 'iwb-lib-chips iwb-glp-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-glp-add iwb-chip-add', title: '新建分组', text: '+' })
addChip.addEventListener('click', function () { newOpen = !newOpen; render() })
chips.appendChild(addChip)
var mgChip = el('button', { class: 'iwb-chip iwb-glp-add 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-glp-card iwb-pcard' + (isEditing ? ' iwb-pcard-editing' : '') + (manage && picked[g.id] ? ' iwb-pcard-selected' : ''),
'data-manage': manage ? '1' : '0',
draggable: isEditing ? 'false' : 'true',
title: manage ? '单击选中 · 右上「移动到分组」' : '双击改名 · 拖到画布实例化 · 右键移动到分组',
})
card.addEventListener('dragstart', function (e) {
if (isEditing) return
try { card.classList.add('iwb-glp-dragging') } catch (err) { /* ignore */ }
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('dragend', function () {
try { card.classList.remove('iwb-glp-dragging') } 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) {
var hint = loadError
? loadError
: (list.length
? '当前分组下没有节点组(共 ' + list.length + ' 个,切到「全部」查看)'
: '宿主返回 0 个收藏节点组。画布编组后点组右上角「收藏」,或用右键菜单「收藏选中节点」。')
scrollBox.appendChild(el('div', { class: 'iwb-hint iwb-glp-empty', text: hint }))
}
}
// 宿主侧变化(画布收藏节点组 / 其它标签页同步)→ 重拉
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.5',
apiVersion: 1,
capabilities: ['panels', 'grouplib'],
data: { schemaVersion: 1, maxBytes: 65536 },
}, function (ctx) {
ctx.ui.registerPanel({
id: PANEL_ID,
title: '节点组',
icon: 'group',
// 宿主只调用 mount(node)(一个参数):必须在这里把工厂 ctx 注入,否则面板里 ctx 是 undefined ⇒ 首渲染抛异常 ⇒ 整块空白
mount: function (host) { return mount(host, ctx) },
})
})
})(typeof window !== 'undefined' ? window : globalThis)
+42
View File
@@ -0,0 +1,42 @@
/* grouplib(节点组)自带样式
作用域全部带 .iwb-glp-*,不影响宿主与其他插件;样式随插件发布,不必等客户端发版。 */
/* 分类胶囊「适应面板宽度」自动换行。
宿主的 .iwb-lib-chips 是 flex-wrap: nowrap(配合 .iwb-lib-chips-scroll 才做单行横向滚动),
分组多时右侧胶囊会被面板宽度裁掉、看不见也用不了。
这里用双类选择器提高优先级(不依赖样式注入顺序),让它按宽度折行。 */
.iwb-lib-chips.iwb-glp-chips {
flex-wrap: wrap;
row-gap: 6px;
}
/* + / ⚙ 是动作按钮,不是分组名:不参与压缩,并与最后一个分组稍作分隔 */
.iwb-glp-chips .iwb-glp-add {
flex: 0 0 auto;
margin-left: 2px;
}
/* v1.0.4(2026-11-21):卡片交互态 + 空态 + 拖拽反馈。
颜色只走宿主 token(--iwb-plugin-* / --iwb-*),不写死。 */
.iwb-glp-card { transition: background .12s ease, border-color .12s ease; }
.iwb-glp-card .iwb-pname { font-weight: 600; }
/* 删除按钮:平时隐藏,悬停/键盘聚焦才出现,减少视觉噪音 */
.iwb-glp-card .iwb-pbtns { opacity: 0; transition: opacity .12s ease; }
.iwb-glp-card:hover .iwb-pbtns,
.iwb-glp-card:focus-within .iwb-pbtns { opacity: 1; }
/* 管理模式的选中标记:右上角圆点 */
.iwb-glp-card[data-manage="1"]::after {
content: ''; position: absolute; right: 8px; top: 8px; width: 12px; height: 12px;
border-radius: 50%; border: 1.5px solid var(--iwb-border2, #b9bfca); background: transparent;
}
.iwb-glp-card[data-manage="1"].iwb-pcard-selected::after {
background: var(--iwb-brand, #6b7280); border-color: var(--iwb-brand, #6b7280);
}
/* 拖拽中:半透明 + 轻微缩放,明确"正在搬运" */
.iwb-glp-dragging { opacity: .55; }
/* 空态:虚线框 */
.iwb-glp-empty {
margin: 4px 0; padding: 12px 12px; border-radius: 10px; text-align: center;
border: 1px dashed var(--iwb-border2, #b9bfca); color: var(--iwb-text2, #4d5668);
font-size: 12px; line-height: 1.7;
}
File diff suppressed because it is too large. Load diff
+387
View File
@@ -0,0 +1,387 @@
# 简化版 PS(Image Editor Lite)目标与实施分析
> 基线:`image-annotate` v1.0.5(`plugin-image-annotate.cfecb6e2ec17.js`),桌面宿主 `image-workbench-desktop` 插件 API v1。
> 本文只做目标定义、差距分析、UI/架构/分期设计,**不含代码改动**。改动前先确认文末「待拍板」一节。
>
> **范围裁定(用户确认)**:只做**单张图片**的编辑与输出,**不做批量出图 / 多图队列 / 批量导出**;
> UI 以「**便利 / 顺手**」为第一目标,不以「像 PS」为目标 —— 菜单层级、弹窗、确认步骤能省则省。
>
> **决策裁定(2026-11-04)**:① 选区 `Delete` **只作用当前图层**;②「清空标注」=**全部还原到打开时的原图**(删掉所有非原图图层 + 清掉所有绘制/变换,且可撤销);③ **≤500KB 做成输出预设**(不默认产两个文件);④ **浮动操作条先实现、上线后由用户实际体验再裁定**保留/调整/移除,本轮不因「待体验」而停工。详见 §8。
---
## 0. 结论先行
现在的插件是一个**功能很强的标注器**,但还不是一个**图像编辑器**。差距不在「工具数量少」(已有 11 个工具),而在三根缺失的柱子:
| 柱子 | 现状 | 对齐目标后 |
| ----- | ------------------------------------------ | ------------------------------ |
| 选区 | 只有裁剪框(`S.cropRect`)和钢笔路径,没有「可作用于像素的选区」 | 框选 → 复制/剪切到新层 / 清除 / 填充 / 限制画笔 |
| 非破坏性 | `confirmCrop()` 把所有可见层 flatten 成一张图,并清空撤销栈 | 裁剪、变换、图层结构都可撤销;导出时才合成 |
| 输出工作流 | 只有 PNG Blob → 覆盖/新建节点 | 单张:格式、尺寸、背景、体积上限、下载/剪贴板可配置 |
建议路径:**先重做地基与 UI(P0)→ 上选区(P1)→ 修裁剪/画布(P2)→ 图层增强(P3)→ 输出工作流(P4)**。
不要直接往现有 `events.js` 里堆选区分支:它已经 1416 行,`e `40 行且后半段是补丁叠加,继续堆会很快失控。
> 便利性不改变架构判断,反而强化了 P0 的必要性:高频动作要「就地、一步可达」,靠的是命令层与统一状态机,而不是往菜单里加更多条目。
---
## 1. 目标定义
### 1.1 产品目标
在宿主画布上选中**一张**图片节点后,不离开画布即可完成:
```
打开图片 → 框选/抠出局部 → 图层化编辑 → 裁剪 / 改尺寸 → 按规范导出 → 回写节点
```
典型场景:截图里圈出商品 → 复制成独立层 → 擦掉多余部分 → 裁成 800×800 → 导出当前这一张。
**一次会话只处理一张图,输出一次只产出一个结果**;不引入队列、批量选择、批量命名、批量下载等概念。
### 1.2 明确不做(边界)
| 不做 | 原因 |
| ------------------------------- | -------------------------------------------- |
| **批量出图 / 多图队列 / 批量导出 / 批量改名** | 用户明确排除;单张处理即可,避免把编辑器做成队列面板 |
| 调色:曲线 / 色阶 / HSL / 色彩平衡 / 色相饱和度 | 用户明确排除;牵涉色彩管理与 LUT,收益低 |
| 滤镜 / 模糊 / 锐化 / 降噪(作为调色类功能) | 同上;**羽化**作为选区属性保留 |
| CMYK / 16bit / RAW / ICC / 印刷输出 | 浏览器 Canvas 2D 只有 8bit sRGB |
| 智能对象 / 动作 / 脚本 / 通道 / 路径面板 | 复杂度远超「简化版」 |
| AI 抠图 | 已有外部链路(`xianyi-cutout` / 本地 rembg),插件只负责后期修图 |
| 非破坏性蒙版式调色图层 | 一期不需要;P3 只做「图层蒙版」这一项 |
| 完整菜单栏(文件/编辑/图像/图层/选择/视图…) | 与「便利」冲突;低频命令收进一个「更多」下拉 |
### 1.3 与 PS 的能力对照
| PS 能力 | 简化版取舍 |
| ------------------------------ | ----------------------------- |
| 选框 / 套索 / 魔棒 | ✅ 矩形、椭圆、多边形、自由套索;魔棒放二期 |
| 选区变换 / 加减 / 反选 / 羽化 | ✅ 一期全做(羽化用 Canvas filter) |
| 复制 / 剪切到新图层、清除、填充、描边 | ✅ 核心,且做成选区旁的浮动操作条 |
| 图层 / 显隐 / 锁定 / 不透明度 / 排序 | ✅ 已有(不透明度 v1.7 才真正可调,之前只有字段没有控件) |
| 混合模式 / 图层蒙版 / 编组 / 缩略图 | 🟡 缩略图与重命名 v1.7 已补;混合模式 / 蒙版 / 编组仍待做 |
| 裁剪 / 画布大小 / 图像大小 / 旋转翻转 | 🟡 P2 补,且改为可撤销 |
| 自由变换(Ctrl+T) | 🟡 已有选中对象的移动/缩放/旋转,P2 扩展到选区内容 |
| 画笔 / 橡皮 / 文字 / 形状 / 吸管 / 抓手 | ✅ 已有,不重写 |
| 历史面板 / 多步撤销 | ✅ 已有栈,P0 补标签与面板 |
| 导出 / 存储为 Web 所用格式 | 🟡 P4,单张可配置预设 |
| 菜单栏 / 批量处理 / 滤镜 / 调色 / 3D / 印刷 | ❌ 不做 |
---
## 2. 现状盘点(代码级)
| 能力 | 实现位置 | 关键事实 |
| ------ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| 11 个工具 | `editor/dom.js` 工具栏 + `editor/events.js` 分发 | select / brush / eraser / pen / text / rect / circle / arrow / picker / hand / crop |
| 位图图层 | `editor/viewport.js#setupCanvas` | 初始 `base`(locked, z=0) + `draw`(z=1);**每个图层都是 imgW×imgH 全幅 canvas** |
| 矢量对象 | `editor/objects.js` `layerUnits()` | 文字/形状/钢笔按 z 与位图混排,1.0.5 已统一为唯一真源 |
| 图层面板 | `editor/layers.js#renderLayerPanel` | 显隐 / 锁定 / 删除 / 颜色 / 线宽 / 透明度 / 拖拽排序 / 4 个排序按钮;**无缩略图、无混合模式、无编组、无多选** |
| 历史 | `editor/history.js` | `snapshotState()` 像素快照;50 条 + 32–128MB 双预算;`restorePath()` 决定哪些层跳过像素 |
| 裁剪 | `editor/crop.js#confirmCrop` | `getCompositeCanvas()` → flatten → `setupCanvas(cropC)` 重建所有层 → 改 `S.imgW/imgH` → **`S.history=[]`**;比例/尺寸约束;越界部分透明 |
| 图片放置 | `editor/placement.js` | 粘贴/导入先进入放置模式(移动/8 手柄/旋转),**必须 Enter 或点击外部确认才落层** |
| 剪贴板 | `editor/events.js#onPaste` | document 捕获阶段,命中图片即 `stopImmediatePropagation()`(防宿主 window 抢粘贴) |
| 视图 | `editor/viewport.js` | zoom 0.1–10、自由平移、`overlayPad` 交互外扩、`getPos()` 统一坐标换算 |
| 输出 | `editor/index.js#exportResult` | 固定 PNG `toBlob` → `glue.js` 转 dataURL → `setNodeImage` / `createImageNode` |
| 内存 | `editor/index.js#releaseEditorMemory` | `close()` 释放所有像素、原图、历史;**会话状态不保留** |
| 宿主 | `plugin/glue.js` | 只对 `ref` 节点暴露;`ctx.canvas.*`;`ctx.storage` 是宿主提供的小容量命名空间 KV,**不是像素仓库** |
---
## 3. 差距矩阵
优先级:P0=地基(必须先做) / P1=选区核心 / P2=图像与裁剪 / P3=图层 / P4=输出 / P5=打磨。
### 3.1 选区(当前完全没有)
| 缺口 | 影响 | 优先级 |
| ------------------------- | -------------- | ------------------- |
| 无矩形/椭圆/多边形/套索选区 | 无法「抠出局部」「只擦一块」 | P1 |
| 无蚂蚁线、无加减选、无反选/全选/取消 | 选区不可见、不可调整 | P1 |
| 无羽化 | 边缘生硬,合成痕迹明显 | P1 |
| 无复制/剪切到新层、Delete 清除、填充/描边 | 选区没有落点,等于没用 | P1 |
| 选区不能约束画笔/橡皮 | 精细化修图做不到 | P1(可后置) |
| 魔棒 / 色彩范围 | 纯色背景一键去背 | P2+(worker 受限,见 §7) |
### 3.2 非破坏性与裁剪(当前是最大架构债)
| 缺口 | 具体表现 | 优先级 |
| ---------------------- | ------------------------------------------------------------------- | ------------- |
| 裁剪即 flatten | `confirmCrop()` 合成所有可见层 → 重建 `base`/`draw`,图层结构全部丢失 | P2 |
| 裁剪不可撤销 | `S.history = []; S.redoStack = []` | P2 |
| 裁剪丢变换信息 | 已核查(v1.7):`drawShape`/文字都用**由几何派生**的包围盒中心做旋转轴,裁剪缩放了几何就等于缩放了轴心,角度本身不随缩放变化 ⇒ 形状的旋转不需要单独处理。残留近似:文字在**非等比**缩放下只按 `scaleX` 缩放字号(等比裁剪精确) | P2(降级为已知近似) |
| 无「画布大小」/「图像大小」 | 只能靠裁剪栏的「尺寸约束」间接缩放 | P2 |
| 无 90° 旋转 / 水平垂直翻转 / 拉直 | 基础图像操作缺失 | P2 |
| 全幅画布模型 | 每个图层都被钉死在 imgW×imgH,裁剪必须重画所有层 | P0 设计 / P2 实施 |
### 3.3 图层
| 缺口 | 说明 | 优先级 |
| ------------------ | ----------------------------------------------------------------------------------------------- | ---------- |
| ~~无缩略图~~ | ✅ v1.7:22px 缩略图 + 90ms 合批;空图层回落到类型图标 | 已完成 |
| 无混合模式 | 正片叠底/滤色/叠加是合成常用 | P3 |
| 无图层蒙版 | 抠图只能破坏性擦除,不能反悔 | P3 |
| ~~无重命名 / 多选~~ / 编组 | ✅ v1.7:双击名字改名(自算双击)、⌘/Ctrl 点击多选合并;编组仍待做 | 部分完成 |
| ~~拖动排序不生效~~ | ✅ v1.8.3:整项 `draggable` 会吃掉子元素的原生拖动(滑杆只能点不能拖)、向下拖一格索引回退等于原地不动。改为指针拖动 + 实时插位,松手读 DOM 顺序落地 | 已完成 |
| `resetDraw()` 语义歧义 | 「清空标注」只清非 base 层像素,留下空白粘贴层(1.0.5 遗留)⇒ **已裁定改为「全部还原」**:删所有非 base 层 + 清绘制 + 复位变换,一步可撤销;按钮改名「还原原图」 | P0 定语义(已定) |
### 3.4 输出(单张)
| 缺口 | 说明 | 优先级 |
| -------------- | ------------------------------------------------------------------------------------ | ----------- |
| 只有 PNG | 无 JPG/WebP、无质量控制 | P4 |
| 无背景切换(透明 / 白底) | 电商出图要手工来回切换 | P4 |
| 无体积上限策略 | 无法保证 ≤500KB 这类交付规范 ⇒ **已裁定做成可切换预设**(800×800 / 长边 640 / 质量迭代 ≤500KB,存 `ctx.settings`) | P4(随 P1 带上) |
| ~~无下载 / 复制到系统剪贴板~~ | ✅ v1.9.0:顶栏「导出」下载;「复制」把结果编成 PNG 写 `ClipboardItem`,粘进聊天窗口/后台上传框,不关闭编辑器。非安全上下文无 `navigator.clipboard` 时明确提示改用导出 | 已完成 |
| 导出步骤偏多 | 覆盖 / 新建 / 退出三个按钮分散,没有「记住上次选择」 | P0 / P4 |
| 导出后图层信息丢失 | 节点里是一张扁平 PNG,下次打开要从头来 | P5(需宿主配合) |
### 3.5 交互、快捷键、状态
| 缺口 | 说明 | 优先级 |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- |
| 快捷键是数字 1–0 | 无 PS 习惯的 V/B/E/M/L/C、Ctrl+A/C/X/V/J/D/T/Z | P0 映射层 / P5 全量 |
| `Ctrl+V` 已被占用 | 现在恒定「贴为新图层」,与「粘贴选区内容」语义冲突,需明确规则 | P1 |
| Delete 只删文字/形状 | 位图层内容不能一键清除 | P1 |
| 无右键菜单 / 无工具选项栏 / 无状态栏 | 参数散落、当前状态不可见 | P0 |
| 错误提示用 `window.alert` | `pasteImageFromUrl` 失败直接弹窗,无 toast | P0 |
| 图片放置要二次确认 | 拖完还得按 Enter,多一步 | P0(便利性) |
| overlay 单 canvas 多用 | 裁剪遮罩、选中框、笔刷环、放置预览、提示文字全在 `S.overlayCanvas`,共用 `clearOverlay()`;**加蚂蚁线必然互相擦除** | P0 |
| `editor.css` 补丁堆积 | 1340 行,后半段大量 `!important`;工具栏 `position:absolute; top:68px`,撤销按钮 `right:154px` 等魔数;`.iwb-editor-footer` 空且 `display:none`;`.iwb-editor-zoom-hint` 绝对定位 | P0 |
| 无响应式 / 无亮色主题 | 窄窗口下 290px 图层面板 + 44px 工具栏挤压画布 | P5 |
| 关闭即清空 | 无草稿、无二次编辑;`ctx.storage` 只是宿主提供的小容量命名空间 KV | P5 |
---
## 4. 目标 UI 布局(便利优先的轻量四区)
**放弃上一版的「PS 式六项菜单栏」**:对单张处理来说,菜单树、多 tab 面板、层层确认都是负担。改成一条精简顶栏 + 就地选项 + 就近操作:
```
┌──────────────────────────────────────────────────────────────────────┐
│ A 顶栏 44px 图片编辑 · 800×800 ↶ ↷ [更多 ▾] 覆盖 新建 下载 │
├──────────────────────────────────────────────────────────────────────┤
│ B 就地选项栏 36px 当前工具只露 2–3 个参数:羽化 0 · 模式 新建 · ▾ │
├────┬──────────────────────────────────────────────┬─────────────────┤
│ C │ D 画布工作区 │ E 图层面板 │
│ 工 │ ┌──────────────┐ │ 260px,默认开 │
│ 具 │ │ 选区(蚂蚁线)│ ┌─────────────────┐ │ 一键收起 ⇥ │
│ 栏 │ │ │ │ 复制 剪切 删除 │ │ 图层 / 历史 │
│ 40 │ └──────────────┘ │ 填充 反选 取消 │ │ 两个 tab │
│ px │ G 选区浮动条 ───┴─────────────────┘ │ │
├────┴──────────────────────────────────────────────┴─────────────────┤
│ F 状态栏 26px 100% | 800×800 | x 312 y 208 | 选区 240×180 | 画笔 │
└──────────────────────────────────────────────────────────────────────┘
```
设计要点:
1. **A 顶栏不做菜单栏**:只放标题/尺寸、撤销重做、一个「更多 ▾」(低频命令:复原、画布大小、旋转翻转、清空…)、以及**常驻的一步输出**(覆盖 / 新建 / 下载)。输出动作记住上次选择,不必每次重新点选。
2. **B 就地选项栏**:只露当前工具最常用的 2–3 个参数,其余收进「▾」。选区 = `模式 + 羽化`;裁剪 = `比例 + 尺寸`;画笔 = `大小 + 硬度`。避免一屏塞满滑块。
3. **G 选区浮动操作条是便利性的核心**:选完框,操作条就出现在选区旁边(不遮内容、可自动避让边界),直接点 `复制为新层 / 剪切 / 删除 / 填充 / 反选 / 取消`。不用去菜单、不用记快捷键,也支持右键菜单与键盘双入口。
4. **E 面板只留两个 tab**:图层(默认)、历史。属性/预设并入选项栏或「更多」,不再叠第三个面板。面板可一键收起,收起后画布自动吃满;窄窗口默认收起。
5. **C 竖工具栏分组**:选择 / 选区组 / 绘制组 / 矢量组 / 视图组;同类工具长按或右键展开,减少图标数量。图标保持现有 SVG 风格,不引第三方图标库(CSP)。
6. **F 状态栏**显示缩放、图像尺寸、光标坐标、选区尺寸、当前工具/图层;替代现在浮在画布上的 `zoom-hint`。尺寸可点开就地输入。
7. **保留肌肉记忆**:数字键 1–0 继续可用,同时新增 PS 字母键;现有标注流程不被打断。
### 4.1 便利性准则(验收口径)
| 准则 | 具体做法 | 反例(不做) |
| --------- | --------------------------------------------------- | ---------------------- |
| 高频动作 0 层级 | 选区操作浮动条、输出按钮常驻顶栏、图层显隐/锁定就地点击 | 先开菜单 → 子菜单 → 对话框 |
| 低频动作 1 层级 | 「更多 ▾」一次展开,展开后可常驻 | 二级子菜单、向导式多步 |
| 少确认 | 粘贴/导入图片拖完即落层(提供 Esc 撤销,取消 Enter 确认);裁剪确认保留一次(破坏性较大) | 每个操作都弹「确定吗」 |
| 撤销可兜底 | 任何一步都能 Ctrl+Z 回退,包括裁剪与选区清除 | 清空历史、不可撤销的破坏性操作 |
| 状态可见 | 状态栏常驻尺寸/坐标/选区/当前层;toast 取代 `window.alert` | 只在 console 报错、浮层提示一闪而过 |
| 记住选择 | 上次输出格式、背景、尺寸预设、面板开合存 `ctx.settings` | 每次打开都回到默认值 |
| 就地编辑 | 尺寸、比例、羽化直接输入数字;选区可拖动、8 手柄调整、实时显示 W×H | 打开属性面板改参数 |
| 三种入口并存 | 浮动条 / 右键菜单 / 快捷键,任一都会走同一 `execute()` | 三条路径各实现一遍 |
| 画布优先 | 面板默认 260px 且可收起;工具栏 40px;窄窗口自动收面板 | 固定 290px 面板 + 常驻色板挤压画布 |
| 无队列 | 一次一张、一次一个结果;不做批量勾选、批量命名、批量下载 | 输出队列、任务进度条、批量结果列表 |
> 「便利」的实现依赖 P0 的命令层:浮动条、右键菜单、快捷键只是三个**视图**,背后必须是同一条 `execute(label, mutator)`,否则便利会变成三套逻辑各修一遍。
改造落点:`editor/dom.js` 的 `innerHTML` 骨架重写 → `editor/editor.css` 按 `base / layout / toolbar / optionbar / panels / canvas / overlays / floating` 分层重写(删掉 900 行之后的补丁段)→ `editor/events.js` 的 `bindIf()` / `querySelector` 选择器同步 → `updateToolUI()` / `updateBrushParamUI()` 改成「渲染选项栏」→ 新增 `floating.js` 负责选区操作条的定位与避让。
---
## 5. 架构改造(选区之前的地基)
### 5.1 命令层 `editor/commands.js`(P0)
现在 `saveSnapshot()` 散落在 20 多处,裁剪干脆绕过历史。统一为:
```
execute(label, mutator)
→ 前置检查(交互态互斥、图层锁定)
→ snapshotState(带 label / 时间戳)
→ mutator() 只改状态
→ renderObjects + renderLayerPanel + 重绘 overlay
→ pushHistory
```
收益:所有新功能(选区清除、复制、剪切、裁剪、变换)自动获得撤销/重做与历史面板;浮动条、右键菜单、快捷键共用这一条路径。
### 5.2 交互状态机 `editor/interaction.js`(P0)
把 `idle / drawing / placing / cropping / marquee / transforming / panning / textEditing` 显式建模,统一 `enter()/cancel()/commit()`。现状是 `setTool()` 里十几个 `if (tool !== ...)` 手动清状态,加一个选区工具要再补五个判断——这是继续堆叠的主要风险。
### 5.3 选区模型 `editor/selection.js`(P1)
```
S.selection = {
kind: 'rect' | 'ellipse' | 'polygon' | 'lasso',
mode: 'new' | 'add' | 'subtract' | 'intersect',
path: Path2D, // 图片坐标系,供 clip / destination-out / 导出共用
bbox: { x, y, w, h }, // 局部 tile 的边界,也是浮动条定位依据
feather: 0..20, // px
active: boolean
}
```
- 掩膜用**一张局部 alpha mask canvas**(只覆盖 bbox,不是全幅),由 `path` 填充 + `ctx.filter='blur(Npx)'` 得到软边。
- `selectionPath()` 是唯一真源:清除、复制、剪切、填充、描边、限制画笔全部走它,不各写一套。
- 与裁剪互斥:裁剪工具激活时清空选区,选区工具激活时 `cancelCrop()`。
- `restoreState()` 需要能恢复选区(或明确「撤销不动选区」并写进文档)。
### 5.4 Overlay 分层(P0)
在 `.iwb-editor-canvas-stack` 内拆成三个独立 canvas,各管各的 `clear()`:
| 层 | 内容 |
| ------------------- | ---------------------------------- |
| `interactionCanvas` | 选中框、8 手柄、旋转弧、放置预览、裁剪遮罩 |
| `selectionCanvas` | 蚂蚁线(rAF 驱动 `lineDashOffset`)、选区外暗化 |
| `cursorCanvas` | 笔刷环、吸管提示光标 |
现在 `clearOverlay()` 一擦全擦,加蚂蚁线后必然与裁剪框/选中框互相打架,必须先拆。浮动操作条是 **DOM 元素**(不是画在 canvas 上),便于点击、键盘可达与本地化。
### 5.5 非破坏性文档模型(P2 的选型)
现有模型是「每个图层 = 全幅 imgW×imgH 画布」,画布尺寸就是图片尺寸,所以裁剪只能重画所有层。两条路线:
| 路线 | 做法 | 改动面 | 结论 |
| --- | --- | --- | --- |
| 路线 1(低风险) | 仍是全幅层,但裁剪时**逐层按裁剪框平移/复制像素**,不 flatten;裁剪前存快照 ⇒ 可撤销、图层保留 | 只动 `crop.js` + `history.js` | **P2 先走这条**,能立刻解决「裁完图层全没、不能撤销」 |
| 路线 2(正解) | 图层改为「局部画布 + transform(x,y,w,h,rotation)」,画布只是视口;裁剪只改视口与偏移,导出时按视口合成 | 命中测试 / 合成 / 历史 / 放置 / 所有绘制模块全要改 | 作为 v2 架构单独评估,不与 P1 选区捆绑 |
路线 2 才是真正的 PS 模型(图层可以比画布大、可以移出边界),但要和 P1 抢工期,建议先把选区做出来验证价值,再决定要不要重构。
### 5.6 输出管道 `editor/export.js`(P4,单张)
```
getCompositeCanvas() // 当前这一张
→ (可选)按输出尺寸重采样 / 加背景(透明 / 白 / 自定义色)
→ 编码 png | jpeg | webp,质量迭代到 ≤ 目标 KB
→ 一次输出一个结果:覆盖节点 / 新建节点 / 下载 / 复制剪贴板
```
- 默认**单结果**;「透明 PNG / 白底 JPG」是同一张图的**格式 + 背景单选开关**,一次只产出一个文件,不引入队列、不默认双输出。
- 预设(格式 / 背景 / 尺寸 / 体积上限)存 `ctx.settings`,下次打开直接沿用;顶栏按钮显示当前预设名。
- **≤500KB 预设(已裁定)**:勾上后按 800×800 输出(商品长边 640px),先按目标格式编码,超出阈值就降 JPG/WebP 质量重编码,PNG 超限时提示改用 JPG 或缩小尺寸;迭代上限 8 次,仍不达标就给出实际体积 + toast,不静默失败。默认不勾选。
- 与现有 `glue.js` 的接口保持 `onResult(out, mode)` 不变,扩展 `mode` 或新增 `onExport(payload)`,避免动宿主。
---
## 6. 分期路线与验收
| 期 | 交付 | 验收 |
| --- | --- | --- |
| **P0 地基 + 轻量 UI** | 精简顶栏、就地选项栏、状态栏、图层面板可收起、命令层、状态机、overlay 分层、toast、CSS 重构、快捷键映射层、定义 `resetDraw` 语义、放置免二次确认 | 功能零变化;**高频动作点击层级 ≤1**、无新增弹窗;桌面客户端 e2e 22/22 全绿;`npm run build` + `npm run validate`;发布契约 6/6 |
| **P1 选区核心** | 矩形/椭圆/多边形/套索;加选减选、全选/反选/取消、羽化、蚂蚁线;**选区浮动操作条 + 右键菜单**;复制/剪切到新层、Delete 清除(**仅当前层**)、填充/描边;附带「还原原图」与「≤500KB」预设 | 框选后浮动条一步完成复制;Ctrl+J 新层像素正确且原层不变;**Delete 后其它层像素原样、当前层挖空且可撤销**;base 锁定提示;「还原原图」后只剩 base 且 Ctrl+Z 能全恢复;预设输出 ≤500KB;选区与裁剪/放置互斥;三条入口结果一致 |
| **P2 图像与裁剪** | 非破坏性裁剪(路线 1)、画布大小、图像大小、90° 旋转 / 翻转、尺寸预设(点击即用)、裁剪可撤销 | 裁剪后图层数不减、Ctrl+Z 能回退;文字/形状 `rotation` 保留;800×800 预设尺寸精确 |
| **P3 图层增强** | 缩略图、重命名、混合模式、图层蒙版(选区→蒙版)、多选/简化编组、历史面板 | 蒙版可显隐/删除且不影响原像素;混合模式在合成与导出一致 |
| **P4 单张输出** | PNG/JPG/WebP + 质量 + ≤500KB 策略 + 背景切换 + 下载/剪贴板 + 记住上次预设 | 单张导出尺寸/体积达标;透明像素正确;导出不污染画布;**无队列、无批量入口** |
| **P5 打磨** | 右键菜单补全、全量快捷键、草稿、亮色主题、响应式、无障碍 | 窄窗口可用;草稿只存元数据不存像素 |
每一期都走同一条发布链:`plugin/editor/*.js` → `npm run build -- image-annotate` → `npm run validate` → 提交源码进本仓 → 桌面仓 `node scripts/sync-plugins-from-repo.js` + `node scripts/gen-market.js`(内容寻址 + SRI,自动重建清单)→ 上传 `market/` 到 NAS → 客户端市场安装验证(带 CSP)。版本以 `package.json` 为准(构建时注入 manifest),禁止手改桌面仓 `plugins/index.json`。
### 6.1 实施进度(v1.1.0,2026-11-04 已交付)
| 项 | 状态 |
| --- | --- |
| P0 命令层 `commands.js`、`execute()`、toast、三入口共用 | ✅ 新功能全部接入;旧标注工具仍用原 `saveSnapshot()`(行为不变、仍可撤销),后续渐进迁移 |
| P0 交互 overlay 分层 | ✅ 新增 `selectionCanvas` / `cursorCanvas`,原 `overlayCanvas` 保留为交互层;三者尺寸与坐标基准由 `viewport.js` 统一同步 |
| P0 轻量 UI | ✅ 精简顶栏、就地选项栏、状态栏、侧栏一键收起、更多 ▾、粘贴一步落层;CSS 以末尾追加方式覆盖历史魔数定位(未整体重写) |
| P1 选区 | ✅ 矩形/椭圆/套索、羽化、反选/全选/取消、蚂蚁线、复制/剪切到新层、Delete(单层)、填充、画笔/橡皮受选区约束;加减选与选区变换留二期 |
| P2 非破坏性裁剪 | ✅ v1.2.0:不再 flatten、不再清历史;逐图层搬运 + `resizeWorkspace()` 换尺寸,`restoreState()` 先复位尺寸再回填像素,可 Ctrl+Z / Ctrl+Shift+Z |
| 工具参数解耦与选项栏 | ✅ v1.2.0:`S.shapeLineWidth` / `S.textSize` 独立于 `S.brushSize`;选项栏按工具出参数(画笔三参、形状线宽+填充、文字字号、选区形状/羽化),与右侧面板双向同步 |
| P3 图层增强 | 🟡 v1.7:缩略图 / 重命名 / 多选 / 不透明度滑杆已补;混合模式 / 图层蒙版 / 编组未做 |
| P4 单张输出 | ✅ PNG/JPG/WebP、透明/白底、800×800(长边 80%)、≤500KB 迭代降质、下载、设置记忆;无队列 |
| 描边「无色」+ X 交换整份状态(v1.17.0 / v1.17.1) | ✅ 形状对象新增 `strokeOn`(缺省有描边,老对象/历史快照无此字段照旧),`drawShape()` 按它跳过 `ctx.stroke()`(不能用 `lineWidth=0`:canvas 忽略 0 且丢失原值);「无」按钮扩到**描边槽**,只关外框、颜色留着,选色即恢复(共用一张快照);去掉描边后会把「只描边」的形状顺手切实心,避免对象消失;箭头与未闭合钢笔不给入口(判据复用 `fillSlotOn()`)。Shift+X 从「只交换颜色」升级为**交换颜色 + 有无**:一边有色时连同颜色整体换到另一边,填充「跟随描边色」时只换有无不拆独立色,两边都无色或换完一无所有则提示不执行。v1.17.1 补对称保护:先无描边再点「无填充」时自动恢复描边,杜绝隐形对象 |
| 右栏调色面板 / 可拖宽度 / 字号(v1.16.0) | ✅ 调色面板从「只弹层」变成「右栏常驻 + 弹层保留」,两处共用同一份 DOM(`dom.js#colorSurfaceHtml`),按 `[data-color-surface]` 各绑一次交互、`updateColorUI` 改遍历同步(HEX / SV / 色相 / 「无」显隐 / 常用色与最近色高亮);右栏宽度统一到 CSS 变量 `--iwb-side-w`(原三处硬编码 240/240/220),手柄 9px 热区、范围 220–520 且 ≤ 窗口 45%、默认 280、双击复位、写 `settings.sideWidth` 记忆;字号在 CSS 末尾用 `#iwb-editor-overlay` 前缀集中 +1 档(面板行名 12.5 / 标题 13 / 状态栏 12 / 选项栏 13 / 颜色 tab 12.5),调节名称列 46→50、数值框 36→40 |
| 调节基准跨图串用修复(v1.15.1) | ✅ 退出编辑器后 `sourceCache`(key = `layer.id`,原图恒为 `'base'`)与 `S.adjust` 未清 ⇒ 第二张图一拖滑杆就把上一张图的像素重算上来,且 `ensureAdjustTarget()` 因 `layerId` 相同而跳过重拍基准。新增 `resetAdjustCache()`,在 `resetState()` 与 `releaseEditorMemory()` 双路径清空;`__debug()` 增 `adjustCacheSize` 观测口,harness 补「退出→重开」三条断言 |
| 图片调节(v1.15.0) | ✅ 右侧栏新增 11 项连续调色:曝光(±2EV)/明度/对比度/阴影/高光/色相/饱和度/温度/色调/锐度/清晰度。走 `getImageData` 逐像素(CSS filter 做不到阴影高光的分区蒙版、白平衡的通道增益、锐化的卷积);拖动用长边 ≤900 的降采样预览(6.7ms),松手才全量(4000² 144ms)。`source` + 每层 `sourceCache` 保证永远从基准重算不叠加;撤销后滑块归零并重拍基准。顺带修强度:增强 brightness 1.12→1.4、高对比 contrast 1.4→1.6 |
| 文字字体下拉修复(v1.14.1) | ✅ 选项栏 click 委托原用 `closest([data-opt-text])` 判断文字样式按钮,`<select data-opt-text="fontFamily">` 自带该属性 → 被当按钮 → 取 `dataset.value`(select 上没有)= undefined → `fontKeyOf` 脏值收敛成 `sans`,症状是「点开下拉看一眼字体就被打回黑体」。改为只认 `button[data-opt-text]` + select 早退;`syncOptionBar` 的 active 遍历同步收紧;change 后不再整体重绘(否则换掉刚操作的下拉节点、焦点丢失)。补 2 条真实 click 用例 —— 原用例用 `selectOption` 绕过 click 才漏掉 |
| 文字字体选择 | ✅ v1.14.0:文字对象新增 `fontFamily`(预设 key:`sans` 黑体 / `serif` 宋体 / `kai` 楷体 / `round` 圆体),`fontOf()` 从硬编码 `sans-serif` 改为读 `TEXT_FONTS[key].stack` 的跨平台字体栈;选项栏加「字体」下拉(`select[data-opt-text]`,走 `change` 委托,其余文字样式仍走 `click`),复用 `TEXT_STYLE_STATE_KEY` 一条写回路径;输入框同步字体族与字重;`fontKeyOf()` 把脏值收敛回默认。**明确不做内置字体**:宿主 CSP `default-src 'self'` 拦第三方字体、CJK 字体 2–64MB 无法内联、异步字体有 measureText 时序坑。实测换字体仅首次多 13–42ms 字形光栅化,热重绘 0.1–0.2ms;中文全角等宽,换字体不改字宽(1000²/30 对象内存 114MB 属既有架构,与字体无关) |
| 快捷键语义修正(v1.13.1) | ✅ v1.13.1:Shift+X 从「实心 ↔ 只描边」开关改成**交换填充色与描边色**(PS 的 X 语义)。旧行为下按一次填充被关掉、描边色不动,用户看到的就是「填充丢了」。新 `swapShapeColors()` 对调 `sh.color ⇄ sh.fillColor` 并同步 `S.color` / `S.shapeFillColor`,**填充开关不动**(交换颜色不改有无),箭头跳过、跟随态只提示,一步历史。实心/描边切换仍留在选项栏按钮上 |
| 界面瘦身 / 快捷键 / 实时预览 / 图层解封 | ✅ v1.13.0:顶栏删掉四个层级按钮(`.iwb-editor-commands` 整块移除,`updateLayerUI()` / `bindLayerOrderButtons()` 一并清除);「适应窗口 / 收起侧栏」移到工具栏 DOM 末尾(shrink-to-fit 天然最右);快捷键 `R` 矩形 / `O` 圆形 / `L` 箭头(套索迁 `A`,`U` 保留),键盘处理改为优先匹配 `e.code` 以兼容中文输入法;原生 `<input type="color">` 补接 `input` 做实时预览(`skipHistory` + `nativeColorSnapped`,一次拖动仍只记 1 步撤销);原图不再钉底——`planPanelOrder` / `updateSortTarget` / `onSortEnd` / `moveLayer` / `mergeUnits` 五处解封,其他图层可拖到原图下方 |
| 颜色体系与矢量属性 | ✅ v1.12.0:颜色上下文收敛成 `colorContext()` 三档(文字 / 形状 / 只有主色),文字上下文给**三格**(文字 / 描边 / 底色,`data-color-mode="triple"`),`applyTextColor()` 统管描边色与底色的写回(含 `skipHistory` 拖拽);「无」按当前格分派(无填充 / 无描边 / 无底色);原文「文本不支持描边与字体色切换」已修 |
| 颜色体系与矢量属性(v1.11) | ✅ v1.11.0:颜色收敛为**描边 / 填充两格**——工具栏改 PS 式双色槽(`S.colorTarget` 决定色板写哪一格),选项栏两色块与工具栏双向同步,`colorSlots()` 成为唯一取值处;填充支持**无**(`fill=false`,颜色保留,槽位画灰底红斜杠);画笔/文字/箭头等无填充概念的工具只显示一格(v1.12 起文字改三格) |
| 颜色体系与矢量属性(v1.10) | ✅ v1.10.0:默认值收口到 `TEXT_DEFAULTS`(文字底色去掉纯黑);三个色块标记「生效/未生效」(未生效显示灰色斜纹);对象选中框改实线(虚线只留给像素选区);选区命令归位到矩形/套索选区工具;矢量图形新增独立 `fillColor`,描边色复用主色,选项栏出 `描边 ■ / 填充 ■` 色块,填充缺省跟随描边 |
| 文字样式与吸附 | ✅ v1.9.0:文字补字重/对齐/行距/描边/底色块/多行(`text.js` 统一量算与绘制,描边底色撑大包围盒);拖动吸附画布中心/边缘 + 其他元素,阈值按屏幕像素折算故不随缩放变化,Alt 禁用;矩形圆角;最近使用颜色(存 `ctx.settings`,跨会话) |
| 历史快照升级 | ✅ `snapshotState()` 记录完整图层集合(含 image 引用),能撤销「新建/删除图层」,这是复制新层与还原原图可撤销的前提 |
| 历史面板 / 多选 / 亮色主题 / 草稿 | ⏳ P3/P5 |
**浮动操作条已按 §8 决策先做出来上线,等待用户在桌面客户端体验后裁定**;它是纯视图(只调 `runCommand`),替换或移除不影响选区命令。
---
## 7. 约束、性能与风险
| 项 | 事实 / 对策 |
| --- | --- |
| 内存 | 4K 图一张全幅 RGBA ≈ 33MB。选区复制会同时产生「合成画布 + 新层 + 历史快照」3–4 份 ⇒ **必须用 bbox 局部 tile**,用完 `canvas.width=0` 释放,并把新 canvas 纳入 `releaseEditorMemory()` |
| 帧率 | 蚂蚁线只重绘 `selectionCanvas`(rAF + `lineDashOffset`),**不要每帧调 `getCompositeCanvas()` 或 `getImageData()`**;浮动条用 DOM 定位,不参与 canvas 重绘 |
| 羽化 | 用 `ctx.filter = 'blur(Npx)'`(Canvas2D 原生,CSP 不限制),不要逐像素遍历 |
| 魔棒 | 宿主 CSP 未放行 `worker-src blob:` ⇒ 不能用 Worker 做连通域;放二期,主线程分块 + 让出帧,且限制最大像素数 |
| CSP | 单文件经典脚本 IIFE;禁 `eval` / `new Function` / ESM / CDN;样式 JS 注入 `<style>`;`toBlob` 要求 origin-clean ⇒ 远程图片必须 `fetch → blob → dataURL`(现有 `onPaste` 已按此实现) |
| 宿主争抢 paste | 宿主在 window 气泡阶段也监听粘贴(建 ref 节点 + 下载)。编辑器继续在 document 捕获阶段 `stopImmediatePropagation()`。新增「复制选区到系统剪贴板」需要 `ClipboardItem` + 用户手势 + 权限,失败必须有 toast 降级 |
| 选项栏横向排布 | `.iwb-editor-optionbar-body` 是 `overflow-x: auto` 的 flex。**任何 `margin-left: auto` 都会把其后内容整组推到最右**,排满时直接滚出可视区 —— `v1.9.1` 就是 `.iwb-opt-sep` 带了 `auto`,导致选区按钮在选择工具下「消失」。留白只允许放在末尾的 `.iwb-opt-hint`;中文双字按钮必须 `white-space: nowrap`,否则会竖排 |
| 草稿持久化 | `ctx.storage` 是宿主提供的命名空间小 KV(`get/set/remove/keys`),**不能塞像素**;`ctx.settings` 适合存输出预设与面板开合。若要做工程草稿,只能存元数据 + 宿主节点引用;真要存图层像素需插件自建 IndexedDB 库(必须自带 `onupgradeneeded` 建表,宿主踩过这个坑)或与宿主协商新能力 |
| 节点模型 | 宿主 `setNodeImage` / `createImageNode` 只收一张图;导出即扁平化。要做「可继续编辑的工程」需要宿主侧支持节点附加数据 ⇒ 属于跨仓变更,P5 再评估 |
| 上游关系 | 编辑器移植自 `iwb-plaus/iwb-cutout-extension`,README 已警告 1.0.5 的 z 序修复不能整目录覆盖回去。P0 的大改等于正式分叉,应在 README 明确改为「一次性移植 + 独立演进」,避免以后误回灌 |
| 发布契约 | 文件名 `plugin-image-annotate.<sha12>.js`(内容寻址)、id 一致、SRI;桌面仓同步脚本按白名单重建市场清单;版本以 `package.json` 为准 |
| 测试 | 本地 mock 探针(直接注入 `src/index.js` + mock host)用于发布前验证;桌面客户端 e2e(CSP / 市场安装 / SRI)用于发布后验证;两者都保留 |
---
## 8. 决策记录
### 8.1 已拍板(用户 2026-11-04 确认,按此实现)
| # | 决策 | 实现口径 |
| --- | --- | --- |
| 1 | **选区 `Delete` 只作用当前图层** | 用 `S.selection.path` 对**当前活动层**做 `destination-out`,不动其它层;`base` 处于锁定态时给 toast 提示「原图层已锁定,请先解锁」,不提供「清所有可见层」入口。清除走 `execute()`,可 Ctrl+Z。 |
| 2 | **「清空标注」=全部还原** | 一键回到**刚打开这张图时的初始态**:删除所有非 `base` 图层(含粘贴/导入/选区复制产生的层)、清空所有绘制像素、复位变换与选区、保留 `base` 原始像素。整步记一个历史快照,**可撤销**。按钮标签改为「还原原图」避免歧义;不再留空白层。 |
| 3 | **≤500KB 做成输出预设** | 输出面板新增可切换预设「电商 800×800 · ≤500KB」:尺寸 800×800、长边占比 80%(640px)、透明 PNG 或白底 JPG **由用户当前选的单一格式决定,一次只产一个结果**;编码质量迭代到 ≤500KB。预设选择存 `ctx.settings`,下次打开沿用。默认仍是「原尺寸 PNG」,不默认启用预设。 |
| 4 | **浮动操作条:先做,体验后定** | 本轮按 §4.1 实现选区旁的浮动条并上线,供用户在桌面客户端体验;「好不好用、要不要保留/换位置/改内容」由体验结论决定,**不作为开工前置条件**。实现上保持它是纯视图(`floating.js` 只调用命令层),日后替换或移除不影响选区功能。 |
配套已按推荐默认落地(无需再问):不设菜单栏、数字键 1–0 保留兼容、`Ctrl+V` 维持「贴为新图层」、选区贴入用 `Ctrl+Shift+V`、正式分叉不回灌 `iwb-plaus`、优先级 **P0 → P1**,输出预设随 P1 一起带上(改动小)。
### 8.2 仍待后续确认(不阻塞本轮)
- 魔棒 / 色彩范围是否要做(CSP 下不能用 Worker,见 §7);
- 选区加减(Shift/Alt)与选区变换放在一期还是二期;
- 工程草稿 / 二次编辑(需宿主支持节点附加数据,P5)。
> 已确认不再讨论:批量出图、多图队列、批量导出/改名/下载 —— 全部移出范围。
---
## 9. 改动面与风险排序
| 改动 | 涉及文件 | 风险 |
| --- | --- | --- |
| UI 骨架 + CSS 重构(轻量四区 + 浮动条) | `dom.js` / `editor.css` / `events.js` / 新增 `floating.js` | 中:选择器面广,但功能不变,靠 e2e 兜底 |
| 命令层 + 状态机 | 新增 2 模块 + 全部编辑入口 | 中高:触碰所有工具,必须逐工具回归 |
| Overlay 分层 | `crop.js` / `viewport.js` / `placement.js` / `objects.js` | 中:坐标基准 `getPos()` 不能变 |
| 选区模型 + 像素操作 | 新增 `selection.js` + `layers.js` / `history.js` / `tools.js` | 高:内存、撤销、锁层、跨域边界都在这里 |
| 非破坏性裁剪(路线 1) | `crop.js` / `history.js` | 中:越界透明;旋转中心由几何派生(v1.7 已核查),文字非等比缩放属已知近似 |
| 输出管道(单张) | `index.js` / `glue.js` | 低:接口可保持兼容 |
| 图层蒙版 / 混合模式 | `layers.js` / `tools.js#getCompositeCanvas` | 中高:合成与导出必须用同一套逻辑 |
| 工程草稿 / 跨仓 | 宿主 + 插件 | 高:需要宿主侧协商,建议最后做 |
| ~~批量队列~~ | — | **不做**(用户裁定移出范围) |
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/image-annotate",
"private": true,
"version": "1.20.7",
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
"ibwPlugin": {
"id": "image-annotate",
"entry": "src/index.js",
"apiVersion": 1
}
}
+2264
View File
File diff suppressed because it is too large. Load diff
+526
View File
@@ -0,0 +1,526 @@
/* adjust.js - 图片调节(v1.15)
*
* 和 effects.js 的分工:
* effects.js = 一键效果(反白/灰度/马赛克……),语义是「换成另一种图」;
* adjust.js = 连续调色(曝光/对比度/白平衡……),语义是「把这张图调好看」。
* 两者都作用在当前位图图层,都保留 source 只重算不叠加。
*
* === 为什么不用 ctx.filter ===
* CSS filter 只有 brightness/contrast/saturate/hue-rotate/blur 这几种全局线性变换,做不到:
* · 阴影 / 高光 —— 需要按亮度做软蒙版分区提亮压暗;
* · 白平衡温度 / 色调 —— 需要 R/B、G/M 通道分别增益;
* · 锐度 / 清晰度 —— USM 反遮罩,需要卷积。
* 所以走 getImageData 逐像素。代价是耗时随像素数线性增长(实测):
* 800² 6.7ms · 1200² 12.8ms · 2000² 36.8ms · 4000² 144.6ms
* 因此拖动滑杆时用「降采样预览」(长边 ≤ PREVIEW_SIDE,一张小图反复算),
* 松手(change)才用原尺寸算一次。这是 PS 的常规做法,观感上只在松手瞬间有一帧停顿。
*
* === 非破坏性怎么保证 ===
* S.adjust.source 存「开始调节前」的原尺寸像素,preview 存它的降采样副本。
* 每次参数变化都从 source 重算,绝不在上一次结果上叠加 —— 否则来回拖滑杆会
* 层层累积、越拖越糊(effects.js 里同样的坑,注释里记过)。
*/
'use strict'
import { S, runtime } from './state.js'
import { saveSnapshot } from './history.js'
import { getActiveLayer, renderLayerPanel } from './layers.js'
import { needsPixelSnapshot } from '../vendor/layer-logic.js'
import { toast } from './commands.js'
/** 拖动预览用的最长边:0.6M 像素,实测 6.7ms,够 60fps */
const PREVIEW_SIDE = 900
/** 图本身小于这个边长就无需降采样,直接全量算 */
const DIRECT_SIDE = 1100
/**
* 参数表。范围按「拉满要有明显变化」定,不是摆设:
* 曝光 ±100 = ±2 档(×4 / ÷4),对比度 ±100 = 0~2 倍,饱和度 ±100 = 0~2 倍。
* 上一版快速效果「增强」拉满只有 brightness(1.12),用户反馈「效果弱」就是这么来的。
*/
export const ADJUST_DEFS = [
{ key: 'exposure', label: '曝光', min: -100, max: 100, step: 1, def: 0 },
{ key: 'brightness', label: '明度', min: -100, max: 100, step: 1, def: 0 },
{ key: 'contrast', label: '对比度', min: -100, max: 100, step: 1, def: 0 },
{ key: 'shadows', label: '阴影', min: -100, max: 100, step: 1, def: 0 },
{ key: 'highlights', label: '高光', min: -100, max: 100, step: 1, def: 0 },
{ key: 'hue', label: '色相', min: -180, max: 180, step: 1, def: 0, suffix: '°' },
{ key: 'saturation', label: '饱和度', min: -100, max: 100, step: 1, def: 0 },
{ key: 'temp', label: '温度', title: '白平衡温度:往右偏暖(黄),往左偏冷(蓝)', min: -100, max: 100, step: 1, def: 0 },
{ key: 'tint', label: '色调', title: '白平衡色调:往右偏品红,往左偏绿', min: -100, max: 100, step: 1, def: 0 },
{ key: 'sharpen', label: '锐度', min: 0, max: 100, step: 1, def: 0 },
{ key: 'clarity', label: '清晰度', min: -100, max: 100, step: 1, def: 0 }
]
export const ADJUST_KEYS = ADJUST_DEFS.map(d => d.key)
export function zeroAdjust() {
const o = {}
for (const k of ADJUST_KEYS) o[k] = 0
return o
}
/** 全部参数都是 0 = 没调过,直接跳过整趟像素运算 */
export function isNeutral(p) {
if (!p) return true
for (const k of ADJUST_KEYS) if (p[k]) return false
return true
}
/** 调节目标:当前活跃位图图层;没有就退回「原图」(与 effects.js 同规则) */
function adjustTarget() {
const active = getActiveLayer()
if (active) return active
return S.layers.find(l => l.id === 'base') || null
}
function copyCanvas(src, maxSide) {
const w0 = src.width, h0 = src.height
let w = w0, h = h0
if (maxSide && Math.max(w0, h0) > maxSide) {
const k = maxSide / Math.max(w0, h0)
w = Math.max(1, Math.round(w0 * k))
h = Math.max(1, Math.round(h0 * k))
}
const c = document.createElement('canvas')
c.width = w
c.height = h
const ctx = c.getContext('2d', { willReadFrequently: true })
ctx.imageSmoothingEnabled = true
ctx.imageSmoothingQuality = 'high'
ctx.drawImage(src, 0, 0, w, h)
return c
}
/* ---------------------------------------------------------------- 像素调色 */
/**
* 逐像素处理。顺序有讲究:
* 白平衡 → 曝光 → 阴影/高光 → 对比度 → 饱和度 → 色相
* 先修色偏再谈明暗,先把动态范围拉开再调饱和,否则「先加饱和后压对比」会把
* 颜色压成一片灰。色相放最后,因为它作用在已经很干净的色相上。
*/
function adjustPixels(ctx, w, h, p) {
const img = ctx.getImageData(0, 0, w, h)
const d = img.data
const ev = p.exposure ? Math.pow(2, p.exposure / 50) : 1
const add = (p.brightness / 100) * 0.45
const con = 1 + p.contrast / 100
const sh = p.shadows / 100
const hi = p.highlights / 100
const sat = 1 + p.saturation / 100
const wbR = 1 + p.temp / 250 + p.tint / 500
const wbG = 1 - p.tint / 400
const wbB = 1 - p.temp / 250 + p.tint / 500
const wb = Boolean(p.temp || p.tint)
const needSh = Boolean(sh)
const needHi = Boolean(hi)
const needCon = Boolean(p.contrast)
const needSat = Boolean(p.saturation)
const needHue = Boolean(p.hue)
// 色相旋转矩阵(与 CSS hue-rotate 同一套系数),预算好避免每像素算三角函数
let h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0, h8 = 0
if (needHue) {
const a = (p.hue * Math.PI) / 180
const c = Math.cos(a), s = Math.sin(a)
h0 = 0.213 + c * 0.787 - s * 0.213
h1 = 0.715 - c * 0.715 - s * 0.715
h2 = 0.072 - c * 0.072 + s * 0.928
h3 = 0.213 - c * 0.213 + s * 0.143
h4 = 0.715 + c * 0.285 + s * 0.140
h5 = 0.072 - c * 0.072 - s * 0.283
h6 = 0.213 - c * 0.213 - s * 0.787
h7 = 0.715 - c * 0.715 + s * 0.715
h8 = 0.072 + c * 0.928 + s * 0.072
}
// 全部为 0 的短路:只做一次遍历判断,省掉逐像素分支
const trivial = !wb && !p.exposure && !add && !needSh && !needHi && !needCon && !needSat && !needHue
if (trivial) return
for (let i = 0; i < d.length; i += 4) {
let r = d[i] / 255, g = d[i + 1] / 255, b = d[i + 2] / 255
if (wb) { r *= wbR; g *= wbG; b *= wbB }
if (ev !== 1) { r *= ev; g *= ev; b *= ev }
if (add) { r += add; g += add; b += add }
// 阴影/高光:按当前亮度给一个软蒙版。阴影权重 (1-l)²,高光 l²,
// 这样中间调几乎不动,只有暗部/亮部两端被推 —— 硬阈值会在边界留下可见台阶。
if (needSh || needHi) {
const l = 0.2126 * r + 0.7152 * g + 0.0722 * b
if (needSh) {
const m = (1 - l) * (1 - l) * sh * 0.85
r += m; g += m; b += m
}
if (needHi) {
const m = l * l * hi * 0.85
r += m; g += m; b += m
}
}
if (needCon) {
r = (r - 0.5) * con + 0.5
g = (g - 0.5) * con + 0.5
b = (b - 0.5) * con + 0.5
}
if (needSat) {
const l = 0.2126 * r + 0.7152 * g + 0.0722 * b
r = l + (r - l) * sat
g = l + (g - l) * sat
b = l + (b - l) * sat
}
if (needHue) {
const nr = h0 * r + h1 * g + h2 * b
const ng = h3 * r + h4 * g + h5 * b
const nb = h6 * r + h7 * g + h8 * b
r = nr; g = ng; b = nb
}
d[i] = r <= 0 ? 0 : (r >= 1 ? 255 : r * 255)
d[i + 1] = g <= 0 ? 0 : (g >= 1 ? 255 : g * 255)
d[i + 2] = b <= 0 ? 0 : (b >= 1 ? 255 : b * 255)
}
ctx.putImageData(img, 0, 0)
}
/* ---------------------------------------------------------------- 锐化 */
/**
* USM 反遮罩:result = src + (src - blur) * amount。
* 锐度用 1px 半径(找边缘),清晰度用更大的半径 + 更低强度(找中间调的体积感)。
* 降采样预览时半径要跟着缩放,否则 900px 的预览用 1px 和原图 1px 视觉上不是一回事。
*/
function unsharp(canvas, radius, amount) {
if (!(amount > 0)) return
const w = canvas.width, h = canvas.height
const blur = document.createElement('canvas')
blur.width = w
blur.height = h
const bc = blur.getContext('2d', { willReadFrequently: true })
bc.filter = 'blur(' + radius.toFixed(2) + 'px)'
bc.drawImage(canvas, 0, 0)
const ctx = canvas.getContext('2d', { willReadFrequently: true })
const src = ctx.getImageData(0, 0, w, h)
const bl = bc.getImageData(0, 0, w, h)
const a = src.data, b = bl.data
for (let i = 0; i < a.length; i += 4) {
// 透明像素不参与(位图层的空白区域),否则边缘会被锐出一圈黑边
if (a[i + 3] === 0) continue
for (let c = 0; c < 3; c++) {
const v = a[i + c] + (a[i + c] - b[i + c]) * amount
a[i + c] = v <= 0 ? 0 : (v >= 255 ? 255 : v)
}
}
ctx.putImageData(src, 0, 0)
}
/* ---------------------------------------------------------------- 渲染 */
/** 把参数应用到一张画布上(画布尺寸决定锐化半径的缩放) */
function paint(canvas, p, refSide) {
const ctx = canvas.getContext('2d', { willReadFrequently: true })
adjustPixels(ctx, canvas.width, canvas.height, p)
const k = Math.max(canvas.width, canvas.height) / (refSide || Math.max(canvas.width, canvas.height))
if (p.sharpen > 0) unsharp(canvas, Math.max(0.6, 1 * k), (p.sharpen / 100) * 1.1)
if (p.clarity) {
// 负清晰度 = 柔化中间调,同样走 USM,只是 amount 为负
unsharp(canvas, Math.max(1.5, 6 * k), (p.clarity / 100) * 0.55)
}
}
function blit(target, src) {
const ctx = target.getContext('2d')
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.globalCompositeOperation = 'copy'
ctx.filter = 'none'
ctx.imageSmoothingEnabled = true
ctx.imageSmoothingQuality = 'high'
ctx.drawImage(src, 0, 0, target.width, target.height)
ctx.restore()
target._bounds = undefined
S.pickerComposite = null
}
/**
* 从 source 重算并写回目标层。
* preview=true 走降采样:拖动滑杆时只要「看得出往哪边变」,不需要像素级准确。
*/
function renderAdjust(preview) {
const st = S.adjust
if (!st || !st.source) return false
const target = S.layers.find(l => l.id === st.layerId)
if (!target) return false
const src = preview && st.previewCanvas ? st.previewCanvas : st.source
const work = copyCanvas(src)
paint(work, st.params, Math.max(st.source.width, st.source.height))
blit(target.canvas, work)
return true
}
/* ---------------------------------------------------------------- 对外 */
/**
* 每层的「调节前基准像素」缓存。
* 为什么需要它:A 层调过 → 切到 B 层调 → 切回 A 层再调。此时 A 的 canvas 里已经
* 是调节后的像素,若拿它当新基准,第二次调整就叠在第一次结果上(来回拖会越调越脏,
* effects.js 注释里记过同样的坑)。缓存不进图层对象,因此不会被历史快照深拷贝。
*/
const sourceCache = new Map()
function captureFor(layer) {
const hit = sourceCache.get(layer.id)
if (hit) return hit
const rec = {
source: copyCanvas(layer.canvas, 0),
previewCanvas: copyCanvas(layer.canvas, PREVIEW_SIDE)
}
sourceCache.set(layer.id, rec)
return rec
}
/**
* 退出编辑器 / 重新打开时清空基准缓存(v1.15.1 修)。
*
* 必须清的原因:缓存的 key 是 layer.id,而原图层的 id 是写死的 'base'。
* 退出编辑器时 releaseEditorMemory() 释放了图层画布,却没清这张 Map,
* 于是下一张图打开后 captureFor() 直接命中上一张图的像素,
* 表现为「调第二张图,画面变回第一张」。id 固定 ⇒ 100% 复现,不是偶发。
*
* 顺带把 S.adjust 也归零:残留的 params 会让新图的滑杆一进来就显示 +80,
* 而画面是未调状态,参数与画面对不上。
*/
export function resetAdjustCache() {
sourceCache.clear()
S.adjust = { layerId: null, source: null, previewCanvas: null, params: zeroAdjust() }
}
/** 观测口:回归用例用它断言「退出后缓存确实清空了」 */
export function adjustCacheSize() {
return sourceCache.size
}
/** 切换调节目标:旧层基准入缓存,新层取缓存或现拍,参数按层恢复 */
function switchTarget(layer) {
const st = S.adjust
if (st && st.layerId && st.source) {
sourceCache.set(st.layerId, { source: st.source, previewCanvas: st.previewCanvas })
}
const rec = captureFor(layer)
S.adjust = {
layerId: layer.id,
source: rec.source,
previewCanvas: rec.previewCanvas,
params: layer.adjustParams ? { ...layer.adjustParams } : zeroAdjust()
}
}
/** 参数写回图层对象:切层回来能显示「这层调成了什么样」 */
function persistParams() {
const st = S.adjust
if (!st || !st.layerId || !st.params) return
const layer = S.layers.find(l => l.id === st.layerId)
if (layer) layer.adjustParams = { ...st.params }
}
/** 确保当前目标层有一份可重算的基准像素 */
export function ensureAdjustTarget() {
let layer = adjustTarget()
if (!layer) { toast('没有可调节的图层'); return null }
if (layer.visible === false) {
toast('「' + layer.name + '」已隐藏,先显示再调节')
return null
}
if (!needsPixelSnapshot(layer)) layer = rasterizeForAdjust(layer)
if (!layer) { toast('栅格化失败,调节未应用'); return null }
if (!S.adjust || S.adjust.layerId !== layer.id || !S.adjust.source) switchTarget(layer)
return layer
}
/** 导入图片层原地改像素会被下次重绘冲掉 —— 先复制一层普通位图(与 effects.js 同策略) */
function rasterizeForAdjust(layer) {
const canvas = document.createElement('canvas')
canvas.width = S.imgW
canvas.height = S.imgH
const ctx = canvas.getContext('2d', { willReadFrequently: true })
ctx.drawImage(layer.canvas, 0, 0)
const copy = {
id: 'adj' + Date.now() + Math.floor(Math.random() * 1000),
name: layer.name + ' · 调节',
canvas, ctx,
opacity: layer.opacity == null ? 1 : layer.opacity,
visible: true, locked: false,
x: 0, y: 0, w: S.imgW, h: S.imgH,
rotation: 0,
z: (layer.z || 0) + 0.5
}
S.layers.push(copy)
layer.visible = false
if (S.selectedLayerId === layer.id) S.selectedLayerId = copy.id
S.activeLayerId = copy.id
renderLayerPanel()
return copy
}
/** 参数变了:重算并画到画布上。preview=true 用降采样 */
export function applyAdjust(preview) {
if (!S.adjust || !S.adjust.source) return false
const ok = renderAdjust(Boolean(preview))
if (ok) {
persistParams()
if (S.renderAll) S.renderAll()
}
renderAdjustPanel()
return ok
}
/** 单个参数变化 */
export function setAdjustValue(key, value, preview) {
const st = S.adjust
if (!st || !st.source) return false
const def = ADJUST_DEFS.find(d => d.key === key)
if (!def) return false
const v = Math.min(def.max, Math.max(def.min, Number(value) || 0))
st.params[key] = v
applyAdjust(preview)
return true
}
/** 复位:单条 or 全部 */
export function resetAdjust(key) {
const st = S.adjust
if (!st || !st.source) return false
saveSnapshot('调节复位')
if (key) st.params[key] = 0
else st.params = zeroAdjust()
applyAdjust(false)
syncAdjustControls()
return true
}
/** 有没有调过(用于「复位」按钮的可用态与标题提示) */
export function adjustDirty() {
return Boolean(S.adjust && S.adjust.source && !isNeutral(S.adjust.params))
}
/* ---------------------------------------------------------------- UI */
/**
* 按 ADJUST_DEFS 生成 11 行控件,只做一次(面板是静态的,之后只改 value / 类名)。
* 单行紧凑布局:名称 46px + 滑杆 flex + 数值 36px —— 240px 侧栏里 11 项只占约 240px 高,
* 不需要把侧栏撑成一整屏滚动。
*/
export function mountAdjustPanel() {
if (!runtime.el) return
const list = runtime.el.querySelector('.iwb-editor-adj-list')
if (!list || list.childElementCount) return
list.innerHTML = ADJUST_DEFS.map(d => `
<div class="iwb-editor-adj-row" data-adj="${d.key}">
<span class="iwb-editor-adj-name" title="${d.title || d.label}${d.suffix ? '' : ''}(双击归零)">${d.label}</span>
<input type="range" class="iwb-editor-adj-range" min="${d.min}" max="${d.max}" step="${d.step}" value="${d.def}" aria-label="${d.title || d.label}">
<input type="number" class="iwb-editor-adj-val" min="${d.min}" max="${d.max}" step="${d.step}" value="${d.def}" aria-label="${d.title || d.label}数值">
</div>`).join('')
renderAdjustPanel()
}
/** 面板里的 target 层名 + 复位按钮可用态 */
export function renderAdjustPanel() {
if (!runtime.el) return
const sec = runtime.el.querySelector('.iwb-editor-adj')
if (!sec) return
const layer = adjustTarget()
// 目标层被切走:面板跟着换到新层(参数按层恢复、新的基准),旧层的像素不动。
// 必须在这里兜住 —— 图层切换走的是 layers.js,那边不能 import 本模块(会形成循环)。
if (layer && S.adjust && S.adjust.layerId && S.adjust.layerId !== layer.id) {
switchTarget(layer)
syncAdjustControls()
return
}
const nameEl = sec.querySelector('.iwb-editor-adj-target')
if (nameEl) {
const name = layer ? layer.name : '无图层'
nameEl.textContent = name
nameEl.title = layer ? '调节作用于「' + name + '」' : '没有可调节的位图图层'
}
const dirty = adjustDirty()
sec.classList.toggle('is-dirty', dirty)
const reset = sec.querySelector('[data-adj-reset="all"]')
if (reset) reset.disabled = !dirty
sec.querySelectorAll('.iwb-editor-adj-row').forEach(row => {
const k = row.dataset.adj
const v = S.adjust && S.adjust.params ? S.adjust.params[k] || 0 : 0
row.classList.toggle('is-set', Boolean(v))
})
}
/** 把 S.adjust.params 写回所有滑杆与数值框(复位后调用) */
export function syncAdjustControls() {
if (!runtime.el) return
const sec = runtime.el.querySelector('.iwb-editor-adj')
if (!sec || !S.adjust || !S.adjust.params) return
sec.querySelectorAll('.iwb-editor-adj-row').forEach(row => {
const k = row.dataset.adj
const v = S.adjust.params[k] || 0
const range = row.querySelector('.iwb-editor-adj-range')
const val = row.querySelector('.iwb-editor-adj-val')
if (range) range.value = String(v)
if (val) val.value = String(v)
})
renderAdjustPanel()
}
/** 进入编辑器 / 切换目标层时重建基准 */
export function refreshAdjustTarget() {
// 只在目标层真的变了才重置基准,否则每次重绘都丢参数
const layer = adjustTarget()
if (!layer) return
const st = S.adjust
if (st.source && st.layerId === layer.id) return
S.adjust = { layerId: null, source: null, previewCanvas: null, params: zeroAdjust() }
renderAdjustPanel()
syncAdjustControls()
}
/**
* 撤销 / 重做之后。
*
* 为什么必须归零:调整是「写进像素」的破坏性操作,历史里只存了像素快照,没存
* 「调节前的基准」。撤销把像素还原了,但 source 对应的已经不是这个状态 —— 留着
* 旧参数只会出现「滑块显示 +80、画面其实没调」。更糟的是下一次拖动会从错误的
* 基准重算,等于把调整叠加两遍。
*
* 所以规则很简单也很可预测:**撤销一步 = 调整作废,滑块归零,基准重拍当前像素**。
* 想再调就从现在这张画面上重新调。
*/
export function onHistoryRestore() {
sourceCache.clear()
const layer = adjustTarget()
if (!layer) {
S.adjust = { layerId: null, source: null, previewCanvas: null, params: zeroAdjust() }
syncAdjustControls()
return
}
if (layer.adjustParams) delete layer.adjustParams
S.adjust = {
layerId: layer.id,
source: copyCanvas(layer.canvas, 0),
previewCanvas: copyCanvas(layer.canvas, PREVIEW_SIDE),
params: zeroAdjust()
}
syncAdjustControls()
}
+79
View File
@@ -0,0 +1,79 @@
/* commands.js - 统一命令层(P0 地基)
*
* 浮动操作条 / 右键菜单 / 快捷键是三个「视图」,都必须走同一条 execute():
* execute(label, mutator) → 前置守卫 → 快照(label) → mutator 只改状态 → 统一重绘 → 记历史
* 这样所有新操作自动获得 Ctrl+Z / Ctrl+Shift+Z,也不会出现三套逻辑各修一遍。
*
* 旧标注工具仍直接调用 history.saveSnapshot()(行为不变、仍可撤销),
* 新功能(选区、还原原图、输出)一律走本模块;后续可渐进迁移旧入口。
*
* 循环依赖规避:本文件顶层不 import 任何渲染模块。渲染出口由 index.js
* 在 open() 时注入 S.renderAll,命令注册表由各功能模块在顶层 defineCommand()。
*/
'use strict'
import { S, runtime } from './state.js'
import { saveSnapshot } from './history.js'
/** 命令注册表:name → { label, enabled?, run } */
export const COMMANDS = Object.create(null)
export function defineCommand(name, def) {
COMMANDS[name] = Object.assign({ label: name }, def || {})
}
/** 统一变更入口。mutator 抛错时回滚刚压入的快照,避免留下「空撤销步」。 */
export function execute(label, mutator) {
const before = S.history.length
saveSnapshot(label)
let result
try {
result = mutator()
} catch (err) {
if (S.history.length === before + 1) S.history.pop()
throw err
}
if (S.renderAll) S.renderAll()
return result
}
/** 三入口共用的命令调用;enabled() 返回 false 时给 toast 而不是静默失败。 */
export function runCommand(name) {
const def = COMMANDS[name]
if (!def) return false
// 选区与裁剪互斥:只在 setTool('crop') 清一次选区不够 —— 快捷键 / 更多菜单 /
// 右键菜单都还能再建选区。三条入口都经过这里,统一在工作层拦掉 sel.*。
if (S.tool === 'crop' && String(name).indexOf('sel.') === 0) {
toast('裁剪中不可使用选区命令,请先切换工具', 'warn')
return false
}
if (typeof def.enabled === 'function' && !def.enabled()) {
toast(def.hint || '当前状态下不可用', 'warn')
return false
}
const args = Array.prototype.slice.call(arguments, 1)
try {
// 纯视图命令(全选 / 反选 / 取消选区)不产生撤销步
if (def.view) {
const r = def.run.apply(null, args)
if (S.renderAll) S.renderAll()
return r
}
return execute(def.label, () => def.run.apply(null, args))
} catch (err) {
console.error('[IWB编辑器] 命令执行失败:' + name, err)
toast('操作失败:' + ((err && err.message) || name), 'error')
return false
}
}
/** 轻量 toast:取代 window.alert / window.confirm,不打断画布操作 */
let toastTimer = null
export function toast(message, kind) {
const el = runtime.el && runtime.el.querySelector('.iwb-editor-toast')
if (!el) return
el.textContent = String(message || '')
el.className = 'iwb-editor-toast iwb-editor-toast-' + (kind || 'info') + ' show'
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => { el.classList.remove('show'); toastTimer = null }, 2600)
}
+360
View File
@@ -0,0 +1,360 @@
/* crop.js - 裁剪工具
* 节:裁剪、裁剪栏。
* 遮罩绘制写 S.overlayCanvas;确认裁剪后逐图层搬运像素(v1.2 起不再 flatten)。
*/
'use strict'
import { S, runtime } from './state.js'
import { resizeWorkspace } from './viewport.js'
import { resetOverlayTransform, viewScale } from './scale.js'
import { disposeSelection } from './selection.js'
import { saveSnapshot } from './history.js'
import { toast } from './commands.js'
// ============ 裁剪 ============
// parseRatio 由 shared/image-math.js 提供(可单测)
/** 设置裁剪约束 */
export function setConstraint(type, ratio, sizeW, sizeH) {
S.cropConstraint = { type, ratio: ratio || 0, sizeW: sizeW || 0, sizeH: sizeH || 0 }
const toggle = runtime.el && runtime.el.querySelector('.iwb-editor-size-toggle')
if (toggle) {
const active = type === 'size'
toggle.classList.toggle('active', active)
toggle.setAttribute('aria-pressed', String(active))
toggle.textContent = active ? '已启用' : '启用尺寸'
}
if (S.cropRect) {
S.cropRect = applyConstraint(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h)
drawCropPreview()
updateCropInfo()
}
}
function applyConstraint(x, y, w, h) {
const c = S.cropConstraint
if (c.type === 'free' || !c.ratio || c.ratio <= 0) return { x, y, w, h }
const ratio = c.ratio
if (w / h > ratio) {
const nw = h * ratio
const dx = (w - nw) / 2
return { x: x + dx, y, w: nw, h }
} else {
const nh = w / ratio
const dy = (h - nh) / 2
return { x, y: y + dy, w, h: nh }
}
}
export function applyConstraintDrag(x1, y1, x2, y2) {
const c = S.cropConstraint
let rx = Math.min(x1, x2), ry = Math.min(y1, y2)
let rw = Math.abs(x2 - x1), rh = Math.abs(y2 - y1)
if (rw < 1) rw = 1
if (rh < 1) rh = 1
if (c.type === 'free' || !c.ratio || c.ratio <= 0) return { x: rx, y: ry, w: rw, h: rh }
const ratio = c.ratio
if (rw / rh > ratio) {
rh = rw / ratio
} else {
rw = rh * ratio
}
return { x: rx, y: ry, w: rw, h: rh }
}
export function updateCropInfo() {
const info = runtime.el.querySelector('.iwb-editor-crop-info')
if (!info) return
if (S.cropRect) {
const w = Math.round(S.cropRect.w)
const h = Math.round(S.cropRect.h)
const c = S.cropConstraint
if (c.type === 'size' && c.sizeW > 0 && c.sizeH > 0) {
info.textContent = `${w}x${h} -> ${c.sizeW}x${c.sizeH}`
} else {
info.textContent = `${w}x${h}`
}
} else {
info.textContent = '--'
}
}
export function clearOverlay() {
const ctx = S.overlayCtx
if (!ctx) return
// 缓冲已按 overlayScale 放大,必须按设备像素整幅清,再恢复图片坐标基准
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
resetOverlayTransform(ctx)
}
export function drawCropPreview(x1, y1, x2, y2) {
const ctx = S.overlayCtx
clearOverlay()
let rx, ry, rw, rh
if (x2 !== undefined) {
const r = applyConstraintDrag(x1, y1, x2, y2)
rx = r.x; ry = r.y; rw = r.w; rh = r.h
} else if (S.cropRect) {
rx = S.cropRect.x; ry = S.cropRect.y
rw = S.cropRect.w; rh = S.cropRect.h
} else {
return
}
ctx.save()
ctx.fillStyle = 'rgba(0,0,0,0.45)'
const cropPad = Math.max(S.imgW, S.imgH) * 2
ctx.fillRect(-cropPad, -cropPad, S.imgW + cropPad * 2, S.imgH + cropPad * 2)
ctx.globalCompositeOperation = 'destination-out'
ctx.fillRect(rx, ry, rw, rh)
ctx.restore()
ctx.save()
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 2 / viewScale()
ctx.setLineDash([8 / viewScale(), 4 / viewScale()])
ctx.strokeRect(rx, ry, rw, rh)
ctx.restore()
if (S.cropRect && !S.cropHandle) drawCropHandles(rx, ry, rw, rh)
}
function cropHandlePoints(rx, ry, rw, rh) {
return {
nw: [rx, ry], ne: [rx + rw, ry],
sw: [rx, ry + rh], se: [rx + rw, ry + rh],
n: [rx + rw / 2, ry], s: [rx + rw / 2, ry + rh],
e: [rx + rw, ry + rh / 2], w: [rx, ry + rh / 2]
}
}
function drawCropHandles(rx, ry, rw, rh) {
const ctx = S.overlayCtx
const pts = cropHandlePoints(rx, ry, rw, rh)
const hs = 4 / viewScale()
ctx.save()
ctx.fillStyle = '#ffffff'
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 1.5 / viewScale()
for (const name in pts) {
ctx.beginPath()
ctx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2)
ctx.fill()
ctx.stroke()
}
ctx.restore()
}
export function insideRect(pos, rect) {
return pos.x >= rect.x && pos.x <= rect.x + rect.w &&
pos.y >= rect.y && pos.y <= rect.y + rect.h
}
export function hitCropHandle(pos) {
if (!S.cropRect) return null
const pts = cropHandlePoints(S.cropRect.x, S.cropRect.y, S.cropRect.w, S.cropRect.h)
const R = 12 / viewScale()
let best = null, bestDist = 1e9
for (const name in pts) {
const dx = pos.x - pts[name][0], dy = pos.y - pts[name][1]
const d = dx * dx + dy * dy
if (d < R * R && d < bestDist) { bestDist = d; best = name }
}
return best
}
export function resizeCropRect(pos) {
if (!S.cropRect) return
const { x, y, w, h } = S.cropRect
const c = S.cropConstraint
let nx = x, ny = y, nw = w, nh = h
const hh = S.cropHandle
// 自由比例:允许超出画布边界(负值/超出值都合法),只限制最小尺寸
if (c.type === 'free' || !c.ratio || c.ratio <= 0) {
if (hh.includes('e')) nw = Math.max(4, pos.x - x)
if (hh.includes('s')) nh = Math.max(4, pos.y - y)
if (hh.includes('w')) { const right = x + w; nx = Math.min(pos.x, right - 4); nw = right - nx }
if (hh.includes('n')) { const bottom = y + h; ny = Math.min(pos.y, bottom - 4); nh = bottom - ny }
S.cropRect = { x: nx, y: ny, w: nw, h: nh }
return
}
// 等比约束:同样允许超出画布边界
const ratio = c.ratio
if (hh === 'e' || hh === 'w') {
if (hh === 'e') {
nw = Math.max(4, pos.x - x)
} else {
const right = x + w
nx = Math.min(pos.x, right - 4)
nw = right - nx
}
nh = nw / ratio
} else if (hh === 'n' || hh === 's') {
if (hh === 's') {
nh = Math.max(4, pos.y - y)
} else {
const bottom = y + h
ny = Math.min(pos.y, bottom - 4)
nh = bottom - ny
}
nw = nh * ratio
} else {
if (hh === 'se') {
nw = Math.max(4, pos.x - x)
nh = Math.max(4, pos.y - y)
} else if (hh === 'ne') {
nw = Math.max(4, pos.x - x)
const bottom = y + h
ny = Math.min(pos.y, bottom - 4)
nh = bottom - ny
} else if (hh === 'sw') {
const right = x + w
nx = Math.min(pos.x, right - 4)
nw = right - nx
nh = Math.max(4, pos.y - y)
} else if (hh === 'nw') {
const right = x + w
nx = Math.min(pos.x, right - 4)
nw = right - nx
const bottom = y + h
ny = Math.min(pos.y, bottom - 4)
nh = bottom - ny
}
// 等比修正
if (nw / nh > ratio) {
nh = nw / ratio
if (hh === 'ne' || hh === 'nw') ny = y + h - nh
} else {
nw = nh * ratio
if (hh === 'nw' || hh === 'sw') nx = x + w - nw
}
}
S.cropRect = { x: nx, y: ny, w: nw, h: nh }
}
/**
* 确认裁剪(v1.2 起非破坏性:可撤销、不 flatten)。
*
* 旧实现把可见图层合成成一张图再 setupCanvas,等于:① 所有图层被合并成一张;
* ② S.history 直接清零 —— 裁错了没有任何退路。现在改为:
* ① 先 saveSnapshot('裁剪'),快照记的是「裁剪前」的尺寸 + 每层像素;
* ② 逐图层把可见区域搬进新尺寸的 canvas(图层结构、命名、透明度、锁定全保留);
* ③ resizeWorkspace 只换尺寸不重建图层,像素随后写回。
* 撤销时 restoreState 会先把画布尺寸复位到快照里的 imgW/imgH,再回填像素。
*/
export function confirmCrop() {
if (!S.cropRect) return
const { x, y, w, h } = S.cropRect
if (w < 2 || h < 2) { cancelCrop(); return }
const c = S.cropConstraint
const sx = Math.round(x), sy = Math.round(y)
const sw = Math.max(1, Math.round(w)), sh = Math.max(1, Math.round(h))
const isSize = c.type === 'size' && c.sizeW > 0 && c.sizeH > 0
const nw = isSize ? Math.max(1, Math.round(c.sizeW)) : sw
const nh = isSize ? Math.max(1, Math.round(c.sizeH)) : sh
// 完全没变就别记一步空历史
if (nw === S.imgW && nh === S.imgH && sx === 0 && sy === 0) { cancelCrop(); return }
const oldW = S.imgW, oldH = S.imgH
const scaleX = nw / sw, scaleY = nh / sh
// 裁剪框可以超出画面:源矩形先夹到画面内,目标矩形按同一比例落位(超出部分为透明)
const srcX = Math.max(0, sx), srcY = Math.max(0, sy)
const srcW = Math.max(0, Math.min(oldW, sx + sw) - srcX)
const srcH = Math.max(0, Math.min(oldH, sy + sh) - srcY)
const dstX = (srcX - sx) * scaleX, dstY = (srcY - sy) * scaleY
const dstW = srcW * scaleX, dstH = srcH * scaleY
// ① 进历史:快照记「裁剪前」的尺寸与每层像素
saveSnapshot('裁剪')
// ② 旧坐标系下的选区/拉框/蚂蚁线/浮动条全部失效
disposeSelection()
// ③ 逐图层把可见区域搬出来(保留图层结构,不再合成成一张)
const staged = S.layers.map(layer => {
const tmp = document.createElement('canvas')
tmp.width = nw
tmp.height = nh
if (srcW > 0 && srcH > 0) {
try {
tmp.getContext('2d').drawImage(layer.canvas, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH)
} catch (e) { /* 单层搬运失败不阻断其余 */ }
}
return tmp
})
// ④ 换尺寸(会清空图层像素)后把搬出来的内容写回
resizeWorkspace(nw, nh)
S.layers.forEach((layer, i) => {
const tmp = staged[i]
try { layer.ctx.drawImage(tmp, 0, 0) } catch (e) { /* ignore */ }
tmp.width = 0
tmp.height = 0
// 像素已落在新坐标系的正确位置,几何元数据不能再参与二次定位;
// 图片源(image / sourceCanvas)尺寸是旧的,留着会让重绘错位,必须摘掉。
// 摘掉后这些层按「像素层」参与快照与恢复(见 vendor/layer-logic.js)。
layer.x = 0
layer.y = 0
layer.w = nw
layer.h = nh
layer.rotation = 0
layer.transformable = false
layer.image = null
layer.sourceCanvas = null
layer._srcBox = null
layer._bounds = undefined
})
// ⑤ 文字/形状按裁剪区域位移与缩放
S.textLayers = S.textLayers.map(t => ({
...t,
x: (t.x - sx) * scaleX,
y: (t.y - sy) * scaleY,
fontSize: t.fontSize * scaleX
}))
S.shapeLayers = S.shapeLayers.map(s => ({
...s,
...(s.type === 'pen' ? { pts: (s.pts || []).map(p => ({ x: (p.x - sx) * scaleX, y: (p.y - sy) * scaleY })) } : {
x1: (s.x1 - sx) * scaleX, y1: (s.y1 - sy) * scaleY,
x2: (s.x2 - sx) * scaleX, y2: (s.y2 - sy) * scaleY
}),
lw: Math.max(1, s.lw * (scaleX + scaleY) / 2)
}))
S.selectedTextId = null
S.textDrag = null
S.selectedShapeId = null
S.shapeDrag = null
// 裁剪后图层 id 不变但几何全变,旧的选中 id 与拖拽中间态都要清
S.selectedLayerId = null
S.bitmapDrag = null
S.zoom = 1
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
updateCropInfo()
if (S.renderAll) S.renderAll()
toast('已裁剪为 ' + nw + '×' + nh + '(Ctrl+Z 可撤销)', 'success')
}
export function cancelCrop() {
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
clearOverlay()
updateCropInfo()
}
// ============ 裁剪栏 ============
// 裁剪参数已迁入选项栏(optionBarHTML('crop'),随工具切换自动出现/消失),
// 画布下方的浮窗 DOM 已删除。这两个入口保留为空操作,调用点(setTool / 拉框)无需改动。
export function showCropBar() { /* 选项栏自动承载,见 events.js#optionBarHTML */ }
export function hideCropBar() { /* 同上 */ }
+417
View File
@@ -0,0 +1,417 @@
/* dom.js - 编辑器 DOM 构建与图片加载
* 节:DOM 创建、图片加载。
* createEl 负责创建遮罩根节点并写入 runtime.el,随后把各 canvas/面板
* 引用挂到 S 上;open() 依赖它保证 el 只创建一次。
*/
'use strict'
import { S, runtime } from './state.js'
import { bindEvents } from './events.js'
// ============ 调色面板(工具栏弹层) ============
/**
* v1.19:右栏常驻面板删掉,只剩工具栏弹层这一份(钉住后它本来就是常开的)。
* 仍抽成函数而不是写在模板里:这套控件有 4 组联动(tab 高亮、SV/色相指示点、
* HEX 回填、常用色/最近色的 active 圈),events.js#updateColorUI 按
* `[data-color-surface]` 逐个刷 —— 留着这层抽象,将来若再加一处面板不用重写联动。
*/
/* 15 个常用色 + 第一格「去色」= 色板里 8 列 × 2 行(v1.20)。
排布刻意成对:第一行是 7 个饱和亮色(红橙黄绿青蓝粉)+ 去色打头,
第二行是 4 个中性色(白/浅灰/中灰/黑)+ 4 个同色系「深一档」,
深红/深绿/深蓝/深紫 在浅色底图上比亮色稳,做描边不刺眼。
亮紫 #aa44ff 让位给第一格的「去色」(v1.20,用户 2026-11-10:去色放常用色第一个)——
紫色还留着深一档的 #6b4fbb,色相不缺,8×2 的网格也不用改成 3 行。 */
const COMMON_COLORS = [
'#ff4444', '#ff8a00', '#ffd400', '#4cd964', '#00bfa5', '#4488ff', '#ff66aa',
'#ffffff', '#d0d0d0', '#808080', '#000000', '#c0392b', '#0f9d58', '#1677ff', '#6b4fbb'
]
/** 色板面板(v1.19 起只有工具栏弹层一份,右栏常驻面板已删)
*
* 头部一行:调哪个槽(描边/填充/底色)│ 吸管 + 色值 │ 图钉
* 把「吸管 + 色值」提到头部,是为了让下面整块高度都留给色块:
* 常用色 2 排 + 最近色 2 排,一屏就能点到,不用滚动、也不用二次点开。
*
* v1.20(用户 2026-11-10):头部不再随上下文增减控件。
* 原因是文字工具会多出「底色」tab,头部一行本来就贴着 440 的极限,
* 再去掉/加上「去色」就会把色值框和吸管挤变形(甚至整颗按钮被 flex 抵没)。
* 现在「去色」下移到常用色网格的第一格 —— 位置永远固定,不可用时只是变灰 + disabled,
* 头部元素因此全是定宽,切工具时头部不再重排。
*/
function colorSurfaceHtml() {
return `
<div class="iwb-color-pop-head">
<button type="button" class="iwb-color-pop-tab active" data-color-slot="stroke" title="正在调描边色(形状描边 / 画笔 / 文字色)"><i></i><span class="iwb-color-pop-tab-label">描边</span></button>
<button type="button" class="iwb-color-pop-tab" data-color-slot="fill" title="正在调填充色(形状内部颜色 / 文字描边色)"><i></i><span class="iwb-color-pop-tab-label">填充</span></button>
<button type="button" class="iwb-color-pop-tab" data-color-slot="bg" hidden title="正在调文本框底色(垫在文字下面)"><i></i><span class="iwb-color-pop-tab-label">底色</span></button>
<!-- 吸管 + 色值 + 图钉(v1.20.1,用户 2026-11-10):整组右对齐。
v1.20 只把图钉推到最右,吸管和色值还紧跟 tab —— tab 数量一变
(文字工具多出「底色」),这组就左右浮一次,用户截图里就是这个现象。
现在 tab 组独占左侧、剩余空隙由它吸收,右组整体钉在右侧,切工具纹丝不动。
右组前面那条竖线删掉了:空隙已经把「选槽」和「取色」分开,
右对齐后它只会孤零零悬在空白里。留下的那条竖线是分隔「图钉」这个常驻开关。 -->
<span class="iwb-color-pop-tools">
<button type="button" class="iwb-editor-color-eye" data-action="palettePick" title="吸色:切到吸管工具,在画布上点一下取色"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3Z"/></svg></button>
<input class="iwb-editor-color-hex-input" value="#ff4444" maxlength="7" spellcheck="false" autocomplete="off" title="十六进制颜色,回车生效">
<span class="iwb-color-pop-bar"></span>
<!-- 钉住(v1.18,用户 2026-11-10):调色常常要连着改好几处,每次点开色板太碎。
钉住后点画布 / 点别处都不收起,只有再点一次图钉、按 Esc、或点吸管才收。
图标是竖向图钉(头朝上),激活态整颗变琥珀色。 -->
<button type="button" class="iwb-color-pop-pin" data-action="pinColorPop" aria-pressed="false" title="钉住色板:一直开着,点画布也不收起(再点一次取消)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"/></svg></button>
</span>
</div>
<div class="iwb-color-pop-body">
<div class="iwb-color-pop-picker">
<div class="iwb-color-sv"><span></span></div>
<div class="iwb-color-hue"><span></span></div>
</div>
<span class="iwb-color-pop-sep"></span>
<!-- 色块区(v1.19):常用色 8×2 在上、最近色 8×2 在下,中间 1px 细线分隔。
不写「常用色 / 最近」小标题 —— 每个色块的 title 已经写明是哪一个,
而标题要各占一行,是这块面板最浪费的高度(v1.18 已这么定,v1.19 沿用)。 -->
<div class="iwb-color-pop-side">
<div class="iwb-color-group">
<span class="iwb-color-group-label">常用色</span>
<div class="iwb-editor-color-swatches">
<!-- 去色(v1.20,用户 2026-11-10):原来是头部一颗带文字的按钮,现在占常用色第一格。
好处有二:① 位置永远固定,切到文字/箭头这类「去不掉色」的上下文只是变灰,
不会整颗消失;② 头部腾出一颗按钮的宽度,文字工具多出「底色」tab 也挤不坏色值框。
含义随当前槽变(无描边 / 无填充 / 无底色),title 在 updateColorUI 里刷。 -->
<button type="button" class="iwb-color-pop-none" data-color-none="1" title="去色:当前这一项不上色(描边/填充/底色按上下文透明)"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="m5.6 5.6 12.8 12.8"/></svg></button>
${COMMON_COLORS.map(c => `<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="${c}" style="background:${c}" title="${c}"></button>`).join('')}
</div>
</div>
<div class="iwb-color-group">
<span class="iwb-color-group-label">最近</span>
<div class="iwb-editor-recent-colors" hidden title="最近使用"></div>
</div>
</div>
</div>`
}
// ============ DOM 创建 ============
export function createEl() {
if (runtime.el) return
runtime.el = document.createElement('div')
runtime.el.id = 'iwb-editor-overlay'
runtime.el.className = 'iwb-editor-overlay'
runtime.el.innerHTML = `
<div class="iwb-editor-modal">
<div class="iwb-editor-header">
<span class="iwb-editor-title">图片编辑 <em class="iwb-editor-doc-size">—</em></span>
<!-- 会话组(v1.2.9):标题是标题、按钮是按钮 —— 新建/覆盖/退出跟在标题后(用户裁定 2026-11-04 晚) -->
<div class="iwb-editor-session">
<button class="iwb-editor-btn iwb-editor-btn-new" data-action="newNode" title="把当前编辑结果新建为节点(不关闭编辑器)">新建</button>
<button class="iwb-editor-btn iwb-editor-btn-replace" data-action="replace" title="用当前编辑结果覆盖原图">覆盖</button>
<button class="iwb-editor-btn iwb-editor-btn-cancel" data-action="cancel" title="放弃修改并退出">退出</button>
</div>
<!-- 撤销/重做/还原(v1.18,用户 2026-11-10):从顶栏搬到画布底部工具栏最右侧。
理由:这三个是「画画时会连着按」的操作,手在画布上,不该抬头去顶栏找。
顶栏只留会话组(新建/覆盖/退出)与输出。 -->
<!-- 顶栏命令带已清空(v1.13):
四个「置顶/上移/下移/置底」按钮删除(图层面板可拖动 + Ctrl+]/[ 已覆盖);
「适应窗口 / 收起侧栏」搬到画布底部工具栏最右侧,离画布更近。
整个 .iwb-editor-commands 容器一并移除,不留一条空分隔线。 -->
<div class="iwb-editor-export-actions">
<div class="iwb-editor-export-settings-wrap">
<button class="iwb-editor-export-settings-btn" data-action="toggleExportSettings" aria-expanded="false">输出 <span class="iwb-editor-export-summary">原尺寸 PNG</span> ▾</button>
<div class="iwb-editor-export-settings">
<div class="iwb-editor-export-row"><span>预设</span>
<button data-export-key="preset" data-export-value="original">原尺寸</button>
<button data-export-key="preset" data-export-value="ecom800">电商方图</button>
</div>
<div class="iwb-editor-export-row"><span>格式</span>
<button data-export-key="format" data-export-value="png">PNG</button>
<button data-export-key="format" data-export-value="jpeg">JPG</button>
<button data-export-key="format" data-export-value="webp">WebP</button>
</div>
<div class="iwb-editor-export-row"><span>背景</span>
<button data-export-key="bg" data-export-value="transparent">透明</button>
<button data-export-key="bg" data-export-value="white">白底</button>
</div>
<div class="iwb-editor-export-row" data-export-when="ecom800"><span>边长</span>
<button data-export-key="size" data-export-value="750">750</button>
<button data-export-key="size" data-export-value="800">800</button>
<button data-export-key="size" data-export-value="1000">1000</button>
<button data-export-key="size" data-export-value="1200">1200</button>
</div>
<div class="iwb-editor-export-row" data-export-when="ecom800" title="商品图体积上限(仅对 JPG / WebP 生效,PNG 无法降质)"><span>≤KB</span>
<button data-export-key="maxKB" data-export-value="0">不限</button>
<button data-export-key="maxKB" data-export-value="300">300</button>
<button data-export-key="maxKB" data-export-value="500">500</button>
<button data-export-key="maxKB" data-export-value="800">800</button>
</div>
<div class="iwb-editor-export-note">一次只输出一个结果;设置会记住</div>
</div>
</div>
<button class="iwb-editor-btn iwb-editor-btn-copy" data-action="copyClipboard" title="复制当前结果到系统剪贴板(可直接粘到聊天窗口/后台),不关闭编辑器">复制</button>
<button class="iwb-editor-btn iwb-editor-btn-download" data-action="download" title="导出当前这一张(不关闭编辑器)">导出</button>
</div>
</div>
<div class="iwb-editor-optionbar">
<span class="iwb-editor-optionbar-label">工具选项</span>
<div class="iwb-editor-optionbar-body"></div>
<span class="iwb-editor-optionbar-tip" title="选中后还可右键;Ctrl+J 复制 · Delete 清除 · Ctrl+D 取消选区">Ctrl+J 复制 · Delete 清除</span>
</div>
<div class="iwb-editor-main">
<div class="iwb-editor-layer-panel">
<div class="iwb-editor-layer-panel-header">
<span class="iwb-editor-layer-panel-title">图层</span>
<!-- 图层的「新建 / 导入图片」回到标题栏右侧(用户裁定 2026-11-04:顶栏只留顺序与视图命令) -->
<div class="iwb-editor-layer-add-group">
<button class="iwb-editor-layer-add-btn" data-action="mergeLayers" title="合并图层 (Ctrl/⌘+E):⌘/Ctrl 点击可多选图层后合并;未多选时向下合并"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 2 9 4.5-9 4.5-9-4.5L12 2Z"/><path d="m3 12 9 4.5 9-4.5"/><path d="M12 17v4"/><path d="m9.5 18.5 2.5 2.5 2.5-2.5"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="mergeVisible" title="合并可见图层 (Ctrl/⌘+Shift+E):隐藏的图层保留不动"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 2 9 4.5-9 4.5-9-4.5L12 2Z"/><path d="m3 11 9 4.5 9-4.5"/><path d="m3 15.5 9 4.5 9-4.5"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="addBlankLayer" title="新建空白图层 (Ctrl+Shift+N)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="addBitmapLayer" title="导入图片为新图层 (Ctrl+O),也可直接 ⌘/Ctrl+V 粘贴剪贴板图片"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg></button>
</div>
</div>
<!-- 图层顺序(置顶/上移/下移/置底)已移到顶栏命令带(v1.2.4) -->
<div class="iwb-editor-layer-list"></div>
</div>
<div class="iwb-editor-canvas-wrap">
<div class="iwb-editor-canvas-stack">
<div class="iwb-editor-transparency-grid"></div>
<!-- 位图图层 canvas 动态插入此处 -->
<canvas class="iwb-editor-stroke"></canvas>
<canvas class="iwb-editor-text"></canvas>
<canvas class="iwb-editor-crop-overlay"></canvas>
<canvas class="iwb-editor-selection-overlay"></canvas>
<canvas class="iwb-editor-cursor-overlay"></canvas>
</div>
<!-- v1.9:input → textarea,支持 Shift+Enter 换行(Enter 仍是确认) -->
<textarea class="iwb-editor-text-input" rows="1" wrap="off" placeholder="输入文字,Enter 确认,Shift+Enter 换行" spellcheck="false"></textarea>
<div class="iwb-editor-picker-tip"><span class="iwb-editor-picker-chip"></span><span class="iwb-editor-picker-hex">#ffffff</span></div>
<!-- 裁剪参数已迁入选项栏(v1.2.2),画布下方浮窗删除 -->
<div class="iwb-editor-sel-bar">
<span class="iwb-editor-sel-info">未框选</span>
<button data-sel-cmd="sel.copy" data-needs-sel="1" title="把当前图层选区复制为新图层 (Ctrl+J)">复制</button>
<button data-sel-cmd="sel.cut" data-needs-sel="1" title="剪切到新图层 (Ctrl+X)">剪切</button>
<button data-sel-cmd="sel.delete" data-needs-sel="1" title="只清除当前图层选区内容 (Delete)">删除</button>
<button data-sel-cmd="sel.fill" data-needs-sel="1" title="用当前颜色填充选区">填充</button>
<button data-sel-cmd="sel.invert" data-needs-sel="1" title="反选 (Ctrl+Shift+I)">反选</button>
<button data-sel-cmd="sel.all" title="全选 (Ctrl+A)">全选</button>
<button data-sel-cmd="sel.none" title="取消选区 (Esc / Ctrl+D)">取消</button>
</div>
<div class="iwb-editor-tools">
<!-- 颜色(v1.11 两格 → v1.12 文字三格):
形状下是「描边 + 填充」两格叠放在一个按钮位里(PS 式前/背景色);
文字下是「文字 / 描边 / 底色」三格横排 —— 文字对象天生就有三个颜色,
只给两格必然有一格无处安放(用户反馈「文本不支持描边与字体色切换」)。
点哪格就调哪格:色板只有一套,写谁由 S.colorTarget 决定。
关掉的那格画斜杠,跟随描边色的填充块带一个小三角角标。 -->
<div class="iwb-editor-color-pair" data-color-mode="single">
<button type="button" class="iwb-editor-color-btn" data-color-slot="stroke" data-action="toggleColorPop" aria-expanded="false" title="描边色:形状描边 / 画笔 / 文字都用它。点开色板调色"><i></i></button>
<button type="button" class="iwb-editor-color-btn" data-color-slot="fill" data-action="toggleColorPop" aria-expanded="false" title="填充色:形状内部颜色。点开色板调色,色板里可切换「无填充」"><i></i></button>
<button type="button" class="iwb-editor-color-btn" data-color-slot="bg" data-action="toggleColorPop" aria-expanded="false" title="文本框底色:垫在文字下面的一块半透明色板。点开调色,可选「无」"><i></i></button>
</div>
<span class="iwb-editor-divider"></span>
<button class="iwb-editor-tool" data-tool="select" title="选择/移动 (V):点击元素选中,拖拽移动,手柄调整大小,双击文字改内容"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3l7.07 16.97 2.51-7.39 7.39-2.51L3 3z"/></svg></button>
<span class="iwb-editor-divider"></span>
<button class="iwb-editor-tool" data-tool="marquee" title="选框 (M):拖出矩形/椭圆选区,松手后旁边出现操作条;Shift+M 切换矩形/椭圆"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4 3"><rect x="3" y="4" width="18" height="16" rx="1"/></svg></button>
<button class="iwb-editor-tool" data-tool="lasso" title="套索 (A):按住拖动自由圈选,松手闭合"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12c0-4 3.6-7 8-7s8 3 8 7-3.6 7-8 7c-2 0-3.8-.6-5.2-1.6"/><path d="M6.8 17.4 4 20l1.2-3.2"/><circle cx="20" cy="19" r="2"/></svg></button>
<button class="iwb-editor-tool active" data-tool="brush" title="画笔 (B):] 增大 / [ 减小笔刷;按住 Alt 临时吸色"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/><path d="m15 5 4 4"/></svg></button>
<button class="iwb-editor-tool" data-tool="eraser" title="橡皮 (E):] 增大 / [ 减小笔刷;擦除当前活跃图层,与画笔共用大小/硬度/透明度;按住 Alt 临时吸色"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg></button>
<button class="iwb-editor-tool" data-tool="pen" title="钢笔 (P):点击添加节点,双击或 Enter 完成自定义形状"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 19 7-7 3 3-7 7-3-3z"/><path d="m18 13-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><path d="m2 2 7.586 7.586"/><circle cx="11" cy="11" r="2"/></svg></button>
<button class="iwb-editor-tool" data-tool="text" title="文字 (T)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 7 4 3 20 3 20 7"/><line x1="9" y1="20" x2="15" y2="20"/><line x1="12" y1="3" x2="12" y2="20"/></svg></button>
<button class="iwb-editor-tool" data-tool="rect" title="矩形 (R):Shift+U 在矩形/圆形/箭头间循环"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/></svg></button>
<button class="iwb-editor-tool" data-tool="circle" title="圆形 (O):Shift+U 在矩形/圆形/箭头间循环"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="8"/></svg></button>
<button class="iwb-editor-tool" data-tool="arrow" title="箭头 (L):Shift+U 在矩形/圆形/箭头间循环"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg></button>
<button class="iwb-editor-tool" data-tool="picker" title="吸管 (I):点击画布取色(悬停预览);选中形状/文字时取色直接改它的颜色,取完切回上一工具"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3Z"/></svg></button>
<button class="iwb-editor-tool" data-tool="hand" title="抓手 (H):拖拽自由移动画布(任意工具下按住空格或鼠标中键也可平移)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 11V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v0"/><path d="M14 10V4a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v2"/><path d="M10 10.5V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v8"/><path d="M18 10a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"/></svg></button>
<span class="iwb-editor-divider"></span>
<button class="iwb-editor-tool" data-tool="crop" title="裁剪 (C):参数在选项栏;Enter 确认 / Esc 取消"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6.13 1L6 16a2 2 0 0 0 2 2h15"/><path d="M1 6.13L16 6a2 2 0 0 1 2 2v15"/></svg></button>
<!-- 视图快捷(v1.13):从顶栏搬过来,贴在工具条最右侧的「|」之后。
工具条本身是 shrink-to-fit 且居中,所以这一组天然就是「最右边」。 -->
<span class="iwb-editor-divider"></span>
<button class="iwb-editor-tool iwb-editor-view-btn" data-action="zoomFit" title="适应窗口 (Ctrl+0):整张图缩放到刚好放得下"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 3 3 3 3 9"/><polyline points="15 3 21 3 21 9"/><polyline points="3 15 3 21 9 21"/><polyline points="21 15 21 21 15 21"/></svg></button>
<button class="iwb-editor-tool iwb-editor-view-btn" data-action="togglePanels" title="收起 / 展开侧栏 (Tab)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><line x1="9" y1="4" x2="9" y2="20"/></svg></button>
<!-- 撤销 / 重做 / 还原(v1.18):从顶栏移到工具条最右。
放在视图快捷之后,是整条工具栏真正的末端 —— 手在画布区时离得最近。 -->
<span class="iwb-editor-divider"></span>
<div class="iwb-editor-history">
<button class="iwb-editor-action" data-action="undo" title="撤销 (Ctrl+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg></button>
<button class="iwb-editor-action" data-action="redo" title="重做 (Ctrl+Shift+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg></button>
<button class="iwb-editor-action iwb-editor-action-reset" data-action="reset" title="还原原图:删掉所有标注/图层,回到打开时的样子(Ctrl+Z 可撤销)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/></svg></button>
</div>
</div>
</div>
<div class="iwb-editor-zoom-hint">滚轮缩放 · 抓手/空格/中键拖拽自由移动画布</div>
<aside class="iwb-editor-left">
<!-- v1.16:侧栏宽度拖拽手柄。贴在侧栏左边缘(它在画布右侧),
双击复位。宽度写进 CSS 变量 --iwb-side-w,由 --iwb-side-w 统一裁各条 width 规则。 -->
<div class="iwb-editor-side-resizer" data-side-resizer="1" title="拖动调整侧栏宽度,双击复位"></div>
<!-- 右栏常驻调色面板已删(v1.19,用户 2026-11-10:「右边栏的调色模块就可以去掉了」)。
理由:弹层钉住之后它一直是开着的,右栏那份同样内容只是在跟弹层抢注意力,
还白占一块最显眼的位置。颜色只剩弹层一处(modal 末尾 .iwb-editor-color-pop),
右栏现在从「图片调节」直接开始。 -->
<!-- 图片调节(v1.15):连续调色,作用于当前位图图层(默认原图)。
行由 adjust.js#mountAdjustPanel() 按 ADJUST_DEFS 生成 —— 参数表只维护一份,
不在 DOM 里再抄一遍(这个项目已经因为「同一个概念两处各写一份」栽过几次)。
和下方「快速效果」的分工:这里是精细连续调,那边是一键换风格。 -->
<section class="iwb-editor-adj">
<div class="iwb-editor-adj-head">
<span class="iwb-editor-adj-title">图片调节</span>
<span class="iwb-editor-adj-target" title="调节作用于当前位图图层">原图</span>
<button type="button" class="iwb-editor-adj-reset" data-adj-reset="all" disabled title="把所有调节项归零(Ctrl+Z 可撤销)">复位</button>
</div>
<div class="iwb-editor-adj-list"></div>
<p class="iwb-editor-adj-tip">拖动实时预览,松手出精细结果 · 双击滑杆归零</p>
</section>
<!-- 快速效果(v1.4):作用于当前位图图层,点一下就应用,Ctrl+Z 撤销。
目标层名由 effects.js 的 updateFxTargetLabel() 实时刷新。 -->
<section class="iwb-editor-fx">
<div class="iwb-editor-fx-head">
<span class="iwb-editor-fx-title">快速效果</span>
<span class="iwb-editor-fx-target" title="效果作用于当前位图图层">原图</span>
</div>
<div class="iwb-editor-fx-grid">
<button type="button" class="iwb-editor-fx-btn" data-fx="invert" title="反白(反相 Invert):明暗翻转,白底变黑底、黑字变白字">
<span class="iwb-editor-fx-ico ico-invert"></span><span>反白</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="gray" title="灰度:去色,保留明暗层次">
<span class="iwb-editor-fx-ico ico-gray"></span><span>灰度</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="boost" title="增强:提亮并略加对比,适合发灰的截图">
<span class="iwb-editor-fx-ico ico-boost"></span><span>增强</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="contrast" title="高对比:压成黑白硬调,突出主体">
<span class="iwb-editor-fx-ico ico-contrast"></span><span>高对比</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="soft" title="柔化:轻微模糊,弱化背景">
<span class="iwb-editor-fx-ico ico-soft"></span><span>柔化</span>
</button>
<button type="button" class="iwb-editor-fx-btn" data-fx="mosaic" title="马赛克:像素化,用于打码手机号/地址等隐私信息">
<span class="iwb-editor-fx-ico ico-mosaic"></span><span>马赛克</span>
</button>
</div>
<!-- v1.8:效果参数。点效果后启用,范围/单位随效果切换(马赛克=块大小,柔化=半径,其余=强度) -->
<div class="iwb-editor-fx-adj iwb-editor-fx-adj-off">
<div class="iwb-editor-fx-adj-head">
<span class="iwb-editor-fx-adj-name">强度</span>
<span class="iwb-editor-fx-adj-val">—</span>
</div>
<input type="range" class="iwb-editor-fx-range" min="0" max="100" step="1" value="0" disabled aria-label="效果强度">
</div>
<p class="iwb-editor-fx-tip">先点效果,再拖强度微调 · Ctrl+Z 撤销</p>
</section>
<div class="iwb-editor-zoom">
<button class="iwb-editor-zoom-btn" data-action="zoomOut" title="缩小 (Ctrl+- / 滚轮向下)">−</button>
<span class="iwb-editor-zoom-val" title="滚轮缩放">100%</span>
<button class="iwb-editor-zoom-btn" data-action="zoomIn" title="放大 (Ctrl++ / 滚轮向上)">+</button>
<button class="iwb-editor-zoom-btn iwb-editor-zoom-fit" data-action="zoomFit" title="适应窗口">适应</button>
</div>
</aside>
</div>
<div class="iwb-editor-footer">
</div>
<div class="iwb-editor-statusbar">
<span class="iwb-editor-status-zoom">100%</span>
<span class="iwb-editor-status-size">—</span>
<span class="iwb-editor-status-pos">x — y —</span>
<span class="iwb-editor-status-sel">无选区</span>
<span class="iwb-editor-status-layer">当前层:原图</span>
<span class="iwb-editor-status-tool">画笔</span>
</div>
<!-- 色板弹层(v1.3;v1.16 起与右栏常驻面板共用同一份 DOM):
工具栏色块点击展开。必须挂在 modal 下、不能塞进 .iwb-editor-tools ——
工具栏是 overflow-x:auto,canvas-wrap 是 overflow:clip,塞进去弹层会被直接裁掉;
定位由 events.js 计算。 -->
<div class="iwb-editor-color-pop" data-color-surface="pop" hidden>
${colorSurfaceHtml()}
</div>
<div class="iwb-editor-toast" role="status" aria-live="polite"></div>
</div>
`
document.body.appendChild(runtime.el)
S.canvasWrap = runtime.el.querySelector('.iwb-editor-canvas-wrap')
S.canvasStack = runtime.el.querySelector('.iwb-editor-canvas-stack')
S.transparencyGrid = runtime.el.querySelector('.iwb-editor-transparency-grid')
S.textCanvas = runtime.el.querySelector('.iwb-editor-text')
S.strokeCanvas = runtime.el.querySelector('.iwb-editor-stroke')
S.overlayCanvas = runtime.el.querySelector('.iwb-editor-crop-overlay')
S.selectionCanvas = runtime.el.querySelector('.iwb-editor-selection-overlay')
S.cursorCanvas = runtime.el.querySelector('.iwb-editor-cursor-overlay')
S.textCtx = S.textCanvas.getContext('2d')
S.strokeCtx = S.strokeCanvas.getContext('2d')
S.overlayCtx = S.overlayCanvas.getContext('2d')
S.selectionCtx = S.selectionCanvas.getContext('2d')
S.cursorCtx = S.cursorCanvas.getContext('2d')
bindEvents()
}
// ============ 图片加载 ============
/**
* 把 base64 dataURL 本地解码成 Blob(不经过 fetch)。
*
* [插件移植改动] 上游用 `fetch(dataURL)` 转 blob URL,但宿主 CSP 是
* `connect-src 'self' https: http://127.0.0.1:30092 http://localhost:30092` —— 不含 `data:`,
* 于是每次 loadImage 都会触发一次 CSP 违规(上游的 catch 回退让它「还能用」,但控制台每次都报错)。
* 这里改为纯本地解码,行为与上游一致(同样拿到 blob URL),且不依赖网络/CSP。
*/
function dataUrlToBlob(dataUrl) {
const comma = dataUrl.indexOf(',')
if (comma < 0) return null
const meta = dataUrl.slice(0, comma)
if (!/;base64/i.test(meta)) return null
const mime = (/^data:([^;,]+)/.exec(meta) || [])[1] || 'image/png'
const bin = atob(dataUrl.slice(comma + 1))
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
return new Blob([bytes], { type: mime })
}
/**
* dataURL 一律先转 blob URL 再喂给 Image:img.src 直接挂 dataURL 会让
* 元素在整个编辑会话期间持有一份几十 MB 的字符串(4K 源图 ≈44MB),而
* 解码只需一次 —— 载入完成立即 revoke,img 保留的是自己的解码资源,
* 之后 drawImage/复原都不再依赖那串字符。
*/
export async function loadImage(src) {
let useSrc = src
let revokeUrl = null
if (typeof src === 'string' && src.slice(0, 5) === 'data:') {
try {
const blob = dataUrlToBlob(src)
if (!blob) throw new Error('dataURL 不是 base64')
useSrc = URL.createObjectURL(blob)
revokeUrl = useSrc
} catch (e) { useSrc = src } // 解码不可用/失败:回落原 dataURL
}
try {
return await new Promise((resolve, reject) => {
const img = new Image()
img.onload = () => resolve(img)
img.onerror = () => reject(new Error('图片加载失败'))
img.src = useSrc
})
} finally {
if (revokeUrl) { try { URL.revokeObjectURL(revokeUrl) } catch (e) { /* ignore */ } }
}
}
+464
View File
@@ -0,0 +1,464 @@
/* effects.js - 侧栏「快速效果」(v1.4,v1.8 加可调参数)
*
* 作用对象只有一个:当前位图图层(侧栏标题后面实时显示层名)。
* 全部走 canvas 2D 的 ctx.filter / 缩放重采样,不引入依赖、不动矢量层、
* 不改图层几何,因此对「原图」这种带 locked 标记的层也安全(效果不是画笔)。
*
* 撤销:应用前 saveSnapshot()。base 与画笔层走像素快照(putImageData),
* 天然可回退;导入图片层走 image/sourceCanvas 重绘,原地改像素会被下一次
* 重绘冲掉,所以先按 PS「栅格化」的做法落一个普通位图副本(原层隐藏)。
*
* v1.8 可调参数的关键设计:**效果不能叠加在自身结果上**。
* 点效果时把目标层当时的像素备份进 S.fx.source,之后拖滑杆一律「先还原 source
* 再按新参数渲染」。否则「马赛克 12px → 40px → 12px」会变成三次采样、块越来
* 越碎且不可逆。历史粒度也因此干净:点效果拍一次快照,拖滑杆不再拍。
*/
'use strict'
import { S, runtime } from './state.js'
import { saveSnapshot } from './history.js'
import { createLayerCanvas, getActiveLayer, renderLayerPanel, reorderLayerCanvas, updateLayerCanvasStyles } from './layers.js'
import { layerUnits } from './objects.js'
import { needsPixelSnapshot } from '../vendor/layer-logic.js'
import { toast } from './commands.js'
const SOFT_MIN = 1.2
const SOFT_MAX = 8
function softRadius(canvas) {
// 默认半径跟短边走:800px 图 ≈2px(v1.4 是 1.6px,小图上几乎看不出模糊,
// 现在有了滑杆可自己拉,但默认值也要先看得出效果)
const side = Math.min(canvas.width || 0, canvas.height || 0)
return Math.max(SOFT_MIN, Math.min(SOFT_MAX, Math.round(side / 400 * 10) / 10))
}
function mosaicBlock(canvas) {
const side = Math.min(canvas.width || 0, canvas.height || 0)
return Math.max(6, Math.round(side / 60))
}
/**
* 效果表。参数语义分两类:
* unit '%' → 强度 0~100,0 等于不处理(invert/grayscale 原生支持比例)
* unit 'px' → 物理量(马赛克块边长 / 模糊半径),默认值按图短边缩放
* def 是函数:px 类要拿到 canvas 才能算默认值。
*/
export const QUICK_EFFECTS = {
invert: {
label: '反白', hint: '反相:明暗翻转,白底变黑底',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => {
if (v <= 0) return
const k = v / 100
if (FILTER_SUPPORTED) { filterCanvas(canvas, 'invert(' + k + ')'); return }
// 线性插值到反相值:out = c + (255 - 2c) * k
const ok = mapPixels(canvas, (r, g, b) => [
clamp255(r + (255 - 2 * r) * k),
clamp255(g + (255 - 2 * g) * k),
clamp255(b + (255 - 2 * b) * k)
])
if (!ok) blendFallback(canvas, 'invert', k)
}
},
gray: {
label: '灰度', hint: '去色,保留明暗层次',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => {
if (v <= 0) return
const k = v / 100
if (FILTER_SUPPORTED) { filterCanvas(canvas, 'grayscale(' + k + ')'); return }
const okGray = mapPixels(canvas, (r, g, b) => {
const y = luma(r, g, b)
return [clamp255(r + (y - r) * k), clamp255(g + (y - g) * k), clamp255(b + (y - b) * k)]
})
if (!okGray) blendFallback(canvas, 'gray', k)
}
},
boost: {
label: '增强', hint: '提亮并加对比,适合发灰的截图',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => {
if (v <= 0) return
const k = v / 100
if (FILTER_SUPPORTED) {
filterCanvas(canvas, 'brightness(' + (1 + 0.4 * k).toFixed(3) + ') contrast(' + (1 + 0.25 * k).toFixed(3) + ') saturate(' + (1 + 0.2 * k).toFixed(3) + ')')
return
}
const bright = 1 + 0.4 * k, contrast = 1 + 0.25 * k, sat = 1 + 0.2 * k
mapPixels(canvas, (r, g, b) => {
const y = luma(r, g, b)
const out = [r, g, b].map((c) => {
let v2 = y + (c - y) * sat
v2 = (v2 - 128) * contrast + 128
return clamp255(v2 * bright)
})
return out
})
}
},
contrast: {
label: '高对比', hint: '压成黑白硬调,突出主体',
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
render: (canvas, v) => {
if (v <= 0) return
const k = v / 100
if (FILTER_SUPPORTED) { filterCanvas(canvas, 'grayscale(' + k.toFixed(3) + ') contrast(' + (1 + 1.6 * k).toFixed(3) + ')'); return }
const c = 1 + 1.6 * k
mapPixels(canvas, (r, g, b) => {
const y = luma(r, g, b)
const gray = y * k + ((r + g + b) / 3) * (1 - k)
const v2 = (gray - 128) * c + 128
return [clamp255(v2), clamp255(v2), clamp255(v2)]
})
}
},
soft: {
label: '柔化', hint: '模糊,弱化背景',
param: '半径', unit: 'px', min: 0, max: 16, step: 0.5, def: (canvas) => softRadius(canvas),
render: (canvas, v) => {
if (v <= 0) return
if (FILTER_SUPPORTED) filterCanvas(canvas, 'blur(' + v + 'px)')
else blurCanvas(canvas, v)
}
},
mosaic: {
label: '马赛克', hint: '像素化,用于打码手机号/地址等隐私信息',
param: '块大小', unit: 'px', min: 2, max: 96, step: 1, def: (canvas) => mosaicBlock(canvas),
render: (canvas, v) => { if (v > 1) pixelateCanvas(canvas, v) }
}
}
/** 效果目标:当前活跃位图图层;没有就退回「原图」 */
export function effectTarget() {
const active = getActiveLayer()
if (active) return active
return S.layers.find(l => l.id === 'base') || null
}
/** 用 ctx.filter 把画布自身重绘一遍(临时画布中转,避免自绘自的采样问题) */
function filterCanvas(canvas, css) {
const w = canvas.width, h = canvas.height
if (!w || !h || !css) return
const tmp = document.createElement('canvas')
tmp.width = w
tmp.height = h
const tctx = tmp.getContext('2d')
tctx.filter = css
tctx.drawImage(canvas, 0, 0)
const ctx = canvas.getContext('2d')
ctx.save()
// 图层 ctx 平时带着视图变换,重绘必须回到设备像素坐标系
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.globalCompositeOperation = 'copy' // copy:连透明像素一起替换,不留旧内容
ctx.filter = 'none'
ctx.drawImage(tmp, 0, 0)
ctx.restore()
}
// ctx.filter 支持性:Chrome/Edge 支持,macOS WKWebView 长期不支持(赋值会被忽略)。
// 不支持时下面全部走像素级兜底,否则「只有马赛克有效」——马赛克本来就不依赖 filter。
// ctx.filter 支持性:不能只看「属性是否可赋值」——WKWebView 里属性存在但绘制时被忽略,
// 赋值检测会误判为支持。这里做功能性探测:红块过 invert(1) 之后必须变青。
const FILTER_SUPPORTED = (function () {
try {
const src = document.createElement('canvas')
src.width = 2; src.height = 2
const sctx = src.getContext('2d')
sctx.fillStyle = '#ff0000'
sctx.fillRect(0, 0, 2, 2)
const dst = document.createElement('canvas')
dst.width = 2; dst.height = 2
const dctx = dst.getContext('2d')
dctx.filter = 'invert(1)'
dctx.drawImage(src, 0, 0)
const d = dctx.getImageData(0, 0, 1, 1).data
return d[0] < 60 && d[1] > 180 && d[2] > 180
} catch (e) { return false }
})()
/** 逐像素处理(设备像素坐标系直接写回);画布被跨域图污染时 getImageData 会抛错 → 返回 false */
function mapPixels(canvas, fn) {
const w = canvas.width, h = canvas.height
if (!w || !h) return false
const ctx = canvas.getContext('2d', { willReadFrequently: true })
let img
try { img = ctx.getImageData(0, 0, w, h) } catch (e) { return false }
const d = img.data
for (let i = 0; i < d.length; i += 4) {
if (d[i + 3] === 0) continue
const out = fn(d[i], d[i + 1], d[i + 2])
d[i] = out[0]; d[i + 1] = out[1]; d[i + 2] = out[2]
}
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.putImageData(img, 0, 0)
return true
}
/** 混合模式兜底(读不到像素时):反相用 difference+白,去色用 saturation+灰 */
function blendFallback(canvas, mode, strength) {
const k = typeof strength === 'number' ? Math.max(0, Math.min(1, strength)) : 1
const ctx = canvas.getContext('2d')
const copy = document.createElement('canvas')
copy.width = canvas.width
copy.height = canvas.height
copy.getContext('2d').drawImage(canvas, 0, 0)
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
if (mode === 'invert') { ctx.globalCompositeOperation = 'difference'; ctx.fillStyle = '#ffffff' }
else { ctx.globalCompositeOperation = 'saturation'; ctx.fillStyle = '#808080' }
ctx.fillRect(0, 0, canvas.width, canvas.height)
// 按强度混回原图(k=1 全反相,k=0 原样)
if (k < 1) {
ctx.globalCompositeOperation = 'source-over'
ctx.globalAlpha = 1 - k
ctx.drawImage(copy, 0, 0)
}
ctx.restore()
}
function luma(r, g, b) { return 0.2126 * r + 0.7152 * g + 0.0722 * b }
function clamp255(v) { return v < 0 ? 0 : (v > 255 ? 255 : v) }
/** 模糊兜底:缩到 1/n 再平滑放大,效果接近 blur 且比卷积快得多 */
function blurCanvas(canvas, radius) {
const w = canvas.width, h = canvas.height
if (!w || !h || radius <= 0) return
const n = Math.max(2, Math.min(16, Math.round(radius * 1.6)))
const sw = Math.max(1, Math.round(w / n))
const sh = Math.max(1, Math.round(h / n))
const tmp = document.createElement('canvas')
tmp.width = sw; tmp.height = sh
const tctx = tmp.getContext('2d')
tctx.imageSmoothingEnabled = true
tctx.drawImage(canvas, 0, 0, sw, sh)
const ctx = canvas.getContext('2d')
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.globalCompositeOperation = 'copy'
ctx.imageSmoothingEnabled = true
ctx.drawImage(tmp, 0, 0, w, h)
ctx.restore()
}
/** 马赛克:缩到 1/block 再关掉平滑放大,比逐像素 getImageData 快一个量级 */
function pixelateCanvas(canvas, block) {
const w = canvas.width, h = canvas.height
if (!w || !h) return
const b = Math.max(2, block)
const sw = Math.max(1, Math.round(w / b))
const sh = Math.max(1, Math.round(h / b))
const tmp = document.createElement('canvas')
tmp.width = sw
tmp.height = sh
const tctx = tmp.getContext('2d')
tctx.imageSmoothingEnabled = true
tctx.drawImage(canvas, 0, 0, sw, sh)
const ctx = canvas.getContext('2d')
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.globalCompositeOperation = 'copy'
ctx.imageSmoothingEnabled = false
ctx.filter = 'none'
ctx.drawImage(tmp, 0, 0, w, h)
ctx.restore()
}
/** 目标层像素的独立副本(同尺寸),作为「可反复重调」的基准 */
function snapshotCanvas(canvas) {
const c = document.createElement('canvas')
c.width = canvas.width
c.height = canvas.height
const ctx = c.getContext('2d')
ctx.drawImage(canvas, 0, 0)
return c
}
/**
* 把「导入图片层」栅格化成普通位图,插在它上面一层。
* 只拷当前 canvas 的可见结果(已含旋转/缩放),所以视觉不变。
* 原层隐藏而不删除:撤销时快照里有它的 visible,能原样恢复。
*/
function rasterizeLayer(layer) {
const canvas = createLayerCanvas()
const ctx = canvas.getContext('2d', { willReadFrequently: true })
ctx.clearRect(0, 0, S.imgW, S.imgH)
ctx.drawImage(layer.canvas, 0, 0)
// z 取「原层 → 上一层」的中点,保证副本紧贴在原层上方,不会窜到别的标注之上
const units = layerUnits()
const i = units.findIndex(u => u.kind === 'bitmap' && u.obj === layer)
const baseZ = layer.z || 0
const nextZ = (i >= 0 && units[i + 1]) ? (units[i + 1].obj.z || 0) : baseZ + 1
const z = nextZ > baseZ ? (baseZ + nextZ) / 2 : baseZ + 0.5
const clone = {
id: 'fx' + Date.now() + Math.floor(Math.random() * 1000),
name: layer.name + ' · 效果',
canvas,
ctx,
opacity: layer.opacity == null ? 1 : layer.opacity,
visible: true,
locked: false,
x: 0, y: 0, w: S.imgW, h: S.imgH,
rotation: 0,
z
}
S.layers.push(clone)
layer.visible = false
if (S.selectedLayerId === layer.id) S.selectedLayerId = clone.id
S.activeLayerId = clone.id
reorderLayerCanvas()
updateLayerCanvasStyles()
renderLayerPanel()
return clone
}
/** 先还原基准像素,再按参数渲染一次 —— 所有重调都走这里 */
function renderFromSource(target, key, value) {
const st = S.fx
const fx = QUICK_EFFECTS[key]
if (!st.source || !fx) return
const ctx = target.canvas.getContext('2d')
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.globalCompositeOperation = 'copy'
ctx.filter = 'none'
ctx.imageSmoothingEnabled = true
ctx.drawImage(st.source, 0, 0)
ctx.restore()
try {
fx.render(target.canvas, value)
} catch (e) {
toast('效果失败:' + ((e && e.message) || e), 'error')
throw e
}
// 像素变了:包围盒要重算,吸管合成缓存要作废
target._bounds = undefined
S.pickerComposite = null
}
/** 数值展示:px 保留到 0.5(柔化),百分比取整 */
function fmtValue(fx, v) {
if (fx.unit === 'px') return (Math.round(v * 10) / 10) + ' px'
return Math.round(v) + '%'
}
/**
* 刷新侧栏「强度」这一条:滑杆范围随效果切换,目标层对不上时置灰。
* 切图层后源属于旧层,此时拖动会把旧像素写进新层 —— 所以必须靠 layerId 拦住。
* 切回原层自动恢复可用(源还在)。
*/
export function renderFxPanel() {
if (!runtime.el) return
const adv = runtime.el.querySelector('.iwb-editor-fx-adj')
if (!adv) return
const range = adv.querySelector('.iwb-editor-fx-range')
const nameEl = adv.querySelector('.iwb-editor-fx-adj-name')
const valEl = adv.querySelector('.iwb-editor-fx-adj-val')
const targetEl = runtime.el.querySelector('.iwb-editor-fx-target')
const layer = effectTarget()
// 当前生效的效果按钮高亮:面板是静态 DOM,只同步类名,不重建
const activeKey = S.fx.source ? S.fx.key : null
runtime.el.querySelectorAll('[data-fx]').forEach(btn => {
btn.classList.toggle('is-active', Boolean(activeKey) && btn.dataset.fx === activeKey)
})
if (targetEl) {
const name = layer ? layer.name : '无图层'
targetEl.textContent = name
targetEl.title = layer ? '效果作用于「' + name + '」' : '没有可处理的位图图层'
}
const st = S.fx
const fx = st.source ? QUICK_EFFECTS[st.key] : null
if (!fx || !range) {
adv.classList.add('iwb-editor-fx-adj-off')
if (nameEl) nameEl.textContent = '强度'
if (valEl) valEl.textContent = '—'
if (range) { range.disabled = true; range.value = '0' }
return
}
const usable = Boolean(layer && st.layerId === layer.id)
adv.classList.toggle('iwb-editor-fx-adj-off', !usable)
if (nameEl) nameEl.textContent = fx.label + ' · ' + fx.param
range.min = String(fx.min)
range.max = String(fx.max)
range.step = String(fx.step)
range.disabled = !usable
if (usable) range.value = String(st.value)
if (valEl) {
valEl.textContent = fmtValue(fx, st.value)
valEl.title = usable ? '' : '效果作用在「' + (S.layers.find(l => l.id === st.layerId) || {}).name + '」,切回该层可继续调整'
}
}
/** 唯一入口:应用一个效果(同层同效果再点 = 重置回默认参数,不叠加) */
export function applyQuickEffect(key) {
const fx = QUICK_EFFECTS[key]
if (!fx) return false
const layer = effectTarget()
if (!layer) { toast('没有可处理的图层'); return false }
if (layer.visible === false) {
toast('「' + layer.name + '」已隐藏,先显示再应用效果')
return false
}
let target = layer
if (!needsPixelSnapshot(layer)) target = rasterizeLayer(layer)
if (!target) { toast('栅格化失败,效果未应用'); return false }
const st = S.fx
// 同一层 + 同一效果:用户是在「回默认值」,不是要再糊一层
if (st.source && st.layerId === target.id && st.key === key) {
st.value = fx.def(target.canvas)
renderFromSource(target, key, st.value)
if (S.renderAll) S.renderAll()
toast('「' + fx.label + '」已重置为 ' + fmtValue(fx, st.value), 'success')
return true
}
saveSnapshot('效果:' + fx.label)
// 基准必须是「应用前」的像素:saveSnapshot 只写历史,不改画布,所以这里拍
S.fx = { key, layerId: target.id, source: snapshotCanvas(target.canvas), value: fx.def(target.canvas) }
renderFromSource(target, key, S.fx.value)
if (S.renderAll) S.renderAll()
toast('已应用「' + fx.label + '」' + fmtValue(fx, S.fx.value) + ' 到 ' + target.name + ' · 可拖强度微调', 'success')
return true
}
/**
* 拖动强度滑杆。不拍快照(历史粒度 = 一次效果操作),也不重建图层面板
* (拖动中每帧 innerHTML 会闪,缩略图交给松开后的 renderAll 刷新)。
*/
export function setEffectValue(value) {
const st = S.fx
if (!st.source) return false
const fx = QUICK_EFFECTS[st.key]
if (!fx) return false
const target = S.layers.find(l => l.id === st.layerId)
if (!target) return false
const layer = effectTarget()
// 目标层已切换:源像素属于别的层,拒绝写入
if (!layer || layer.id !== st.layerId) return false
const v = Math.min(fx.max, Math.max(fx.min, Number(value) || 0))
st.value = v
renderFromSource(target, st.key, v)
if (runtime.el) {
const valEl = runtime.el.querySelector('.iwb-editor-fx-adj-val')
if (valEl) valEl.textContent = fmtValue(fx, v)
}
return true
}
File diff suppressed because it is too large. Load diff
+357
View File
@@ -0,0 +1,357 @@
/* export.js - 单张输出管道(P4,随 P1 一起带上)
*
* 一次只产出一个结果:覆盖节点 / 新建节点 / 下载。不做队列、不默认双输出。
* 「电商 800×800 · ≤500KB」是可切换预设(用户 2026-11-04 裁定),
* 预设 / 格式 / 背景存宿主 ctx.settings,下次打开沿用。
*
* 与宿主接口不变:glue.js 仍只收 (blob|dataURL, mode)。
*/
'use strict'
import { S, runtime } from './state.js'
import { getCompositeCanvas } from './tools.js'
import { toast } from './commands.js'
export const DEFAULT_EXPORT = Object.freeze({
preset: 'original', // original | ecom800
format: 'png', // png | jpeg | webp
bg: 'transparent', // transparent | white
maxKB: 0, // 0 = 不限
size: 800 // 预设输出边长
})
const SETTINGS_KEY = {
preset: 'exportPreset', format: 'exportFormat', bg: 'exportBg',
maxKB: 'exportMaxKB', size: 'exportSize'
}
function settings() { return S.callbacks && S.callbacks.settings }
/** 实际输出背景:JPG 没有 alpha 通道,选「透明」也必须落白底。
* 整条输出链(画布、摘要、状态)统一读这里,避免「按钮显示透明、文件是白底」。 */
export function effectiveBg(o) {
o = o || S.exportOptions || DEFAULT_EXPORT
return (o.bg === 'white' || o.format === 'jpeg') ? 'white' : 'transparent'
}
/** 当前输出设置的派生签名:判断「上次输出」是否还代表现在这套设置 */
function exportSignature(o) {
o = o || S.exportOptions || DEFAULT_EXPORT
const ecom = o.preset === 'ecom800'
return [o.preset, o.format, ecom ? o.size : 'orig', effectiveBg(o), ecom ? o.maxKB : 0].join(':')
}
export function loadExportOptions() {
const st = settings()
const get = (k, d) => {
let v = d
if (st && typeof st.get === 'function') {
try { const got = st.get(SETTINGS_KEY[k]); if (got !== undefined && got !== null) v = got } catch (e) { /* ignore */ }
}
return v
}
const preset = get('preset', DEFAULT_EXPORT.preset) === 'ecom800' ? 'ecom800' : 'original'
const format = ['png', 'jpeg', 'webp'].indexOf(get('format', DEFAULT_EXPORT.format)) >= 0 ? get('format', DEFAULT_EXPORT.format) : 'png'
// 体积上限 / 边长只属于电商方图预设。原尺寸分支不继承上一次留下的限制,
// 否则宿主里残留的 exportMaxKB 会让「原尺寸」也偷偷降质。
// null 表示从未设置过(走默认 500),0 表示用户显式选了「不限」——两者必须区分。
const rawMax = get('maxKB', null)
const rawSize = get('size', null)
S.exportOptions = {
preset: preset,
format: format,
// JPG 下背景直接收敛到白底,状态本身自洽,不靠 UI 撒谎
bg: format === 'jpeg' ? 'white' : (get('bg', DEFAULT_EXPORT.bg) === 'white' ? 'white' : 'transparent'),
maxKB: preset === 'ecom800' ? (rawMax === null ? 500 : Math.max(0, Number(rawMax) || 0)) : 0,
size: Math.max(64, Number(rawSize === null ? 800 : rawSize) || 800)
}
renderExportUI()
}
export function setExportOption(key, value) {
if (!S.exportOptions) loadExportOptions()
const o = S.exportOptions
const st = settings()
const persist = (k, v) => {
if (st && typeof st.set === 'function') { try { st.set(SETTINGS_KEY[k], v) } catch (e) { /* ignore */ } }
}
if (key === 'preset') {
o.preset = value === 'ecom800' ? 'ecom800' : 'original'
o.maxKB = o.preset === 'ecom800' ? 500 : 0
persist('preset', o.preset)
// maxKB 必须一起写回:只改内存的话,下次打开会被旧的 exportMaxKB 让限制「复活」
persist('maxKB', o.maxKB)
} else if (key === 'format') {
o.format = ['png', 'jpeg', 'webp'].indexOf(value) >= 0 ? value : 'png'
persist('format', o.format)
if (o.format === 'jpeg' && o.bg !== 'white') {
o.bg = 'white'
persist('bg', 'white')
toast('JPG 不支持透明背景,已切换为白底', 'info')
}
} else if (key === 'bg') {
if (o.format === 'jpeg') { renderExportUI(); return } // 按钮已禁用,这里兜底
o.bg = value === 'white' ? 'white' : 'transparent'
persist('bg', o.bg)
} else if (key === 'maxKB') {
o.maxKB = Math.max(0, Number(value) || 0)
persist('maxKB', o.maxKB)
} else if (key === 'size') {
o.size = Math.max(64, Number(value) || 800)
persist('size', o.size)
}
renderExportUI()
}
/** 顶栏输出设置面板:按钮态 + 预设摘要(摘要必须反映「实际会输出什么」) */
export function renderExportUI() {
const o = S.exportOptions || DEFAULT_EXPORT
const root = runtime.el
if (!root) return
const ecom = o.preset === 'ecom800'
const jpg = o.format === 'jpeg'
root.querySelectorAll('[data-export-key]').forEach(btn => {
const on = String(o[btn.dataset.exportKey]) === String(btn.dataset.exportValue)
btn.classList.toggle('active', on)
btn.setAttribute('aria-pressed', String(on))
})
// JPG 无 alpha 通道:透明按钮禁用并给出原因,而不是留着高亮却悄悄输出白底
root.querySelectorAll('[data-export-key="bg"]').forEach(btn => {
const blocked = jpg && btn.dataset.exportValue === 'transparent'
btn.disabled = blocked
if (blocked) btn.title = 'JPG 不支持透明背景,已自动使用白底'
else btn.removeAttribute('title')
})
// 边长 / 体积上限只在电商方图预设下有意义
root.querySelectorAll('[data-export-when="ecom800"]').forEach(row => { row.hidden = !ecom })
const summary = root.querySelector('.iwb-editor-export-summary')
if (summary) {
const size = ecom ? (o.size + '×' + o.size) : ('原尺寸 ' + S.imgW + '×' + S.imgH)
const limit = ecom && o.maxKB ? (' · ≤' + o.maxKB + 'KB') : ''
const bg = effectiveBg(o) === 'white' ? '白底' : '透明'
// jpeg 的 MIME 名是 JPEG,但对用户就说 JPG
const fmt = o.format === 'jpeg' ? 'JPG' : o.format === 'webp' ? 'WebP' : 'PNG'
summary.textContent = size + ' · ' + fmt + ' · ' + bg + limit
}
// 「上次输出」只在当前这套设置确实产过结果时才报,否则会误导
const note = root.querySelector('.iwb-editor-export-note')
if (note) {
const le = S.lastExport
note.textContent = (le && le.signature === exportSignature(o))
? ('上次输出 ' + le.width + '×' + le.height + ' · ' + Math.max(1, Math.round(le.bytes / 1024)) + 'KB')
: '一次只输出一个结果;设置会记住'
}
}
/** 事件委托:输出设置面板(下拉容器常驻 DOM,展开由 CSS class 控制) */
export function bindExportUI() {
const root = runtime.el
if (!root) return
const panel = root.querySelector('.iwb-editor-export-settings')
const toggle = root.querySelector('[data-action="toggleExportSettings"]')
if (panel && panel.dataset.bound === '1') return
if (panel) panel.dataset.bound = '1'
if (toggle && panel) {
toggle.addEventListener('mousedown', (e) => e.stopPropagation())
toggle.addEventListener('click', (e) => {
e.stopPropagation()
const open = panel.classList.toggle('open')
toggle.setAttribute('aria-expanded', String(open))
})
}
if (panel) {
panel.addEventListener('mousedown', (e) => e.stopPropagation())
panel.addEventListener('click', (e) => {
const btn = e.target.closest('[data-export-key]')
if (!btn) return
e.stopPropagation()
let v = btn.dataset.exportValue
if (btn.dataset.exportKey === 'maxKB' || btn.dataset.exportKey === 'size') v = Number(v)
setExportOption(btn.dataset.exportKey, v)
})
}
}
/** 合成 → 尺寸/背景处理。返回结果画布(调用方负责释放) */
export function buildOutputCanvas() {
const o = S.exportOptions || DEFAULT_EXPORT
const white = effectiveBg(o) === 'white'
const src = getCompositeCanvas()
let out = src
if (o.preset === 'ecom800') {
const size = o.size
const c = document.createElement('canvas')
c.width = size
c.height = size
const cx = c.getContext('2d')
if (white) { cx.fillStyle = '#ffffff'; cx.fillRect(0, 0, size, size) }
const long = Math.max(S.imgW, S.imgH) || 1
const k = (size * 0.8) / long // 商品长边占比 80%(640px / 800px)
const w = S.imgW * k, h = S.imgH * k
cx.drawImage(src, (size - w) / 2, (size - h) / 2, w, h)
src.width = 0; src.height = 0
out = c
} else if (white) {
const c = document.createElement('canvas')
c.width = S.imgW
c.height = S.imgH
const cx = c.getContext('2d')
cx.fillStyle = '#ffffff'
cx.fillRect(0, 0, c.width, c.height)
cx.drawImage(src, 0, 0)
src.width = 0; src.height = 0
out = c
}
return out
}
function toBlob(canvas, mime, quality) {
return new Promise((resolve, reject) => {
try {
if (typeof canvas.toBlob !== 'function') { reject(new Error('当前环境不支持 toBlob')); return }
canvas.toBlob((blob) => {
if (blob) resolve(blob)
else {
try { resolve(dataUrlToBlob(canvas.toDataURL(mime, quality))) }
catch (e) { reject(e) }
}
}, mime, quality)
} catch (e) { reject(e) }
})
}
function dataUrlToBlob(dataUrl) {
const comma = dataUrl.indexOf(',')
const meta = dataUrl.slice(0, comma)
const bin = atob(dataUrl.slice(comma + 1))
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
return new Blob([bytes], { type: (/^data:([^;,]+)/.exec(meta) || [])[1] || 'image/png' })
}
/** 编码并按 ≤maxKB 迭代降质(jpeg/webp);PNG 无质量参数,明确提示而不是静默失败 */
export async function encodeOutput(canvas) {
const o = S.exportOptions || DEFAULT_EXPORT
const mime = o.format === 'jpeg' ? 'image/jpeg' : o.format === 'webp' ? 'image/webp' : 'image/png'
// ≤KB 只在电商方图预设下约束;「原尺寸 + 残留 maxKB」不应偷偷降质
const limit = (o.preset === 'ecom800' && o.maxKB > 0) ? o.maxKB * 1024 : 0
let blob = await toBlob(canvas, mime, 0.92)
if (limit && blob.size > limit) {
if (o.format === 'png') {
toast('PNG 无法降质:当前 ' + Math.round(blob.size / 1024) + 'KB,可切换 JPG/WebP 或缩小尺寸', 'warn')
} else {
let q = 0.82
for (let i = 0; i < 8 && blob.size > limit && q >= 0.3; i++) {
blob = await toBlob(canvas, mime, q)
q -= 0.09
}
if (blob.size > limit) toast('已尽力压缩,仍为 ' + Math.round(blob.size / 1024) + 'KB(目标 ≤' + o.maxKB + 'KB)', 'warn')
}
}
return blob
}
/** 发布前准备:返回 Blob + 体积信息,不碰宿主、不关闭编辑器 */
export async function prepareOutput() {
const canvas = buildOutputCanvas()
try {
const blob = await encodeOutput(canvas)
const o = S.exportOptions || DEFAULT_EXPORT
const info = {
bytes: blob.size,
width: canvas.width,
height: canvas.height,
format: o.format,
bg: effectiveBg(o),
preset: o.preset,
maxKB: o.preset === 'ecom800' ? o.maxKB : 0,
// 记下产出时用的设置指纹,UI 才能判断「上次输出」是否还代表当前设置
signature: exportSignature(o)
}
S.lastExport = info
return { blob, info }
} finally {
canvas.width = 0
canvas.height = 0
}
}
/** 下载:一次一个文件,用完立即 revoke blob URL */
export function downloadBlob(blob) {
const o = S.exportOptions || DEFAULT_EXPORT
const ext = o.format === 'jpeg' ? 'jpg' : o.format
const raw = (S.callbacks && S.callbacks.imageName) || 'image.png'
const name = String(raw).replace(/\.[^.]+$/, '') + '_edit.' + ext
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = name
document.body.appendChild(a)
a.click()
if (a.parentNode) a.parentNode.removeChild(a)
setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 2000)
toast('已下载 ' + name + '(' + Math.round(blob.size / 1024) + 'KB)', 'success')
}
/** 任意图片 blob → PNG blob(剪贴板对 image/png 支持最稳,体积在剪贴板里无所谓) */
async function toPngBlob(blob) {
// 优先 createImageBitmap:不经过 URL,绕开宿主 CSP 对 img-src 的限制
try {
if (typeof createImageBitmap === 'function') {
const bmp = await createImageBitmap(blob)
const c = document.createElement('canvas')
c.width = bmp.width
c.height = bmp.height
c.getContext('2d').drawImage(bmp, 0, 0)
if (typeof bmp.close === 'function') bmp.close()
const out = await new Promise(res => c.toBlob(b => res(b), 'image/png'))
c.width = 0
c.height = 0
if (out) return out
}
} catch (e) { /* 走 img 回退 */ }
return await new Promise((resolve) => {
const url = URL.createObjectURL(blob)
const img = new Image()
img.onload = () => {
const c = document.createElement('canvas')
c.width = img.naturalWidth
c.height = img.naturalHeight
c.getContext('2d').drawImage(img, 0, 0)
try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ }
c.toBlob(b => resolve(b || blob), 'image/png')
}
img.onerror = () => {
try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ }
resolve(blob)
}
img.src = url
})
}
/**
* 复制到系统剪贴板:运营场景最常用的一条路 —— 复制后直接粘进聊天窗口/小红书后台,
* 省掉「下载 → 再上传」。必须在用户手势里调用(浏览器要求),失败给可操作提示。
*/
export async function copyBlobToClipboard(blob) {
const nav = typeof navigator !== 'undefined' ? navigator : null
const CI = typeof window !== 'undefined' ? window.ClipboardItem : null
if (!nav || !nav.clipboard || typeof nav.clipboard.write !== 'function' || typeof CI !== 'function') {
toast('当前浏览器不支持复制图片,请用「导出」下载', 'warn')
return false
}
let png = blob
if (blob.type !== 'image/png') {
try { png = await toPngBlob(blob) } catch (e) { png = blob }
}
try {
await nav.clipboard.write([new CI({ 'image/png': png })])
toast('已复制到剪贴板(' + Math.round(png.size / 1024) + 'KB),可直接粘贴', 'success')
return true
} catch (e) {
toast('复制失败:' + ((e && e.message) || '浏览器拒绝了剪贴板写入') + ';可用「导出」下载', 'error')
return false
}
}
+111
View File
@@ -0,0 +1,111 @@
/* floating.js - 选区浮动操作条(便利版 UI 的核心)
*
* 它是纯视图:按钮只调用 commands.runCommand(),因此浮动条 / 右键菜单 / 快捷键
* 三条入口天然一致;日后用户体验后决定保留、换位置或移除,都不影响选区功能。
*
* DOM 元素由 dom.js 静态生成(.iwb-editor-sel-bar),本模块只负责绑定、定位与显隐。
*/
'use strict'
import { S, runtime } from './state.js'
import { runCommand, toast } from './commands.js'
import { hasSelection, selectionInfo } from './selection.js'
let contextMode = false
function bar() {
return runtime.el && runtime.el.querySelector('.iwb-editor-sel-bar')
}
/** 事件委托:所有 [data-sel-cmd] 走同一命令层 */
export function bindFloating() {
const el = bar()
if (!el || el.dataset.bound === '1') return
el.dataset.bound = '1'
el.addEventListener('mousedown', (e) => e.stopPropagation())
el.addEventListener('click', (e) => {
const btn = e.target.closest('[data-sel-cmd]')
if (!btn) return
e.stopPropagation()
runCommand(btn.dataset.selCmd)
contextMode = false
positionFloating()
})
}
/** 图片坐标 → canvas-wrap 内屏幕坐标 */
function imageToWrap(x, y) {
const stack = S.canvasStack.getBoundingClientRect()
const wrap = S.canvasWrap.getBoundingClientRect()
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
const pad = S.overlayPad || 0
return {
x: stack.left - wrap.left + (pad + x) * scale,
y: stack.top - wrap.top + (pad + y) * scale
}
}
/**
* 定位:默认贴在选区右下角外侧;靠边时自动翻到左侧/上方,始终留在工作区内。
* 蚂蚁线 rAF 每帧调用,因此缩放/平移时它会跟着选区走。
*/
export function positionFloating() {
const el = bar()
if (!el || !S.open) return
const active = hasSelection()
if (!active && !contextMode) { el.style.display = 'none'; return }
el.style.display = 'flex'
el.classList.toggle('as-menu', contextMode)
const wrapW = S.canvasWrap.clientWidth
const wrapH = S.canvasWrap.clientHeight
const bw = el.offsetWidth || 300
const bh = el.offsetHeight || 36
let left, top
if (contextMode && el.dataset.cx !== undefined) {
left = Number(el.dataset.cx)
top = Number(el.dataset.cy)
} else {
const b = S.selection.bbox
const p = imageToWrap(b.x + b.w, b.y + b.h)
left = p.x + 10
top = p.y + 8
if (left + bw > wrapW - 8) left = imageToWrap(b.x, b.y).x + (b.w * (S.fitW * S.zoom) / S.imgW) - bw
if (top + bh > wrapH - 8) top = imageToWrap(b.x, b.y).y - bh - 8
}
el.style.left = Math.max(8, Math.min(left, Math.max(8, wrapW - bw - 8))) + 'px'
el.style.top = Math.max(8, Math.min(top, Math.max(8, wrapH - bh - 8))) + 'px'
// 无选区时禁用「需要选区」的按钮(右键菜单里仍能看到「全选」)
el.querySelectorAll('[data-sel-cmd]').forEach(btn => {
const need = btn.dataset.needsSel === '1'
btn.disabled = need && !active
})
const info = el.querySelector('.iwb-editor-sel-info')
if (info) {
const s = selectionInfo()
info.textContent = s ? (s.w + '×' + s.h + (s.feather ? ' · 羽化 ' + s.feather : '')) : '未框选'
}
}
/** 右键菜单:同一条操作条,定位到鼠标处 */
export function showSelectionContext(e) {
const el = bar()
if (!el) return
const wrap = S.canvasWrap.getBoundingClientRect()
contextMode = true
el.dataset.cx = String(e.clientX - wrap.left)
el.dataset.cy = String(e.clientY - wrap.top)
positionFloating()
if (!hasSelection()) toast('右键菜单:可先「全选」,或框选后直接操作', 'info')
}
export function hideSelectionContext() {
if (!contextMode) return
contextMode = false
const el = bar()
if (el) el.classList.remove('as-menu')
positionFloating()
}
export function isSelectionContextOpen() { return contextMode }
+368
View File
@@ -0,0 +1,368 @@
/* history.js - 历史快照与撤销/重做
*
* v1.1:快照升级为「完整图层集合」——除了像素,还记录图层的类型、名称、z、
* image/sourceCanvas 引用等元数据。恢复时能删掉后来新增的层、重建被删掉的层,
* 于是「复制/剪切到新层」「还原原图」这类会改变图层数量的操作也能 Ctrl+Z。
* 快照只存在于会话内存里(ImageData / Image 引用都可以直接持有,不需要序列化)。
*
* 约定:快照端 needsPixelSnapshot() 与恢复端 restorePath() 共用 vendor/layer-logic.js,
* 两边判定必须一致,否则会出现「没拍却要读」的像素丢失。
*/
'use strict'
import { S } from './state.js'
import { clearOverlay, updateCropInfo } from './crop.js'
import { hideTextInput, renderObjects } from './objects.js'
import {
createLayerCanvas, purgeVectorCanvases, redrawBitmapLayer,
renderLayerPanel, reorderLayerCanvas, updateLayerCanvasStyles
} from './layers.js'
import { resizeWorkspace, setupCanvas } from './viewport.js'
import { updateAllUI } from './events.js'
import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/layer-logic.js'
import { toast } from './commands.js'
// ============ 历史快照(所有位图图层 + 矢量对象) ============
export const snapshotStats = { snapshots: 0, getImageDataCalls: 0, bytesWritten: 0 }
/**
* 矢量对象上挂着运行时 DOM 画布(_canvas / _ctx)。JSON 深拷贝会把 canvas
* 序列化成 {},撤销恢复后 reorderLayerCanvas() 就会拿 {} 去 insertBefore →
* "parameter 1 is not of type 'Node'"。快照必须把这些运行时字段剔干净。
*/
function cloneVectors(arr) {
return JSON.parse(JSON.stringify(arr || [], (key, value) => {
if (key === '_canvas' || key === '_ctx') return undefined
return value
}))
}
/**
* 捕获当前状态
* @param {{metaOnly?: boolean}} [opts]
* metaOnly=true:只取几何/矢量/图层元数据,用于拖拽结束时「有没有变化」的比对。
*/
export function snapshotState(opts) {
const metaOnly = !!(opts && opts.metaOnly)
const bitmaps = S.layers.map(layer => {
let data = null
if (!metaOnly && needsPixelSnapshot(layer)) {
try { data = layer.ctx.getImageData(0, 0, S.imgW, S.imgH) } catch (e) { /* ignore */ }
if (data) {
snapshotStats.getImageDataCalls++
snapshotStats.bytesWritten += data.data.byteLength
}
}
return {
id: layer.id,
data,
// ---- 图层重建所需元数据(v1.1)----
name: layer.name,
z: layer.z,
opacity: layer.opacity,
visible: layer.visible,
locked: !!layer.locked,
transformable: !!layer.transformable,
color: layer.color,
lineWidth: layer.lineWidth,
imageRef: layer.image || null,
sourceRef: layer.sourceCanvas || null,
sourceBox: layer._srcBox ? { ...layer._srcBox } : null,
x: layer.x, y: layer.y, w: layer.w, h: layer.h,
rotation: layer.rotation || 0
}
})
snapshotStats.snapshots++
return {
imgW: S.imgW,
imgH: S.imgH,
activeLayerId: S.activeLayerId,
bitmaps,
texts: cloneVectors(S.textLayers),
shapes: cloneVectors(S.shapeLayers),
layerOrder: S.layers.map(l => ({ id: l.id, name: l.name, z: l.z, opacity: l.opacity, visible: l.visible, locked: !!l.locked, x: l.x, y: l.y, w: l.w, h: l.h }))
}
}
export const HISTORY_MAX_ENTRIES = 50
export const HISTORY_MAX_BYTES = 128 * 1024 * 1024
const HISTORY_MIN_BYTES = 32 * 1024 * 1024
export function historyBudgetBytes() {
const px = (S.imgW || 0) * (S.imgH || 0) * 4
if (!px) return HISTORY_MAX_BYTES
return Math.min(HISTORY_MAX_BYTES, Math.max(HISTORY_MIN_BYTES, px * 4))
}
function stateBytes(state) {
let n = 0
if (state && state.bitmaps) {
for (const b of state.bitmaps) {
if (b.data && b.data.data) n += b.data.data.byteLength
}
}
if (state) {
n += state.texts ? JSON.stringify(state.texts).length * 2 : 0
n += state.shapes ? JSON.stringify(state.shapes).length * 2 : 0
}
return n
}
export function pushHistory(stack, state, label) {
state.__bytes = stateBytes(state)
if (label) state.__label = label
stack.push(state)
const budget = historyBudgetBytes()
let total = stack.reduce((sum, s) => sum + (s.__bytes || 0), 0)
while (stack.length > 1 && (stack.length > HISTORY_MAX_ENTRIES || total > budget)) {
total -= stack.shift().__bytes || 0
}
return state
}
/** 操作前调用:压入历史,清空重做栈 */
export function saveSnapshot(label) {
pushHistory(S.history, snapshotState(), label)
S.redoStack = []
}
/** 按快照元数据重建一个已被删除的位图图层 */
function recreateLayer(bm) {
const canvas = createLayerCanvas()
const ctx = canvas.getContext('2d', { willReadFrequently: true })
return {
id: bm.id,
name: bm.name || ('图层 ' + bm.id),
canvas,
ctx,
opacity: bm.opacity == null ? 1 : bm.opacity,
visible: bm.visible !== false,
locked: !!bm.locked,
transformable: !!bm.transformable,
color: bm.color,
lineWidth: bm.lineWidth,
image: bm.imageRef || null,
sourceCanvas: bm.sourceRef || null,
_srcBox: bm.sourceBox || null,
x: bm.x, y: bm.y, w: bm.w, h: bm.h,
rotation: bm.rotation || 0,
z: bm.z || 0
}
}
function releaseLayer(layer) {
try {
if (layer.canvas && layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas)
if (layer.canvas) { layer.canvas.width = 0; layer.canvas.height = 0 }
} catch (e) { /* 单个图层释放失败不阻断其余 */ }
}
/** 恢复到指定状态(含图层增删) */
function restoreState(state) {
// v1.2:裁剪也进历史链,所以快照的画布尺寸可能与当前不同,必须先把尺寸复位。
// 尺寸一变,现有图层对象的像素缓冲已被 resizeWorkspace 清空、几何元数据也失效,
// 直接「复用现有图层再 putImageData」会让走过 redraw 路径的图片层彻底丢内容;
// 因此全部释放、让下面的「按快照重建」分支统一重建(它会按 bm 的 imageRef/sourceRef
// 选择 redraw 还是 pixels)。
if (state.imgW && state.imgH && (state.imgW !== S.imgW || state.imgH !== S.imgH)) {
purgeVectorCanvases()
for (const l of S.layers) releaseLayer(l)
S.layers = []
resizeWorkspace(state.imgW, state.imgH)
}
purgeVectorCanvases()
for (const l of S.layers) l._bounds = undefined
const snaps = state.bitmaps || []
const want = new Set(snaps.map(b => b.id))
// ① 删掉「快照里没有」的层(撤销复制/粘贴/选区新层)
for (let i = S.layers.length - 1; i >= 0; i--) {
if (!want.has(S.layers[i].id)) {
releaseLayer(S.layers[i])
S.layers.splice(i, 1)
}
}
// ② 按快照顺序补齐/恢复
const ordered = []
for (const bm of snaps) {
let layer = S.layers.find(l => l.id === bm.id)
if (!layer) {
layer = recreateLayer(bm)
S.layers.push(layer)
if (bm.data) {
try { layer.ctx.putImageData(bm.data, 0, 0) } catch (e) { /* ignore */ }
} else if (restorePath(layer) === 'redraw') {
redrawBitmapLayer(layer)
}
} else {
layer.x = bm.x
layer.y = bm.y
layer.w = bm.w
layer.h = bm.h
layer.locked = !!bm.locked
layer.rotation = bm.rotation || 0
if (isDrawableLayer(layer)) {
layer._srcBox = null
layer.sourceCanvas = null
layer.rotation = 0
layer.x = 0
layer.y = 0
layer.w = S.imgW
layer.h = S.imgH
layer._bounds = undefined
}
if (restorePath(layer) === 'redraw') {
redrawBitmapLayer(layer)
} else if (bm.data) {
try {
layer.ctx.clearRect(0, 0, S.imgW, S.imgH)
layer.ctx.putImageData(bm.data, 0, 0)
} catch (e) { /* ignore */ }
}
}
ordered.push(layer)
}
S.layers = ordered
if (state.layerOrder) {
for (const meta of state.layerOrder) {
const layer = S.layers.find(l => l.id === meta.id)
if (layer) {
layer.name = meta.name
layer.z = meta.z
layer.opacity = meta.opacity == null ? 1 : meta.opacity
layer.visible = meta.visible !== false
}
}
}
if (!S.layers.some(l => l.id === S.activeLayerId)) S.activeLayerId = S.layers.length ? S.layers[S.layers.length - 1].id : null
if (state.activeLayerId && S.layers.some(l => l.id === state.activeLayerId)) S.activeLayerId = state.activeLayerId
S.zCounter = Math.max(S.zCounter, ...S.layers.map(l => l.z || 0), ...(state.texts || []).map(t => t.z || 0), ...(state.shapes || []).map(s => s.z || 0))
S.textLayers = cloneVectors(state.texts)
S.shapeLayers = cloneVectors(state.shapes)
S.selectedTextId = null
S.textDrag = null
S.selectedShapeId = null
S.shapeDrag = null
S.selectedLayerId = null
S.bitmapDrag = null
S.penPath = null
S.penEditId = null
S.layerMulti.length = 0
// 撤销不动选区:选区是「视图状态」,不是像素状态,避免 Ctrl+Z 后框消失还要重画
reorderLayerCanvas()
updateLayerCanvasStyles()
renderObjects()
renderLayerPanel()
updateCropInfo()
}
export function undo() {
if (S.placingImage) return
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return
if (S.history.length === 0) { toast('没有可撤销的操作'); return }
pushHistory(S.redoStack, snapshotState())
restoreState(S.history.pop())
if (S.onHistoryRestore) S.onHistoryRestore()
if (S.renderAll) S.renderAll()
}
export function redo() {
if (S.placingImage) return
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return
if (S.redoStack.length === 0) { toast('没有可重做的操作'); return }
pushHistory(S.history, snapshotState())
restoreState(S.redoStack.pop())
if (S.onHistoryRestore) S.onHistoryRestore()
if (S.renderAll) S.renderAll()
}
/**
* 还原原图(用户 2026-11-04 裁定):清空标注 = 全部还原到刚打开时的状态 ——
* 删掉所有非原图图层、清掉所有绘制/矢量、复位变换与选区,只留「原图」。
* 整步记一个快照,Ctrl+Z 可完整恢复(包括被删的粘贴层与图形)。
* 旧版 resetDraw() 只清像素、留下空白层且清空撤销栈,已废弃。
*/
export function restoreAll() {
if (!S.originalImage) return
const img = S.originalImage
const ow = img.naturalWidth || img.width
const oh = img.naturalHeight || img.height
const sizeChanged = ow !== S.imgW || oh !== S.imgH
// 裁剪会改变画布尺寸且(P2 之前)会清空历史,此路径无法用像素快照回退;
// 明确 toast 告知,不做「假的可撤销」。
if (sizeChanged) {
S.imgW = ow
S.imgH = oh
S.zoom = 1
setupCanvas(img)
S.history = []
S.redoStack = []
clearAllEditState()
updateAllUI()
// 尺寸变了就必须走统一重绘出口:输出摘要/状态栏读 S.imgW/imgH,
// clearAllEditState 只清选区不停止蚂蚁线 rAF(唯一停止点是 renderAll/clearMarquee)
if (S.renderAll) S.renderAll()
toast('已还原为原图(裁剪后的画布尺寸已复位)', 'success')
return
}
saveSnapshot('还原原图')
const base = S.layers.find(l => l.id === 'base')
for (const layer of S.layers) {
if (layer !== base) releaseLayer(layer)
}
if (base) {
base.ctx.clearRect(0, 0, S.imgW, S.imgH)
base.ctx.drawImage(img, 0, 0)
base.locked = true
base.visible = true
base.opacity = 1
base.z = 0
}
S.layers = base ? [base] : []
// 默认无画笔层(用户裁定),活动层回到原图;再画时 ensureWritableLayer 兜底建层
S.activeLayerId = base ? 'base' : null
S.zCounter = 1
clearAllEditState()
if (S.renderAll) S.renderAll()
renderLayerPanel()
hideTextInput()
toast('已还原为原图,Ctrl+Z 可撤销', 'success')
}
function clearAllEditState() {
S.textLayers = []
S.selectedTextId = null
S.textDrag = null
S.textEditingId = null
S.shapeLayers = []
S.selectedShapeId = null
S.shapeDrag = null
S.selectedLayerId = null
S.bitmapDrag = null
S.penPath = null
S.penEditId = null
S.layerMulti.length = 0
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
S.selection = null
S.marquee = null
S.lassoPts = null
S.pickerComposite = null
clearOverlay()
updateCropInfo()
reorderLayerCanvas()
updateLayerCanvasStyles()
renderObjects()
}
/** 兼容旧入口:清空标注按钮 / 更多菜单都指向 restoreAll */
export function resetDraw() { restoreAll() }
export function restoreOriginal() { restoreAll() }
+458
View File
@@ -0,0 +1,458 @@
/* IWB 图片编辑器 - 图层化裁剪与标注
* 独立模块,通过 window.__iwbEditor.open() 调用
* 接收 imageBase64,返回编辑后的 dataURL
*
* v2.0.0 特性:
* - 图层系统:位图图层动态管理(原图、画笔、导入图片),可调透明度、显隐、排序
* - 矢量对象(文字/形状)在图层面板中统一展示,z 序可调
* - 统一橡皮:一个橡皮擦除当前活跃位图图层,与画笔共用大小/透明度/软硬
* - 添加位图图层:支持导入新图片作为独立图层
* - 工具:选择 / 画笔 / 矩形 / 箭头 / 文字 / 橡皮 / 吸管 / 抓手 / 裁剪
*
* 分层架构:
* - bitmap layers: 每个位图图层一个 canvas(动态创建/排序),CSS opacity 控制透明度
* - textCanvas: 矢量对象层(文字+形状),共享一个 canvas
* - strokeCanvas: 笔划预览层(一笔结束后合成进活跃图层)
* - overlayCanvas: 选中框/裁剪遮罩/笔刷预览
*/
/* index.js - 模块组装与对外接口
* 汇总各子模块,承载「打开编辑器 / 关闭 / 复原 / 输出」生命周期,
* 并把 window.__iwbEditor = { open, close, __stats } 挂到全局(对外唯一接口)。
* 注意:entries/content.js 必须先 import 本文件再 import content.js。
* 顶层只允许声明与这次 window 赋值,不调用其它模块的函数(避免循环 TDZ)。
*/
'use strict'
import { S, runtime } from './state.js'
import { HISTORY_MAX_BYTES, HISTORY_MAX_ENTRIES, historyBudgetBytes, snapshotStats } from './history.js'
import { cancelImagePlacement } from './placement.js'
import { clearSelection, purgeVectorCanvases, renderLayerPanel } from './layers.js'
import { createEl, loadImage } from './dom.js'
import { renderObjects, hideTextInput, textBounds } from './objects.js'
import { setupCanvas } from './viewport.js'
import { resetOverlayTransform } from './scale.js'
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar, loadSideWidth, loadColorPopPinned } from './events.js'
import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js'
import { bindFloating, positionFloating, hideSelectionContext } from './floating.js'
import { renderFxPanel } from './effects.js'
import { adjustCacheSize, onHistoryRestore as onAdjustHistoryRestore, renderAdjustPanel, resetAdjustCache } from './adjust.js'
import { loadExportOptions, prepareOutput, downloadBlob, copyBlobToClipboard, bindExportUI, renderExportUI } from './export.js'
import { loadRecentColors } from './recent-colors.js'
import { toast } from './commands.js'
// ============ 打开编辑器 ============
export async function open(options) {
if (!options || !options.imageBase64) return
createEl()
S.callbacks = options
// 命令层 / 蚂蚁线的渲染出口走注入,避免新模块与 events.js 形成顶层求值循环
S.renderAll = renderAll
S.positionFloating = positionFloating
S.renderFxPanel = renderFxPanel
S.renderAdjustPanel = renderAdjustPanel
// 撤销/重做后调节参数必须归零(详见 adjust.js#onHistoryRestore 的注释)
S.onHistoryRestore = onAdjustHistoryRestore
try {
const img = await loadImage(options.imageBase64)
S.imgW = img.naturalWidth || img.width
S.imgH = img.naturalHeight || img.height
S.originalImage = img
runtime.el.style.display = 'flex'
S.open = true
S.zoom = 1
setupCanvas(img)
resetState()
updateAllUI()
registerSelectionCommands()
loadExportOptions()
loadRecentColors()
// v1.18:色板「钉住」状态也来自宿主 KV,和常用色/最近色一起恢复
loadColorPopPinned()
bindLiteUI()
bindFloating()
bindExportUI()
initPanels()
// 右栏宽度跟着用户上次拖的位置(v1.16);必须在 initPanels 之后——
// 侧栏收起时元素虽 display:none,写 CSS 变量仍然有效,下次展开直接生效
loadSideWidth()
renderAll()
} catch (e) {
console.error('[IWB编辑器] 打开失败:', e)
if (runtime.el) runtime.el.style.display = 'none'
if (options.onError) options.onError(e.message)
} finally {
// 源图字符串只在解码这一刻有用(loadImage 内已转 blob URL)。
// 不丢的话 S.callbacks 会在整个编辑会话持有整份 dataURL(4K ≈44MB),
// 打开失败路径更是会一直挂到下次打开才被覆盖。
options.imageBase64 = null
}
}
function resetState() {
purgeVectorCanvases()
S.history = []
S.redoStack = []
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
S.isDrawing = false
S.panning = false
S.tool = 'brush'
S.color = '#ff4444'
S.brushSize = 3
S.brushHardness = 100
S.brushOpacity = 1
S.prevTool = null
S.pickerComposite = null
S.rectFill = false
S.shapeLineWidth = 3
S.textSize = 32
S.cropConstraint = { type: 'free', ratio: 0, sizeW: 0, sizeH: 0 }
S.textLayers = []
S.selectedTextId = null
S.textDrag = null
S.textEditingId = null
S.shapeLayers = []
S.selectedShapeId = null
S.shapeDrag = null
S.penPath = null
S.penEditId = null
S.penDragPt = -1
S.penDragBase = null
S.penDragPending = null
// 编辑器 DOM 复用,重开时旧的位图选中 id 指向已删除的图层,必须清掉
S.selectedLayerId = null
S.bitmapDrag = null
// 跨会话残留:多选合并集合、悬停点、双击判定都会指向上一张图的图层
S.layerMulti.length = 0
S.hoverPos = null
S.lastClick = null
S.lastNameClick = null
S.altPicker = false
// 快速效果的基准像素属于上一张图,重开必须清掉(否则滑杆会往新图上写旧像素)
S.fx = { key: null, value: 0, layerId: null, source: null }
// 图片调节的基准像素同理,而且更致命:缓存 key 是图层 id,原图恒为 'base',
// 不清就一定命中上一张图的像素(v1.15.1 修「调新图变回旧图」)
resetAdjustCache()
S.zCounter = Math.max(S.layers.length - 1, 0)
S.placingImage = null
S.placingHandle = null
S.placingStart = null
const sizeToggle = runtime.el && runtime.el.querySelector('.iwb-editor-size-toggle')
if (sizeToggle) { sizeToggle.classList.remove('active'); sizeToggle.setAttribute('aria-pressed', 'false'); sizeToggle.textContent = '启用尺寸' }
// 重开时旧选区 / 蚂蚁线 / 浮动条不能残留
S.selection = null
S.marquee = null
S.lassoPts = null
S.interaction = 'idle'
S.lastExport = null
if (S._antFrame) { cancelAnimationFrame(S._antFrame); S._antFrame = 0 }
hideSelectionContext()
if (S.selectionCtx) renderSelection()
if (S.cursorCtx) {
S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0)
S.cursorCtx.clearRect(0, 0, S.cursorCtx.canvas.width, S.cursorCtx.canvas.height)
resetOverlayTransform(S.cursorCtx)
}
}
/** 命令层统一重绘出口:所有新操作的像素/UI/选区状态在这里对齐 */
function renderAll() {
if (!S.open || !runtime.el) return
renderObjects()
renderLayerPanel()
renderFxPanel()
// 调节面板跟着图层走:新建/切换/删除图层都要刷新 target 与滑块值
renderAdjustPanel()
renderOptionBar()
updateStatusbar()
renderExportUI()
renderSelection()
syncAnts()
positionFloating()
}
/** 侧栏开合:记住上次选择,窄窗口默认收起(画布优先) */
function initPanels() {
if (!runtime.el) return
const st = S.callbacks && S.callbacks.settings
let saved = false
if (st && typeof st.get === 'function') { try { saved = !!st.get('panelsCollapsed') } catch (e) { /* ignore */ } }
const auto = (window.innerWidth || 1440) < 1100
runtime.el.classList.toggle('panels-collapsed', saved || auto)
}
/**
* 关闭编辑器。reason:'cancel'(用户点退出)| 'done'(导出成功后关闭)。
* 必须先通知宿主再置空 S.callbacks —— glue.js 的 openEditor() 只在
* onResult / onError / onClose 三处结算,「退出」曾经没有任何回调,宿主
* Promise 永远悬挂;回调异常不能阻断后面的内存释放。
*/
export function close(reason) {
const callbacks = S.callbacks
try {
if (callbacks && typeof callbacks.onClose === 'function') callbacks.onClose(reason || 'cancel')
} catch (e) {
console.error('[IWB编辑器] onClose 回调异常:', e)
}
if (runtime.el) {
hideTextInput()
runtime.el.style.display = 'none'
}
releaseEditorMemory()
S.open = false
S.callbacks = null
S.placingImage = null
S.placingHandle = null
S.placingStart = null
S.penPath = null
S.textEditingId = null
clearSelection()
hideSelectionContext()
disposeSelection()
}
/**
* 关闭即释放(对齐宿主「内存里不放大图」的模型):
* 此前 close() 只把遮罩 display:none,历史快照(≤128MB 的全幅 ImageData)、
* 各全幅图层/overlay canvas 的像素缓冲、原图 Image 与 base64 全部继续驻留 ——
* 编辑一张 4K 图后即使退出,堆里仍挂着 ~100MB,直到下次打开编辑器才被重建顶掉。
* 释放后下次 open() 由 setupCanvas + resetState 全量重建,无状态残留依赖。
*/
function releaseEditorMemory() {
// 1) 撤销/重做栈:像素快照是最大头
S.history = []
S.redoStack = []
// 2) 原图引用与吸管合成缓存(各为一张全幅位图)
S.originalImage = null
S.pickerComposite = null
// 2b) 快速效果的基准像素:又一张全幅位图,不释放就白占一份图大小的内存
S.fx = { key: null, value: 0, layerId: null, source: null }
// 2c) 图片调节的基准像素与预览副本(两张全幅位图)+ 按 layer.id 的缓存 Map。
// 缓存必须清,否则下次打开新图时 'base' 会命中这份旧像素(v1.15.1)
resetAdjustCache()
// 3) 交互态复位:关闭后 window mouseup 等全局监听仍活着,靠标志位保证不落到绘制路径
S.isDrawing = false
S.panning = false
S.penDragPt = -1
S.penDragPending = null
S.placingImage = null
S.placingHandle = null
S.placingStart = null
// 4) 位图图层(含 sourceCanvas):置 0 释放像素缓冲并从 DOM 摘除;
// setupCanvas 依赖 S.layers 做清理,这里必须同步清空,避免下次打开残留旧 canvas
for (const layer of S.layers) {
try {
if (layer.sourceCanvas) { layer.sourceCanvas.width = 0; layer.sourceCanvas.height = 0 }
if (layer.canvas) {
if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas)
layer.canvas.width = 0
layer.canvas.height = 0
}
} catch (e) { /* 单个图层释放失败不阻断其余 */ }
}
S.layers = []
// 5) 工作 canvas:text / stroke / overlay(overlay 含 18% 交互边距,4K 图约 74MB)
for (const c of [S.textCanvas, S.strokeCanvas, S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) {
try { if (c) { c.width = 0; c.height = 0 } } catch (e) { /* ignore */ }
}
// 6) 矢量对象的画布缓存
purgeVectorCanvases()
}
// ============ 输出 ============
/**
* 导出:合成 → PNG 字节 → onResult(out, mode) → close()。
* 用 toBlob 而非 toDataURL —— 编码结果落在浏览器 Blob 存储(堆外),
* 省掉全幅 base64 字符串(4K 图约 44MB JS 堆驻留);onResult 收到 Blob 或 dataURL 均可。
*/
/**
* 单张输出:prepareOutput() 负责合成 → 尺寸/背景 → 编码(含 ≤500KB 降质)。
* 一次只产出一个结果;download 只下载、不关编辑器、不回写宿主节点。
*/
export async function exportResult(mode) {
if (S.placingImage) cancelImagePlacement()
try {
const { blob } = await prepareOutput()
if (mode === 'download') {
downloadBlob(blob)
// download 不关编辑器:必须走一次统一重绘,摘要的「上次输出 …KB」才会更新
if (S.renderAll) S.renderAll()
return
}
if (S.callbacks && S.callbacks.onResult) S.callbacks.onResult(blob, mode)
close('done')
} catch (e) {
console.error('[IWB编辑器] 导出失败:', e)
toast('导出失败:' + ((e && e.message) || '图片可能跨域'), 'error')
if (S.callbacks && S.callbacks.onError) S.callbacks.onError('导出失败:' + ((e && e.message) || '图片跨域'))
}
}
/** 复制当前结果为图片到系统剪贴板:不关编辑器、不写宿主节点 */
export async function copyResult() {
if (S.placingImage) cancelImagePlacement()
try {
const { blob } = await prepareOutput()
await copyBlobToClipboard(blob)
if (S.renderAll) S.renderAll() // 摘要里的「上次输出 …KB」要跟上
} catch (e) {
console.error('[IWB编辑器] 复制失败:', e)
toast('复制失败:' + ((e && e.message) || '图片可能跨域'), 'error')
}
}
// ============ 暴露接口 ============
/**
* 快照/历史开销观测口(性能回归与手测用):
* history / redo 当前栈深度与占用字节
* snapshots 快照次数
* getImageDataCalls 累计全幅像素读取次数(优化前后最直观的对比指标)
* bytesWritten 累计拍摄的像素字节数
*/
export const __stats = () => ({
history: S.history.length,
historyBytes: S.history.reduce((n, s) => n + (s.__bytes || 0), 0),
redo: S.redoStack.length,
redoBytes: S.redoStack.reduce((n, s) => n + (s.__bytes || 0), 0),
maxEntries: HISTORY_MAX_ENTRIES,
maxBytes: HISTORY_MAX_BYTES,
historyBudget: historyBudgetBytes(),
...snapshotStats
})
/** 开发/回归观测口:本地探针与真站 e2e 用它断言图层、选区与像素,不参与业务逻辑 */
const __debug = () => ({
open: S.open,
tool: S.tool,
color: S.color,
altPicker: !!S.altPicker,
doc: { w: S.imgW, h: S.imgH },
zoom: S.zoom,
fit: { w: Math.round(S.fitW || 0), h: Math.round(S.fitH || 0) },
layers: S.layers.map(l => ({
id: l.id, name: l.name, z: l.z, locked: !!l.locked, visible: l.visible !== false,
// 不透明度有两个面:数据字段(导出/合并用)与 CSS(屏幕上看到的),两者必须一致
opacity: l.opacity == null ? 1 : l.opacity,
cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || '1') : null
})),
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, strokeOn: s.strokeOn !== false, z: s.z, color: s.color, fillColor: s.fillColor || null, radius: s.radius || 0, x1: Math.round(s.x1 || 0), y1: Math.round(s.y1 || 0), x2: Math.round(s.x2 || 0), y2: Math.round(s.y2 || 0) })),
texts: S.textLayers.map(t => ({
id: t.id, text: t.text, x: t.x, y: t.y, fontSize: t.fontSize, color: t.color,
fontWeight: t.fontWeight, fontFamily: t.fontFamily, align: t.align, lineHeight: t.lineHeight,
strokeWidth: t.strokeWidth, strokeColor: t.strokeColor, bgFill: !!t.bgFill, bgColor: t.bgColor,
// 包围盒:吸附/多行/底色/描边的断言都靠它,和绘制共用同一套度量
box: (() => { const b = textBounds(t); return { x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h) } })()
})),
// 吸附参考线(拖动中才有)与最近使用颜色:交互回归用
guides: S.guides ? S.guides.map(g => ({ axis: g.axis, at: Math.round(g.at * 10) / 10 })) : [],
recentColors: (S.recentColors || []).slice(),
textDefaults: {
weight: S.textWeight, family: S.textFamily, align: S.textAlign, lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth, strokeColor: S.textStrokeColor,
bgFill: S.textBgFill, bgColor: S.textBgColor, bgAlpha: S.textBgAlpha
},
// 矢量图形颜色:fillColor=null 表示跟随描边色(回归要能断言这条语义)
shapeColors: { stroke: S.color, fill: S.shapeFillColor || null },
// 色板当前在调哪一格:stroke / fill / bg(文字上下文里 fill=描边、bg=底色)
colorTarget: S.colorTarget,
selectedShapeId: S.selectedShapeId,
// 光标所在的图片坐标(状态栏同源):换算问题的第一现场证据
lastPos: S.lastPos ? { x: Math.round(S.lastPos.x), y: Math.round(S.lastPos.y) } : null,
// 当前正在进行的拖拽类型:move 才是拖动本体,handle/rotate 说明点到了控制点
drag: S.shapeDrag ? ('shape:' + S.shapeDrag.mode + (S.shapeDrag.handle ? ':' + S.shapeDrag.handle : ''))
: S.textDrag ? ('text:' + S.textDrag.mode)
: S.bitmapDrag ? ('bitmap:' + S.bitmapDrag.mode + (S.bitmapDrag.handle ? ':' + S.bitmapDrag.handle : ''))
: null,
selectedTextId: S.selectedTextId,
penEditId: S.penEditId,
activeLayerId: S.activeLayerId,
selectedLayerId: S.selectedLayerId,
layerMulti: S.layerMulti.map(x => x.type + ':' + x.id),
selection: selectionInfo(),
toolOptions: {
brushSize: S.brushSize,
brushHardness: S.brushHardness,
brushOpacity: S.brushOpacity,
shapeLineWidth: S.shapeLineWidth,
textSize: S.textSize,
rectFill: S.rectFill,
penFill: S.penFill
},
history: S.history.length,
historyLabels: S.history.map(s => s.__label || ''),
redo: S.redoStack.length,
exportOptions: S.exportOptions ? { ...S.exportOptions } : null,
lastExport: S.lastExport ? { ...S.lastExport } : null,
// 快速效果的可重调状态:hasSource=false 表示还没点过效果(滑杆应置灰)
fx: { key: S.fx.key, value: S.fx.value, layerId: S.fx.layerId, hasSource: Boolean(S.fx.source) },
// v1.15 图片调节:params 是 11 项当前值,hasSource 决定面板是否可用
adjust: {
layerId: S.adjust ? S.adjust.layerId : null,
hasSource: Boolean(S.adjust && S.adjust.source),
params: S.adjust && S.adjust.params ? { ...S.adjust.params } : null
},
// 调节基准缓存条数:退出编辑器后必须是 0(否则下一张图会拿到上一张的像素)
adjustCacheSize: adjustCacheSize(),
interaction: S.interaction,
ants: !!S._antFrame,
view: S.viewX !== null ? [Math.round(S.viewX), Math.round(S.viewY)] : null,
// 图层整幅像素指纹(抽样校验和):断言「改强度后从基准重算」而不是叠加,
// 比逐点采样稳 —— 马赛克/模糊的差异散在整幅,单点可能刚好相同
layerHash: (id) => {
const l = S.layers.find(v => v.id === id)
if (!l || !l.ctx || !l.canvas) return 0
try {
const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data
let h = 2166136261
for (let i = 0; i < d.length; i += 97) {
h ^= d[i]
h = Math.imul(h, 16777619)
}
return h >>> 0
} catch (e) { return 0 }
},
// 非透明像素的平均色:断言效果是否落在预期值上(如反相 50% 必然趋近 128)
avgColor: (id) => {
const l = S.layers.find(v => v.id === id)
if (!l || !l.ctx || !l.canvas) return null
try {
const d = l.ctx.getImageData(0, 0, l.canvas.width, l.canvas.height).data
let r = 0, g = 0, b = 0, n = 0
for (let i = 0; i < d.length; i += 4) {
if (d[i + 3] < 200) continue
r += d[i]; g += d[i + 1]; b += d[i + 2]; n++
}
return n ? [Math.round(r / n), Math.round(g / n), Math.round(b / n), n] : null
} catch (e) { return null }
},
pixel: (id, x, y) => {
const l = S.layers.find(v => v.id === id)
if (!l || !l.ctx) return null
try { return Array.from(l.ctx.getImageData(Math.round(x), Math.round(y), 1, 1).data) } catch (e) { return null }
},
// 区域透明像素统计:断言「合并后两半都有内容」比逐点采样快一个量级
alphaIn: (id, x0, y0, x1, y1) => {
const l = S.layers.find(v => v.id === id)
if (!l || !l.ctx) return 0
try {
const w = Math.max(1, Math.round(x1 - x0))
const h = Math.max(1, Math.round(y1 - y0))
const d = l.ctx.getImageData(Math.round(x0), Math.round(y0), w, h).data
let n = 0
for (let i = 3; i < d.length; i += 4) if (d[i] > 0) n++
return n
} catch (e) { return 0 }
}
})
window.__iwbEditor = {
open,
close,
__stats,
__debug
}
File diff suppressed because it is too large. Load diff
+763
View File
@@ -0,0 +1,763 @@
/* objects.js - 文字、形状、钢笔与选择手柄
* 节:文字图层、形状图层、钢笔二次编辑、文字输入框。
* 矢量对象统一走 S.textLayers / S.shapeLayers 与 S.zCounter 排序,
* 渲染到 S.textCanvas(layers.js 负责它在图层栈里的位置)。
*/
'use strict'
import { S, runtime } from './state.js'
import { boxCorners, clamp, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js'
import { clearOverlay, drawCropPreview } from './crop.js'
import { drawBitmapSelection, drawVectorToCanvas, hitBitmapAt, removeVecCanvas, renderLayerPanel, reorderLayerCanvas } from './layers.js'
import { drawPlacementPreview } from './placement.js'
import { drawShape, setTool } from './tools.js'
import { saveSnapshot, snapshotState } from './history.js'
import { toast } from './commands.js'
import { renderOptionBar } from './events.js'
import { fontOf, fontStackOf, newTextStyle, textBox, weightOf } from './text.js'
import { drawGuides } from './snap.js'
import { isDrawableLayer } from '../vendor/layer-logic.js'
// ============ 文字图层 ============
/** 兼容旧调用点:TEXT_FONT(size) 返回粗体字体串;带样式的字体请用 text.js 的 fontOf(obj) */
export const TEXT_FONT = (size) => fontOf({ fontSize: size, fontWeight: 'bold' })
/** 文字包围盒:含多行、底色 padding 与描边外扩(单行时与旧实现完全一致) */
export function textBounds(t) {
return textBox(t)
}
export function getSelectedText() {
return S.textLayers.find(t => t.id === S.selectedTextId) || null
}
export function hitTextLayer(pos) {
for (let i = S.textLayers.length - 1; i >= 0; i--) {
const t = S.textLayers[i]
if (t.visible === false) continue
const b = textBounds(t)
const rot = t.rotation || 0
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]
if (lp[0] >= b.x - 2 && lp[0] <= b.x + b.w + 2 &&
lp[1] >= b.y - 2 && lp[1] <= b.y + b.h + 2) {
return t
}
}
return null
}
function textHandlePoints(t) {
const b = textBounds(t)
const rot = t.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const local = { nw: [b.x, b.y], ne: [b.x + b.w, b.y], sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h] }
const out = {}
for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot)
return out
}
export function hitTextHandle(pos) {
const t = getSelectedText()
if (!t) return null
const b = textBounds(t)
const rot = t.rotation || 0
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]
if (hitRotationHandle(lp, b)) return 'rotate'
const local = { nw: [b.x, b.y], ne: [b.x + b.w, b.y], sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h] }
const R = 12 / viewScale()
let best = null, bestDist = 1e9
for (const name in local) {
const dx = lp[0] - local[name][0], dy = lp[1] - local[name][1]
const d = dx * dx + dy * dy
if (d < R * R && d < bestDist) { bestDist = d; best = name }
}
return best
}
// ============ 形状图层 ============
export function shapeBounds(s) {
if (s.type === 'pen' && s.pts && s.pts.length) { const xs = s.pts.map(p => p.x), ys = s.pts.map(p => p.y), x = Math.min(...xs), y = Math.min(...ys); return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y } }
return { x: Math.min(s.x1, s.x2), y: Math.min(s.y1, s.y2), w: Math.abs(s.x2 - s.x1), h: Math.abs(s.y2 - s.y1) }
}
export function getSelectedShape() {
return S.shapeLayers.find(s => s.id === S.selectedShapeId) || null
}
function distToSeg(px, py, x1, y1, x2, y2) {
const dx = x2 - x1, dy = y2 - y1
const l2 = dx * dx + dy * dy
let t = l2 ? ((px - x1) * dx + (py - y1) * dy) / l2 : 0
t = clamp(t, 0, 1)
return Math.hypot(px - (x1 + t * dx), py - (y1 + t * dy))
}
function hitShapeObj(pos, s, includeInterior) {
if (s.visible === false) return false
if (s.rotation) {
const b = shapeBounds(s)
const lp = unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, s.rotation)
pos = { x: lp[0], y: lp[1] }
}
if (s.type === 'pen') { const pts = s.pts || []; for (let i = 1; i < pts.length; i++) if (distToSeg(pos.x, pos.y, pts[i-1].x, pts[i-1].y, pts[i].x, pts[i].y) <= Math.max(8 / viewScale(), s.lw)) return true; if (s.closed && pts.length > 2 && distToSeg(pos.x, pos.y, pts[pts.length-1].x, pts[pts.length-1].y, pts[0].x, pts[0].y) <= Math.max(8 / viewScale(), s.lw)) return true; if (!includeInterior) return false; const b = shapeBounds(s); return pos.x >= b.x && pos.x <= b.x + b.w && pos.y >= b.y && pos.y <= b.y + b.h }
if (s.type === 'circle') {
const b = shapeBounds(s)
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const rx = Math.max(0.5, b.w / 2), ry = Math.max(0.5, b.h / 2)
const nx = (pos.x - cx) / rx, ny = (pos.y - cy) / ry
const value = nx * nx + ny * ny
if (includeInterior || s.fill) return value <= 1
const edgeTolerance = Math.max(4 / viewScale(), s.lw / Math.min(rx, ry))
const outer = (1 + edgeTolerance) * (1 + edgeTolerance)
const inner = Math.max(0, 1 - edgeTolerance) * Math.max(0, 1 - edgeTolerance)
return value >= inner && value <= outer
}
if (s.type === 'rect') {
const b = shapeBounds(s)
const pad = Math.max(4, s.lw * 1.5)
const inOuter = pos.x >= b.x - pad && pos.x <= b.x + b.w + pad &&
pos.y >= b.y - pad && pos.y <= b.y + b.h + pad
if (!inOuter) return false
if (includeInterior || s.fill) return true
const inInner = pos.x >= b.x + pad && pos.x <= b.x + b.w - pad &&
pos.y >= b.y + pad && pos.y <= b.y + b.h - pad
return !inInner
}
return distToSeg(pos.x, pos.y, s.x1, s.y1, s.x2, s.y2) <= Math.max(8 / viewScale(), s.lw)
}
export function hitShapeLayer(pos, includeInterior) {
for (let i = S.shapeLayers.length - 1; i >= 0; i--) {
if (hitShapeObj(pos, S.shapeLayers[i], includeInterior)) return S.shapeLayers[i]
}
return null
}
/** 所有对象(文字 + 形状)按 z 升序排列 */
export function allObjects() {
const arr = S.textLayers.map(o => ({ kind: 'text', obj: o }))
.concat(S.shapeLayers.map(o => ({ kind: 'shape', obj: o })))
arr.sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0))
return arr
}
export function sortLayersByZ() {
const cmp = (a, b) => (a.z || 0) - (b.z || 0)
S.textLayers.sort(cmp)
S.shapeLayers.sort(cmp)
}
/** 图层顺序的唯一真源:位图 + 矢量对象,按 z 升序。
* 之前位图(S.layers)与矢量(allObjects)各自排序、z 由两套计数器分配,
* 导致粘贴图片与图形 z 撞车、面板与画布叠放顺序相反、排序按钮交换 z 无效。 */
export function layerUnits() {
const arr = S.layers.map(obj => ({ kind: 'bitmap', obj }))
.concat(S.textLayers.map(obj => ({ kind: 'text', obj })))
.concat(S.shapeLayers.map(obj => ({ kind: 'shape', obj })))
arr.sort((a, b) => (a.obj.z || 0) - (b.obj.z || 0))
return arr
}
/** 同一份列表按 z 降序(最上层在前):命中测试 / 图层面板共用 */
export function layerUnitsDesc() { return layerUnits().reverse() }
/** 重排后按索引重新分配连续 z,并同步 zCounter —— 杜绝重复 z */
export function assignLayerZ(units) {
units.forEach((u, i) => { u.obj.z = i })
S.zCounter = Math.max(S.zCounter, units.length - 1)
}
/** 选中态唯一入口:四个 id 一起写,杜绝「两个图层同时高亮 / 排序作用错对象」 */
export function selectUnit(kind, id) {
// 单选变了就退出「合并多选」:两套选择同时留着会让面板出现说不清的多个高亮
S.layerMulti.length = 0
S.selectedLayerId = kind === 'bitmap' ? id : null
S.selectedTextId = kind === 'text' ? id : null
S.selectedShapeId = kind === 'shape' ? id : null
S.textDrag = null
S.shapeDrag = null
S.bitmapDrag = null
// 选中态变了,选项栏要跟着换成该对象的参数(选择工具下改描边/实心/线宽/字号)
renderOptionBar()
}
/** 判定一个图层单元是否命中该点(位图用矩形/像素,矢量用包围盒/形状) */
export function hitUnit(unit, pos) {
const { kind, obj } = unit
if (!obj || obj.visible === false) return false
if (kind === 'bitmap') return obj.locked ? false : hitBitmapAt(obj, pos)
if (kind === 'text') {
const b = textBounds(obj)
const rot = obj.rotation || 0
const lp = rot ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, rot) : [pos.x, pos.y]
return lp[0] >= b.x - 2 && lp[0] <= b.x + b.w + 2 &&
lp[1] >= b.y - 2 && lp[1] <= b.y + b.h + 2
}
return hitShapeObj(pos, obj, true)
}
/** 命中测试唯一入口:位图与矢量放同一份 z 降序列表里比较,最上层优先 */
export function hitTopmost(pos) {
for (const unit of layerUnitsDesc()) if (hitUnit(unit, pos)) return unit
return null
}
/** 其它可见元素的包围盒(拖动吸附用):排除自己与原图底图(底图边界=画布边界,重复) */
export function otherObjectBoxes(exclude) {
const out = []
for (const unit of layerUnits()) {
const o = unit.obj
if (!o || o === exclude || o.id === 'base' || o.visible === false) continue
if (unit.kind === 'bitmap') {
if (isFinite(o.x) && isFinite(o.y) && o.w > 0 && o.h > 0) out.push({ x: o.x, y: o.y, w: o.w, h: o.h })
} else if (unit.kind === 'text') {
out.push(textBox(o))
} else {
out.push(shapeBounds(o))
}
}
return out
}
export function hitAnyObject(pos) {
for (const unit of layerUnitsDesc()) {
if (unit.kind === 'bitmap') continue
if (hitUnit(unit, pos)) return unit
}
return null
}
function getSelectedObject() {
const t = getSelectedText()
if (t) return { kind: 'text', obj: t }
const s = getSelectedShape()
if (s) return { kind: 'shape', obj: s }
return null
}
/** 图层顺序调整(置顶 / 上移 / 下移 / 置底)
* 旧实现靠「交换相邻两项的 z」:一旦两个图层 z 相同(粘贴图片用 S.layers.length、
* 矢量用 ++S.zCounter,必然撞车),交换后仍是同一个值 ⇒ 按钮看起来没反应;
* 置底还会算出 -1 被不透明原图盖住。现在改成统一列表重排 + 重新分配连续 z。 */
export function moveLayer(dir) {
let sel = getSelectedObject()
if (sel) { if (sel.obj.locked) return } else {
const layer = S.layers.find(l => l.id === S.selectedLayerId && l.id !== 'base' && !l.locked)
if (layer) sel = { kind: 'bitmap', obj: layer }
}
// 快捷键(Ctrl+]/[)与按钮共用此入口:没选中时给出可见反馈,不再无声失败
if (!sel) { toast('先在画布或图层面板选中要调整的元素', 'info'); return }
if (sel.obj.locked || sel.obj.id === 'base') return
const units = layerUnits()
// v1.13:不再把原图钉在最底层 —— 「置底」可以真的沉到原图下面(垫背景层的常见用法)。
// 原图行本身仍不可参与(上面已 return),避免把底图整层挪走。
const from = units.findIndex(u => u.obj === sel.obj)
if (from < 0) return
const min = 0
let to
if (dir === 'up') to = Math.min(from + 1, units.length - 1)
else if (dir === 'down') to = Math.max(from - 1, min)
else if (dir === 'top') to = units.length - 1
else if (dir === 'bottom') to = min
else return
if (to === from) return
saveSnapshot()
const [moved] = units.splice(from, 1)
units.splice(to, 0, moved)
assignLayerZ(units)
sortLayersByZ()
reorderLayerCanvas()
renderObjects()
renderLayerPanel()
}
/** PS: Alt+] / Alt+[ 向上/向下选择图层(位图与矢量同一份 z 列表)。
* 当前没有任何选中时:向上选最顶层、向下选最底层,让用户能用键盘从头开始遍历。 */
export function selectNeighborLayer(up) {
const units = layerUnits()
if (!units.length) return
const sel = getSelectedObject()
let cur = -1
if (sel) cur = units.findIndex(u => u.obj === sel.obj)
else if (S.selectedLayerId) cur = units.findIndex(u => u.kind === 'bitmap' && u.obj.id === S.selectedLayerId)
const idx = cur < 0
? (up ? units.length - 1 : 0)
: (up ? Math.min(cur + 1, units.length - 1) : Math.max(cur - 1, 0))
const u = units[idx]
if (!u) return
selectUnit(u.kind, u.obj.id)
renderLayerPanel()
}
function shapeHandlePoints(s) {
const b = shapeBounds(s)
if (s.type === 'pen') {
return Object.fromEntries((s.pts || []).map((p, i) => ['p' + i, [p.x, p.y]]))
}
if (s.type === 'arrow') {
return { start: [s.x1, s.y1], end: [s.x2, s.y2] }
}
return {
nw: [b.x, b.y], ne: [b.x + b.w, b.y],
sw: [b.x, b.y + b.h], se: [b.x + b.w, b.y + b.h],
n: [b.x + b.w / 2, b.y], s: [b.x + b.w / 2, b.y + b.h],
e: [b.x + b.w, b.y + b.h / 2], w: [b.x, b.y + b.h / 2]
}
}
/** 形状控制点的世界坐标(应用旋转后) */
function shapeHandleWorld(s) {
const b = shapeBounds(s)
const rot = s.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const local = shapeHandlePoints(s)
const out = {}
for (const k in local) out[k] = rotPt(local[k][0], local[k][1], cx, cy, rot)
return out
}
export function hitShapeHandle(pos) {
const s = getSelectedShape()
if (!s) return null
const b = shapeBounds(s)
const rot = s.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const lp = rot ? unrotPt(pos.x, pos.y, cx, cy, rot) : [pos.x, pos.y]
if (hitRotationHandle(lp, b)) return 'rotate'
const pts = shapeHandlePoints(s)
const offset = 8 / viewScale()
const R = 14 / viewScale()
let best = null, bestDist = 1e9
for (const name in pts) {
const px = pts[name][0] + (name.includes('w') ? -offset : name.includes('e') ? offset : 0)
const py = pts[name][1] + (name.includes('n') ? -offset : name.includes('s') ? offset : 0)
const dx = lp[0] - px, dy = lp[1] - py
const d = dx * dx + dy * dy
if (d < R * R && d < bestDist) { bestDist = d; best = name }
}
return best
}
export function applyShapeHandle(s, handle, pos) {
const b0 = shapeBounds(s)
const rot0 = s.rotation || 0
const c0x = b0.x + b0.w / 2, c0y = b0.y + b0.h / 2
if (handle === 'rotate') {
const st = S.shapeDrag && S.shapeDrag.start
const baseRot = (S.shapeDrag && S.shapeDrag.shape && (S.shapeDrag.shape.rotation || 0)) || 0
if (st) {
const a0 = Math.atan2(st.y - c0y, st.x - c0x)
const a1 = Math.atan2(pos.y - c0y, pos.x - c0x)
let deg = baseRot + (a1 - a0) * 180 / Math.PI
if (S._shiftDown) deg = Math.round(deg / 15) * 15
s.rotation = deg
}
return
}
const lp = rot0 ? unrotPt(pos.x, pos.y, c0x, c0y, rot0) : [pos.x, pos.y]
pos = { x: lp[0], y: lp[1] }
if (s.type === 'pen' && handle && handle[0] === 'p') {
const i = parseInt(handle.slice(1), 10)
if (s.pts && s.pts[i]) { s.pts[i].x = clamp(pos.x, 0, S.imgW); s.pts[i].y = clamp(pos.y, 0, S.imgH) }
return
}
if (s.type === 'arrow') {
if (handle === 'start') { s.x1 = clamp(pos.x, 0, S.imgW); s.y1 = clamp(pos.y, 0, S.imgH) }
else { s.x2 = clamp(pos.x, 0, S.imgW); s.y2 = clamp(pos.y, 0, S.imgH) }
return
}
const b = shapeBounds(s)
const offset = 8 / viewScale()
const adjusted = { x: pos.x - (handle.includes('w') ? -offset : handle.includes('e') ? offset : 0), y: pos.y - (handle.includes('n') ? -offset : handle.includes('s') ? offset : 0) }
let x1 = b.x, y1 = b.y, x2 = b.x + b.w, y2 = b.y + b.h
if (handle.includes('e')) x2 = Math.max(x1 + 2, adjusted.x)
if (handle.includes('s')) y2 = Math.max(y1 + 2, adjusted.y)
if (handle.includes('w')) x1 = Math.min(x2 - 2, adjusted.x)
if (handle.includes('n')) y1 = Math.min(y2 - 2, adjusted.y)
s.x1 = x1; s.y1 = y1; s.x2 = x2; s.y2 = y2
}
function drawPenPathPreview() {
const path = S.penPath
if (!path || !path.pts || !path.pts.length) return
const ctx = S.overlayCtx
const pts = path.pts.slice()
const first = pts[0]
const nearStart = path.preview && pts.length >= 3 && Math.hypot(path.preview.x - first.x, path.preview.y - first.y) <= Math.max(12 / viewScale(), S.shapeLineWidth * 1.5)
if (path.preview) pts.push(nearStart ? first : path.preview)
ctx.save()
ctx.strokeStyle = S.color
ctx.fillStyle = nearStart ? 'rgba(232, 167, 53, 0.18)' : 'transparent'
// 预览线宽 = 实际线宽(图片单位),不再除缩放,做到所见即所得
ctx.lineWidth = Math.max(1, S.shapeLineWidth)
ctx.setLineDash([8 / viewScale(), 5 / viewScale()])
ctx.beginPath()
ctx.moveTo(pts[0].x, pts[0].y)
for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y)
if (nearStart) { ctx.closePath(); ctx.fill() }
ctx.stroke()
ctx.setLineDash([])
for (let i = 0; i < path.pts.length; i++) {
const point = path.pts[i]
ctx.beginPath()
ctx.fillStyle = i === 0 && nearStart ? '#e8a735' : '#ffffff'
ctx.strokeStyle = S.color
ctx.arc(point.x, point.y, 6 / viewScale(), 0, Math.PI * 2)
ctx.fill(); ctx.stroke()
}
ctx.restore()
}
function drawShapeSelection(s) {
const octx = S.overlayCtx
const b = shapeBounds(s)
const rot = s.rotation || 0
octx.save()
octx.strokeStyle = '#e8a735'
octx.lineWidth = 1.5 / viewScale()
// v1.10:对象选中框用**实线**。虚线在 PS 语义里是「像素选区(蚂蚁线)」,
// 用户看到文字/图形外面一圈虚线会当成「莫名其妙多出来的选区」。
const corners = boxCorners(b.x, b.y, b.w, b.h, rot)
octx.beginPath()
octx.moveTo(corners[0][0], corners[0][1])
for (let i = 1; i < corners.length; i++) octx.lineTo(corners[i][0], corners[i][1])
octx.closePath()
octx.stroke()
const hs = 5.5 / viewScale()
octx.fillStyle = '#ffffff'
octx.strokeStyle = '#e8a735'
const pts = shapeHandleWorld(s)
for (const name in pts) {
octx.beginPath()
octx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2)
octx.fill()
octx.stroke()
}
octx.restore()
drawRotationHandles(octx, b, rot)
}
export function deleteSelectedShape() {
if (!S.selectedShapeId) return
const selected = getSelectedShape()
if (selected && selected.locked) return
saveSnapshot()
removeVecCanvas(selected)
S.shapeLayers = S.shapeLayers.filter(s => s.id !== S.selectedShapeId)
S.selectedShapeId = null
renderObjects()
}
/** 重绘对象层 + 选中态 */
export function renderObjects(tempShape) {
for (const { kind, obj } of allObjects()) drawVectorToCanvas(kind, obj)
reorderLayerCanvas()
clearOverlay()
// 吸附参考线:拖动中才有值,松手清空。画在 overlay 层,不参与合成与导出
drawGuides(S.overlayCtx, S.guides)
if (tempShape) drawShape(S.overlayCtx, tempShape)
if (S.tool === 'pen' && S.penPath && S.penPath.pts.length) drawPenPathPreview()
// 图片放置模式优先显示放置预览
if (S.placingImage) {
drawPlacementPreview()
return
}
const bitmapSelection = S.layers.find(l => l.id === S.selectedLayerId && (l.transformable || isDrawableLayer(l)))
if (bitmapSelection) drawBitmapSelection(bitmapSelection)
const sel = getSelectedText()
if (sel) {
const b = textBounds(sel)
const rot = sel.rotation || 0
const octx = S.overlayCtx
octx.save()
octx.strokeStyle = '#e8a735'
octx.lineWidth = 1.5 / viewScale()
// 同上:对象选中是实线(虚线只留给像素选区的蚂蚁线)
const corners = boxCorners(b.x - 2 / viewScale(), b.y - 2 / viewScale(), b.w + 4 / viewScale(), b.h + 4 / viewScale(), rot)
octx.beginPath()
octx.moveTo(corners[0][0], corners[0][1])
for (let i = 1; i < corners.length; i++) octx.lineTo(corners[i][0], corners[i][1])
octx.closePath()
octx.stroke()
const hs = 5.5 / viewScale()
octx.fillStyle = '#ffffff'
octx.strokeStyle = '#e8a735'
const pts = textHandlePoints(sel)
for (const name in pts) {
octx.beginPath()
octx.rect(pts[name][0] - hs, pts[name][1] - hs, hs * 2, hs * 2)
octx.fill()
octx.stroke()
}
octx.restore()
} else {
const sh = getSelectedShape()
if (sh) drawShapeSelection(sh)
}
const penShape = getPenEditingShape()
if (penShape) drawPenEditOverlay(penShape)
if (S.cropRect) drawCropPreview()
}
// ============ 钢笔二次编辑(移动/添加/删除节点) ============
export function getPenEditingShape() {
if (!S.penEditId) return null
return S.shapeLayers.find(sh => sh.id === S.penEditId && sh.type === 'pen') || null
}
export function beginPenEdit(shape) {
S.penEditId = shape.id
S.selectedShapeId = shape.id
S.selectedTextId = null
S.selectedLayerId = null
S.shapeDrag = null
S.penDragPt = -1
S.penDragBase = null
S.penDragPending = null
renderObjects()
renderLayerPanel()
}
export function exitPenEdit() {
S.penEditId = null
S.penDragPt = -1
S.penDragBase = null
S.penDragPending = null
renderObjects()
renderLayerPanel()
}
export function hitPenPoint(pos, shape, r) {
const pts = shape.pts || []
const b = shapeBounds(shape)
const lp = shape.rotation ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, shape.rotation) : [pos.x, pos.y]
for (let i = 0; i < pts.length; i++) {
if (Math.hypot(lp[0] - pts[i].x, lp[1] - pts[i].y) <= r) return i
}
return -1
}
export function hitPenEdgeInsert(pos, shape) {
const pts = shape.pts || []
const b = shapeBounds(shape)
const lp = shape.rotation ? unrotPt(pos.x, pos.y, b.x + b.w / 2, b.y + b.h / 2, shape.rotation) : [pos.x, pos.y]
const r = 12 / viewScale()
for (let i = 0; i < pts.length - 1; i++) {
if (distToSeg(lp[0], lp[1], pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y) <= r) return i
}
if (shape.closed && pts.length >= 3) {
if (distToSeg(lp[0], lp[1], pts[pts.length - 1].x, pts[pts.length - 1].y, pts[0].x, pts[0].y) <= r) return pts.length - 1
}
return -1
}
function drawPenEditOverlay(shape) {
const ctx = S.overlayCtx
const pts = shape.pts || []
const b = shapeBounds(shape)
const rot = shape.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const W = (p) => rotPt(p.x, p.y, cx, cy, rot)
const R = 7 / viewScale()
ctx.save()
ctx.lineWidth = 1.5 / viewScale()
const segments = []
for (let i = 0; i < pts.length - 1; i++) segments.push([pts[i], pts[i + 1]])
if (shape.closed && pts.length >= 3) segments.push([pts[pts.length - 1], pts[0]])
ctx.strokeStyle = '#e8a735'
for (const [a, bb] of segments) {
const wa = W(a), wb = W(bb)
const mx = (wa[0] + wb[0]) / 2, my = (wa[1] + wb[1]) / 2
ctx.beginPath()
ctx.arc(mx, my, 3 / viewScale(), 0, Math.PI * 2)
ctx.stroke()
}
for (let i = 0; i < pts.length; i++) {
const wp = W(pts[i])
ctx.beginPath()
ctx.rect(wp[0] - R / 2, wp[1] - R / 2, R, R)
ctx.fillStyle = '#ffffff'
ctx.strokeStyle = i === S.penDragPt ? '#ff8c00' : '#e8a735'
ctx.fill()
ctx.stroke()
}
ctx.restore()
}
// ============ 文字输入框 ============
export function showTextInput(x, y, layer) {
const input = runtime.el.querySelector('.iwb-editor-text-input')
const wrapRect = S.canvasWrap.getBoundingClientRect()
// 不能用 canvasStack 的矩形换算:stack 的尺寸是 (imgW + 2*overlayPad) * scale,
// 图片在 stack 内部还额外偏移了 pad*scale(图层 canvas 的 left/top)。
// 拿它算比例会偏小、又漏掉这段偏移,输入框就整体跑到点击点的左上方。
// textCanvas 与图层 canvas 同基准,矩形精确等于「图片显示区域」。
const box = (S.textCanvas || S.canvasStack).getBoundingClientRect()
const sx = S.imgW ? box.width / S.imgW : 1
const sy = S.imgH ? box.height / S.imgH : 1
// textarea 有 2px 边框 + 8/4px 内边距,反向抵消后「输入框里的字起点」正压在点击点上,
// 与提交后 drawTextObject 从 t.x/t.y 起画的位置完全一致(所见即所得)。
const INSET_X = 10
const INSET_Y = 6
input.style.left = (box.left - wrapRect.left + x * sx - INSET_X) + 'px'
input.style.top = (box.top - wrapRect.top + y * sy - INSET_Y) + 'px'
input.style.display = 'block'
if (layer) {
input.value = layer.text
S.textEditingId = layer.id
} else {
input.value = ''
S.textEditingId = null
}
// 输入时看到的字形要和提交后一致:字体族与字重跟随这段文字自己的样式
// (新建时跟随「下一段文字的默认值」)。字号仍按 CSS 的 14px —— 那是输入框的可读性取舍,
// 跟字体不同:字体不一致会让人以为「选错字体了」,字号不一致只是大小不同。
const styleSrc = layer || { fontFamily: S.textFamily, fontWeight: S.textWeight }
input.style.fontFamily = fontStackOf(styleSrc)
input.style.fontWeight = weightOf(styleSrc)
input.focus()
input.select()
input.dataset.x = x
input.dataset.y = y
// textarea 不会自己长高:先按内容撑开,否则多行文本会挤在一行里
input.style.height = 'auto'
input.style.height = Math.max(30, input.scrollHeight + 4) + 'px'
}
export function hideTextInput() {
const input = runtime.el.querySelector('.iwb-editor-text-input')
if (input) {
// 必须先 blur:只隐藏不清焦点的话,焦点还留在隐藏的 input 上,
// 之后按 Esc 会被 isTyping() 当成"正在输入文字"吞掉(清不掉选中态)
if (document.activeElement === input) input.blur()
input.style.display = 'none'
input.value = ''
}
S.textEditingId = null
}
export function commitTextInput() {
const input = runtime.el.querySelector('.iwb-editor-text-input')
if (!input || input.style.display === 'none') return false
const text = input.value.trim()
const x = parseFloat(input.dataset.x)
const y = parseFloat(input.dataset.y)
let committed = false
if (S.textEditingId) {
const t = S.textLayers.find(l => l.id === S.textEditingId)
if (t && t.locked) { hideTextInput(); return true }
if (t && text !== t.text) {
saveSnapshot()
if (text) {
t.text = text
} else {
removeVecCanvas(t)
S.textLayers = S.textLayers.filter(l => l.id !== t.id)
S.selectedTextId = null
}
renderObjects()
}
committed = true
} else if (text) {
saveSnapshot()
const layer = {
id: 't' + Date.now() + Math.floor(Math.random() * 1000),
x, y, text,
color: S.color,
fontSize: Math.max(8, S.textSize),
// 样式一次性随默认值落进对象:老对象没有这些字段,text.js 会各自回退到等价默认值
...newTextStyle({
fontWeight: S.textWeight, fontFamily: S.textFamily, align: S.textAlign, lineHeight: S.textLineHeight,
strokeWidth: S.textStrokeWidth, strokeColor: S.textStrokeColor,
bgFill: S.textBgFill, bgColor: S.textBgColor
}),
opacity: 1,
visible: true,
locked: false,
z: ++S.zCounter
}
S.textLayers.push(layer)
selectUnit('text', layer.id)
renderObjects()
committed = true
}
hideTextInput()
// 文字落成即回 V 并选中(用户 2026-11-05):输入完下一步通常是挪位置 / 改字号颜色。
// 必须延后一个微任务 —— setTool 第一行就是 commitTextInput(),同步调用会自我递归。
// 延后期间若又开了新输入框(在 T 下连续点着输入),就不要把工具抢走。
if (committed) {
const id = S.selectedTextId
queueMicrotask(() => {
if (S.tool !== 'text') return
const box = runtime.el && runtime.el.querySelector('.iwb-editor-text-input')
if (box && box.style.display !== 'none') return
setTool('select')
if (!id) return
selectUnit('text', id)
renderObjects()
renderLayerPanel()
})
}
return committed
}
export function deleteSelectedText() {
if (!S.selectedTextId) return
const selected = getSelectedText()
if (selected && selected.locked) return
saveSnapshot()
removeVecCanvas(selected)
S.textLayers = S.textLayers.filter(t => t.id !== S.selectedTextId)
S.selectedTextId = null
renderObjects()
}
export function beginTextRotate(pos) {
const t = getSelectedText()
if (!t || t.locked) return
const b = textBounds(t)
S.textDrag = {
mode: 'rotate',
rotation: t.rotation || 0,
cx: b.x + b.w / 2,
cy: b.y + b.h / 2,
startX0: pos.x,
startY0: pos.y,
pending: snapshotState()
}
}
export function beginTextScaleDrag(handle, pos) {
const t = getSelectedText()
if (!t || t.locked) return
const b = textBounds(t)
const rot = t.rotation || 0
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const anchors = {
se: [b.x, b.y],
ne: [b.x, b.y + b.h],
sw: [b.x + b.w, b.y],
nw: [b.x + b.w, b.y + b.h]
}
const a = rotPt(anchors[handle][0], anchors[handle][1], cx, cy, rot)
const anchor = { x: a[0], y: a[1] }
const dx = pos.x - anchor.x, dy = pos.y - anchor.y
S.textDrag = {
mode: 'scale',
anchor,
d0: Math.sqrt(dx * dx + dy * dy),
fontSize: t.fontSize,
pending: snapshotState()
}
}
export function beginShapeHandleDrag(handle, pos) {
const sh = getSelectedShape()
if (!sh || sh.locked) return
S.shapeDrag = {
mode: 'handle', handle,
start: pos,
shape: { ...sh },
pending: snapshotState()
}
}
+278
View File
@@ -0,0 +1,278 @@
/* placement.js - 导入图片的放置(先调大小/位置再确认)
* 节:图片放置(导入图片时先调整大小/位置)。
* 状态挂在 S.placingImage / placingHandle / placingStart 上,
* 确认后由 confirmImagePlacement 把图片落成新的位图图层(调 layers.js)。
*/
'use strict'
import { S } from './state.js'
import { boxCorners, drawRotationHandles, hitRotationHandle, rotPt, unrotPt } from './viewport.js'
import { viewScale } from './scale.js'
import { clearOverlay } from './crop.js'
import { createLayerCanvas, redrawBitmapLayer, renderLayerPanel, reorderLayerCanvas, setActiveLayer, updateLayerCanvasStyles } from './layers.js'
import { saveSnapshot } from './history.js'
import { updateCursor } from './events.js'
// ============ 图片放置(导入图片时先调整大小/位置) ============
/** 启动图片放置:默认尺寸为图片原大但不超过画布 50%,居中 */
export function startImagePlacement(img) {
const iw = img.naturalWidth || img.width
const ih = img.naturalHeight || img.height
// 默认大小:不超过画布宽高的 50%
const maxW = S.imgW * 0.5
const maxH = S.imgH * 0.5
const ratio = Math.min(maxW / iw, maxH / ih, 1)
let w = Math.round(iw * ratio)
let h = Math.round(ih * ratio)
if (w < 10) w = 10
if (h < 10) h = 10
// 居中
const x = Math.round((S.imgW - w) / 2)
const y = Math.round((S.imgH - h) / 2)
S.placingImage = { img, x, y, w, h, rotation: 0 }
S.placingHandle = null
S.placingStart = null
S.drawCanvasCursor('move')
drawPlacementPreview()
}
/** 图片参数 → 新位图图层(放置确认与「直接落层」共用) */
function commitImageAsLayer(img, x, y, w, h, rotation) {
const id = 'L' + Date.now() + Math.floor(Math.random() * 1000)
const canvas = createLayerCanvas()
const ctx = canvas.getContext('2d', { willReadFrequently: true })
ctx.clearRect(0, 0, S.imgW, S.imgH)
const layer = {
id,
name: '图层 ' + (S.layers.length + 1), image: img, x, y, w, h, rotation: rotation || 0, transformable: true,
canvas,
ctx,
opacity: 1,
visible: true,
locked: false,
// 与矢量对象 / 空白图层共用同一个 z 计数器(旧值 S.layers.length 会和 ++S.zCounter 撞车,
// 导致粘贴的截图与图形 z 相同:排序按钮交换 z 无效、命中测试选错对象)
z: ++S.zCounter
}
redrawBitmapLayer(layer)
saveSnapshot()
S.layers.push(layer)
reorderLayerCanvas()
setActiveLayer(id)
updateLayerCanvasStyles()
renderLayerPanel()
return layer
}
/** 确认图片放置:创建新位图图层并绘制图片 */
export function confirmImagePlacement() {
if (!S.placingImage) return
const { img, x, y, w, h } = S.placingImage
const placementRotation = S.placingImage.rotation || 0
S.placingImage = null
S.placingHandle = null
S.placingStart = null
clearOverlay()
commitImageAsLayer(img, x, y, w, h, placementRotation)
updateCursor()
}
/**
* 便利版:粘贴 / 导入图片一步落层,不再要求 Enter 二次确认。
* 默认原大但不超过画布 50%、居中;要调整大小/位置直接切选择工具拖手柄。
* 整步有快照,Ctrl+Z 可撤销,Esc 也能当作「后悔」的兜底。
*/
export function placeImageDirectly(img) {
const iw = img.naturalWidth || img.width
const ih = img.naturalHeight || img.height
const ratio = Math.min((S.imgW * 0.5) / iw, (S.imgH * 0.5) / ih, 1)
const w = Math.max(10, Math.round(iw * ratio))
const h = Math.max(10, Math.round(ih * ratio))
const layer = commitImageAsLayer(img, Math.round((S.imgW - w) / 2), Math.round((S.imgH - h) / 2), w, h, 0)
// 粘贴常发生在刚点过工具按钮之后;若焦点还停在按钮上,用户习惯性补按 Enter
// 会激活那个按钮(最坏情况是「还原原图」)。落层后主动把焦点还给画布。
try { if (document.activeElement && document.activeElement.blur) document.activeElement.blur() } catch (e) { /* ignore */ }
if (S.renderAll) S.renderAll()
return layer
}
/** 取消图片放置 */
export function cancelImagePlacement() {
S.placingImage = null
S.placingHandle = null
S.placingStart = null
clearOverlay()
updateCursor()
}
/** 放置预览:在 overlay 上画图片 + 手柄 */
export function drawPlacementPreview() {
if (!S.placingImage) return
const ctx = S.overlayCtx
const { img, x, y, w, h } = S.placingImage
const rot = S.placingImage.rotation || 0
const cx = x + w / 2, cy = y + h / 2
clearOverlay()
// 半透明遮罩
ctx.save()
ctx.fillStyle = 'rgba(0,0,0,0.35)'
ctx.fillRect(0, 0, S.imgW, S.imgH)
ctx.restore()
// 画图片(带旋转)
ctx.save()
ctx.translate(cx, cy)
if (rot) ctx.rotate(rot * Math.PI / 180)
ctx.translate(-cx, -cy)
ctx.drawImage(img, x, y, w, h)
ctx.restore()
// 选区边框(旋转后)
const corners = boxCorners(x, y, w, h, rot)
ctx.save()
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 2 / viewScale()
ctx.setLineDash([8 / viewScale(), 4 / viewScale()])
ctx.beginPath()
ctx.moveTo(corners[0][0], corners[0][1])
for (let i = 1; i < corners.length; i++) ctx.lineTo(corners[i][0], corners[i][1])
ctx.closePath()
ctx.stroke()
ctx.setLineDash([])
// 8 个缩放手柄(旋转后位置)
const hs = 5.5 / viewScale()
ctx.fillStyle = '#fff'
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 1.5 / viewScale()
const localPts = {
nw: [x, y], ne: [x + w, y],
sw: [x, y + h], se: [x + w, y + h],
n: [x + w / 2, y], s: [x + w / 2, y + h],
e: [x + w, y + h / 2], w: [x, y + h / 2]
}
for (const name in localPts) {
const ptp = rotPt(localPts[name][0], localPts[name][1], cx, cy, rot)
ctx.beginPath()
ctx.rect(ptp[0] - hs, ptp[1] - hs, hs * 2, hs * 2)
ctx.fill()
ctx.stroke()
}
ctx.restore()
// 四角外侧圆弧 = 旋转手柄
drawRotationHandles(ctx, { x, y, w, h }, rot)
// 提示文字
ctx.save()
ctx.font = 'bold ' + Math.round(14 / viewScale()) + 'px sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = 'top'
const hintText = '拖拽手柄调整大小 · 圆点=旋转 · Shift=等比/15°吸附 · Enter=确认 · Esc=取消'
const br = boxCorners(x, y, w, h, rot).reduce((acc, pt) => Math.max(acc, pt[1]), -Infinity)
const hintY = br + 10 / viewScale()
const tw = ctx.measureText(hintText).width
ctx.fillStyle = 'rgba(0,0,0,0.6)'
ctx.fillRect(cx - tw / 2 - 6 / viewScale(), hintY, tw + 12 / viewScale(), 22 / viewScale())
ctx.fillStyle = 'rgba(255,255,255,0.95)'
ctx.fillText(hintText, cx, hintY + 4 / viewScale())
ctx.restore()
}
export function hitPlacementHandle(pos) {
if (!S.placingImage) return null
const { x, y, w, h } = S.placingImage
const rot = S.placingImage.rotation || 0
const cx = x + w / 2, cy = y + h / 2
const lp = unrotPt(pos.x, pos.y, cx, cy, rot)
const R = 12 / viewScale()
// 四角外侧圆弧 = 旋转手柄
if (hitRotationHandle(lp, { x, y, w, h })) return 'rotate'
const pts = {
nw: [x, y], ne: [x + w, y],
sw: [x, y + h], se: [x + w, y + h],
n: [x + w / 2, y], s: [x + w / 2, y + h],
e: [x + w, y + h / 2], w: [x, y + h / 2]
}
let best = null, bestDist = 1e9
for (const name in pts) {
const dx = lp[0] - pts[name][0], dy = lp[1] - pts[name][1]
const d = dx * dx + dy * dy
if (d < R * R && d < bestDist) { bestDist = d; best = name }
}
return best
}
/** 检查是否在放置矩形内 */
export function insidePlacementRect(pos) {
if (!S.placingImage) return false
const { x, y, w, h } = S.placingImage
const rot = S.placingImage.rotation || 0
const cx = x + w / 2, cy = y + h / 2
const lp = unrotPt(pos.x, pos.y, cx, cy, rot)
return lp[0] >= x && lp[0] <= x + w && lp[1] >= y && lp[1] <= y + h
}
/** 放置手柄拖拽:根据手柄调整图片大小 */
export function resizePlacement(pos) {
if (!S.placingImage || !S.placingHandle || !S.placingStart) return
const { img } = S.placingImage
const s = S.placingStart
const iw = img.naturalWidth || img.width
const ih = img.naturalHeight || img.height
const aspect = iw / ih
const hh = S.placingHandle
if (hh === 'move') {
const dx = pos.x - s.mx
const dy = pos.y - s.my
S.placingImage.x = s.x + dx
S.placingImage.y = s.y + dy
return
}
if (hh === 'rotate') {
const rcx = s.x + s.w / 2, rcy = s.y + s.h / 2
const a0 = Math.atan2(s.my - rcy, s.mx - rcx)
const a1 = Math.atan2(pos.y - rcy, pos.x - rcx)
let deg = (s.rotation || 0) + (a1 - a0) * 180 / Math.PI
if (S._shiftDown) deg = Math.round(deg / 15) * 15
S.placingImage.rotation = deg
return
}
// 缩放:先反旋转到图片局部坐标系再计算
const loc = unrotPt(pos.x, pos.y, s.x + s.w / 2, s.y + s.h / 2, s.rotation || 0)
pos = { x: loc[0], y: loc[1] }
// 计算新矩形
let nx = s.x, ny = s.y, nw = s.w, nh = s.h
if (hh.includes('e')) nw = Math.max(10, pos.x - s.x)
if (hh.includes('s')) nh = Math.max(10, pos.y - s.y)
if (hh.includes('w')) { const r = s.x + s.w; nx = Math.min(pos.x, r - 10); nw = r - nx }
if (hh.includes('n')) { const b = s.y + s.h; ny = Math.min(pos.y, b - 10); nh = b - ny }
// Shift 键 = 等比缩放
if (S._shiftDown) {
if (nw / nh > aspect) {
if (hh.includes('n') || hh.includes('s')) {
nw = nh * aspect
if (hh.includes('w')) nx = s.x + s.w - nw
} else {
nh = nw / aspect
if (hh.includes('n')) ny = s.y + s.h - nh
}
} else {
if (hh.includes('e') || hh.includes('w')) {
nh = nw / aspect
if (hh.includes('n')) ny = s.y + s.h - nh
} else {
nw = nh * aspect
if (hh.includes('w')) nx = s.x + s.w - nw
}
}
}
S.placingImage.x = nx
S.placingImage.y = ny
S.placingImage.w = nw
S.placingImage.h = nh
}
@@ -0,0 +1,63 @@
/* recent-colors.js - 最近使用颜色(v1.9)
*
* 只依赖 state.js(叶子模块):tools.js 在改色时调用 rememberColor(),
* color pop 打开时 renderRecentColors() 把最近的色块铺出来。
* 持久化走宿主 ctx.settings(小 KV,不放像素,符合宿主存储约定)。
*/
'use strict'
import { S, runtime } from './state.js'
// v1.19:上限 6 → 16。色板弹层改成 8 列网格,16 个正好铺满两排
// (v1.18 为「更紧凑」收到 6,是因为当时只有一排的空间;吸管+色值移到头部后省出这一排)。
const MAX = 16
const KEY = 'recentColors'
function valid(hex) {
return /^#[0-9a-f]{6}$/i.test(String(hex || ''))
}
export function loadRecentColors() {
const st = S.callbacks && S.callbacks.settings
let list = []
if (st && typeof st.get === 'function') {
try {
const got = st.get(KEY)
if (Array.isArray(got)) list = got
} catch (e) { /* 宿主 KV 不可用就当没有 */ }
}
S.recentColors = list.filter(valid).map(c => String(c).toLowerCase()).slice(0, MAX)
renderRecentColors()
}
/** 记一个颜色:去重后置顶,最多 MAX 个 */
export function rememberColor(hex) {
if (!valid(hex)) return
const c = String(hex).toLowerCase()
if (S.recentColors && S.recentColors[0] === c) return // 已经是最新,别每次重排
const list = [c].concat((S.recentColors || []).filter(x => x !== c))
S.recentColors = list.slice(0, MAX)
const st = S.callbacks && S.callbacks.settings
if (st && typeof st.set === 'function') {
try { st.set(KEY, S.recentColors) } catch (e) { /* 存不下就只在本次会话用 */ }
}
renderRecentColors()
}
export function renderRecentColors() {
if (!runtime.el) return
const wraps = runtime.el.querySelectorAll('.iwb-editor-recent-colors')
if (!wraps.length) return
const list = S.recentColors || []
const html = list.map(c =>
`<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="${c}" style="background:${c}" title="最近使用 ${c}"></button>`
).join('')
wraps.forEach(wrap => {
wrap.innerHTML = html
wrap.hidden = !list.length
// 没有最近色时整组一起藏,否则下面留一块空白,看起来像没加载出来
const group = wrap.closest('.iwb-color-group')
if (group) group.hidden = !list.length
})
}
+49
View File
@@ -0,0 +1,49 @@
/* scale.js - 视图缩放换算(零依赖叶子模块,只读 S)
*
* 为什么单独成文件:这三个函数被 viewport / objects / layers / crop / selection /
* placement / events 共用,而 viewport 与 crop、objects、layers 之间存在**循环 import**。
* 把换算函数放在有循环的模块里,esbuild 打成 IIFE 后另一侧会拿到 undefined:
* 实测 clearOverlay 报 "resetOverlayTransform is not defined"(setupCanvas 调 clearOverlay,
* 此时 viewport 模块尚在求值中)。叶子模块没有反向依赖,任何时候都可用。
*/
'use strict'
import { S } from './state.js'
/**
* 视图缩放:**1 个图片像素 = 多少屏幕 CSS 像素**。
*
* ⚠️ 这不是 S.zoom。S.zoom 是「相对 fitW 的倍数」:图片适应窗口后 fitW ≠ imgW,
* 所以 zoom=1 时屏幕上每个图片像素只占 fitW/imgW 个 CSS 像素。
*
* 所有「屏幕上恒定大小」的界面元素(控制点、描边粗细、虚线间距、命中半径、
* 预览文字)都必须用 X / viewScale() 换算。直接写 X / S.zoom 会让实际屏幕尺寸
* 变成 X * fitW / imgW —— 只跟图片尺寸走、和缩放无关:
* 小图被放大铺满容器时 fitW/imgW 可达 4~8,控制点就会大得离谱;大图则缩成看不见。
*/
export function viewScale() {
return (S.imgW && S.fitW) ? (S.fitW * S.zoom) / S.imgW : 1
}
/**
* overlay 系列画布(选中框 / 蚂蚁线 / 笔刷环)的像素倍率。
*
* 这三张画布的像素缓冲原本就等于「图片尺寸 + padding」,CSS 再按 viewScale 拉伸显示。
* 小图被「适应窗口」放大 5~10 倍时缓冲严重不足,控制点、虚线全糊成一团发光点。
*
* 倍率只看适应窗口的基准比例(fitW / imgW,**不含 zoom**):拖动缩放不会改变它,
* 所以不会在缩放过程中反复重建 canvas。上限 4 是为内存 —— 缓冲面积按平方增长。
*/
export function overlayScale() {
const base = (S.imgW && S.fitW) ? S.fitW / S.imgW : 1
return Math.max(1, Math.min(4, base))
}
/** 把 ctx 重置到「图片坐标」基准:含 pad 偏移与 overlayScale 倍率。
* 清屏后必须用它恢复,否则后续绘制会按 1:1 铺到设备像素上、整体偏移。 */
export function resetOverlayTransform(cx) {
const k = overlayScale()
const pad = S.overlayPad || 0
cx.setTransform(k, 0, 0, k, pad * k, pad * k)
}
+444
View File
@@ -0,0 +1,444 @@
/* selection.js - 选区模型、蚂蚁线与像素命令(P1)
*
* 唯一真源:S.selection = { path, outlinePath, bbox, fillRule, feather, kind, inverted }
* path 图片坐标系的 Path2D,清除 / 复制 / 剪切 / 填充 / 限制画笔全部复用它
* outlinePath 只用于画蚂蚁线(反选时不应把整图外框也画成虚线)
* fillRule 'nonzero' | 'evenodd'(反选 = 整图矩形 + 原 path,evenodd 填充)
*
* 蚂蚁线画在独立的 selectionCanvas 上:renderObjects() 里那句 clearOverlay()
* 只清交互层,不会把选区擦掉,也不会反过来擦掉裁剪框/选中手柄。
* 掩膜只覆盖 bbox(+ 羽化边距),不做全幅 getImageData —— 4K 图下这是内存底线。
*/
'use strict'
import { S } from './state.js'
import { clamp, getPos } from './viewport.js'
import { resetOverlayTransform, viewScale } from './scale.js'
import { clearOverlay } from './crop.js'
import { defineCommand, runCommand, toast } from './commands.js'
import { createLayerCanvas, ensureWritableLayer, getActiveLayer, reorderLayerCanvas, setActiveLayer, updateLayerCanvasStyles } from './layers.js'
// ============ 状态查询 ============
export function hasSelection() { return !!(S.selection && S.selection.active) }
/** 供状态栏 / 浮动条显示 */
export function selectionInfo() {
if (!hasSelection()) return null
const b = S.selection.bbox
return { kind: S.selection.kind, x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h), feather: S.selection.feather || 0, inverted: !!S.selection.inverted }
}
// ============ 选区图层(独立 canvas) ============
/** 清 selectionCanvas(与 crop.js#clearOverlay 同一坐标基准,但互不干扰) */
function clearSelectionCanvas() {
const ctx = S.selectionCtx
if (!ctx) return
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
resetOverlayTransform(ctx)
}
export function clearCursorCanvas() {
const ctx = S.cursorCtx
if (!ctx) return
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
resetOverlayTransform(ctx)
}
/** 蚂蚁线:黑白两段错位的虚线,rAF 只重绘这一张小画布 */
export function renderSelection() {
if (!S.selectionCtx) return
clearSelectionCanvas()
const ctx = S.selectionCtx
const k = 1 / Math.max(viewScale(), 0.0001)
// 拉框 / 套索过程中:画预览,不画正式选区
if (S.marquee || (S.lassoPts && S.lassoPts.length > 1)) {
ctx.save()
ctx.lineWidth = 1.5 * k
ctx.strokeStyle = '#ffffff'
ctx.setLineDash([5 * k, 4 * k])
if (S.marquee) {
const b = marqueeBox()
if (S.selectionKind === 'ellipse') {
ctx.beginPath()
ctx.ellipse(b.x + b.w / 2, b.y + b.h / 2, Math.max(1, b.w / 2), Math.max(1, b.h / 2), 0, 0, Math.PI * 2)
ctx.stroke()
} else ctx.strokeRect(b.x, b.y, b.w, b.h)
} else {
ctx.beginPath()
ctx.moveTo(S.lassoPts[0].x, S.lassoPts[0].y)
for (let i = 1; i < S.lassoPts.length; i++) ctx.lineTo(S.lassoPts[i].x, S.lassoPts[i].y)
ctx.closePath()
ctx.stroke()
}
ctx.restore()
return
}
if (!hasSelection()) return
const p = S.selection.outlinePath || S.selection.path
ctx.save()
ctx.lineWidth = 1.4 * k
ctx.setLineDash([5 * k, 5 * k])
ctx.lineDashOffset = (S._antOffset || 0) * k
ctx.strokeStyle = 'rgba(0,0,0,0.85)'
ctx.stroke(p)
ctx.lineDashOffset = ((S._antOffset || 0) + 5) * k
ctx.strokeStyle = 'rgba(255,255,255,0.95)'
ctx.stroke(p)
ctx.restore()
}
/** 启动/停止蚂蚁线动画;同时每帧刷新浮动条位置(缩放/平移时跟着选区走) */
export function syncAnts() {
if (hasSelection() && S.open) {
if (!S._antFrame) {
const tick = () => {
S._antOffset = ((S._antOffset || 0) + 0.55) % 10
renderSelection()
if (S.positionFloating) S.positionFloating()
S._antFrame = requestAnimationFrame(tick)
}
S._antFrame = requestAnimationFrame(tick)
}
} else if (S._antFrame) {
cancelAnimationFrame(S._antFrame)
S._antFrame = 0
}
}
// ============ 建立选区 ============
function rectFromPoints(x0, y0, x1, y1) {
const x = Math.min(x0, x1), y = Math.min(y0, y1)
return { x, y, w: Math.abs(x1 - x0), h: Math.abs(y1 - y0) }
}
function pathForBox(b, kind) {
const p = new Path2D()
if (kind === 'ellipse') {
p.ellipse(b.x + b.w / 2, b.y + b.h / 2, Math.max(0.5, b.w / 2), Math.max(0.5, b.h / 2), 0, 0, Math.PI * 2)
} else p.rect(b.x, b.y, Math.max(0.5, b.w), Math.max(0.5, b.h))
return p
}
function pathForLasso(pts) {
const p = new Path2D()
if (!pts.length) return p
p.moveTo(pts[0].x, pts[0].y)
for (let i = 1; i < pts.length; i++) p.lineTo(pts[i].x, pts[i].y)
p.closePath()
return p
}
function bboxOfPoints(pts) {
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity
for (const p of pts) {
if (p.x < minX) minX = p.x
if (p.y < minY) minY = p.y
if (p.x > maxX) maxX = p.x
if (p.y > maxY) maxY = p.y
}
return { x: minX, y: minY, w: Math.max(0, maxX - minX), h: Math.max(0, maxY - minY) }
}
/** 用一条路径替换当前选区(纯视图操作,不进历史) */
function applyPath(kind, outlinePath, bbox, opts) {
const o = opts || {}
const feather = clamp(Number(S.selectionFeather) || 0, 0, 20)
const inverted = !!o.inverted
const path = new Path2D()
if (inverted) {
path.rect(0, 0, S.imgW, S.imgH)
path.addPath(outlinePath)
} else {
path.addPath(outlinePath)
}
// 建立像素选区即接管 Delete 语义:清掉矢量对象选中态,否则
// 「选中形状 → Ctrl+A → Delete」会走删对象分支,而不是清像素。
S.selectedTextId = null
S.selectedShapeId = null
S.selection = {
kind, path, outlinePath, bbox,
fillRule: inverted ? 'evenodd' : 'nonzero',
feather, inverted, active: true
}
S.marquee = null
S.lassoPts = null
S.interaction = 'idle'
if (S.renderAll) S.renderAll()
else renderSelection()
toast(inverted ? '已反选' : '选区 ' + Math.round(bbox.w) + '×' + Math.round(bbox.h), 'info')
}
export function clearMarquee() {
S.selection = null
S.marquee = null
S.lassoPts = null
S.interaction = 'idle'
renderSelection()
syncAnts()
if (S.renderAll) S.renderAll()
}
export function selectAll() {
const b = { x: 0, y: 0, w: S.imgW, h: S.imgH }
applyPath('rect', pathForBox(b, 'rect'), b)
}
export function invertSelection() {
if (!hasSelection()) { toast('先框出一个选区'); return }
applyPath(S.selection.kind, S.selection.outlinePath, S.selection.bbox, { inverted: !S.selection.inverted })
}
// ============ 鼠标交互(由 events.js 转发) ============
function marqueeBox() {
const m = S.marquee
return rectFromPoints(m.x0, m.y0, m.x1, m.y1)
}
export function beginMarquee(pos) {
S.selection = null
S.marquee = { x0: pos.x, y0: pos.y, x1: pos.x, y1: pos.y }
S.interaction = 'marquee'
S.isDrawing = true
renderSelection()
}
export function updateMarquee(pos) {
if (!S.marquee) return
S.marquee.x1 = pos.x
S.marquee.y1 = pos.y
renderSelection()
}
export function endMarquee() {
const m = S.marquee
if (!m) return
const b = marqueeBox()
S.marquee = null
S.isDrawing = false
S.interaction = 'idle'
if (b.w > 3 && b.h > 3) {
applyPath(S.selectionKind, pathForBox(b, S.selectionKind), b)
} else {
clearMarquee()
}
}
export function beginLasso(pos) {
S.selection = null
S.lassoPts = [{ x: pos.x, y: pos.y }]
S.interaction = 'lasso'
S.isDrawing = true
renderSelection()
}
export function updateLasso(pos) {
if (!S.lassoPts) return
const last = S.lassoPts[S.lassoPts.length - 1]
if (Math.hypot(pos.x - last.x, pos.y - last.y) < 2) return
S.lassoPts.push({ x: pos.x, y: pos.y })
renderSelection()
}
export function endLasso() {
const pts = S.lassoPts
if (!pts) return
S.lassoPts = null
S.isDrawing = false
S.interaction = 'idle'
if (pts.length > 2) {
const b = bboxOfPoints(pts)
if (b.w > 3 && b.h > 3) { applyPath('lasso', pathForLasso(pts), b); return }
}
clearMarquee()
}
// ============ 局部掩膜(羽化软边) ============
/**
* 掩膜必须覆盖的范围(整数基准,避免 tile 原点与平移量差 1px)。
* 反选的 path 是「整图矩形 + 原选区」,只按原 bbox 开 tile 会把 tile 之外
* 的反选区域整块丢掉 —— 填充走全幅 fill(path) 不受影响,于是 Delete/复制/剪切
* 只作用原 bbox,与填充互相矛盾。反选时扩成整幅,临时画布用完即弃。
*/
function maskExtent() {
const sel = S.selection
const b = sel.inverted ? { x: 0, y: 0, w: S.imgW, h: S.imgH } : sel.bbox
const x = Math.floor(b.x)
const y = Math.floor(b.y)
return {
x, y,
w: Math.max(1, Math.ceil(b.x + b.w) - x),
h: Math.max(1, Math.ceil(b.y + b.h) - y)
}
}
/**
* 返回覆盖 bbox 的 alpha 掩膜(局部 tile,不是全幅;反选时整幅)。
* feather>0 用 Canvas2D 原生 filter 模糊填充边缘,CSP 不限制。
*/
function buildMask() {
const sel = S.selection
const feather = sel.feather || 0
const pad = Math.ceil(feather * 2)
const e = maskExtent()
const w = e.w + pad * 2
const h = e.h + pad * 2
const c = document.createElement('canvas')
c.width = w
c.height = h
const cx = c.getContext('2d')
cx.save()
cx.translate(-e.x + pad, -e.y + pad)
if (feather > 0) cx.filter = 'blur(' + feather + 'px)'
cx.fillStyle = '#ffffff'
cx.fill(sel.path, sel.fillRule)
cx.restore()
return { canvas: c, x: e.x - pad, y: e.y - pad, w, h }
}
function writableLayer() {
const layer = getActiveLayer()
if (!layer || layer.locked) {
toast(layer && layer.locked ? '当前图层已锁定,请先解锁' : '没有可用的图层', 'warn')
return null
}
return layer
}
/** 清除当前图层在选区内的像素(用户裁定:Delete 只作用单层,不动其它层) */
function eraseOnActiveLayer() {
const layer = writableLayer()
if (!layer) return false
const mask = buildMask()
layer.ctx.save()
layer.ctx.globalCompositeOperation = 'destination-out'
layer.ctx.drawImage(mask.canvas, mask.x, mask.y)
layer.ctx.restore()
layer._bounds = undefined
S.pickerComposite = null
mask.canvas.width = 0
mask.canvas.height = 0
return true
}
/** 复制/剪切:按 bbox 做局部 tile,再生成一张全幅透明图层,原位置不变 */
function copyToLayer(cut) {
const layer = writableLayer()
if (!layer) return false
const mask = buildMask()
const tile = document.createElement('canvas')
tile.width = mask.w
tile.height = mask.h
const tctx = tile.getContext('2d')
// 把当前层按「全局坐标 → tile 局部坐标」对齐后取像素
tctx.drawImage(layer.canvas, -mask.x, -mask.y)
tctx.globalCompositeOperation = 'destination-in'
tctx.drawImage(mask.canvas, 0, 0)
const canvas = createLayerCanvas()
const ctx = canvas.getContext('2d', { willReadFrequently: true })
ctx.drawImage(tile, mask.x, mask.y)
const id = 'S' + Date.now() + Math.floor(Math.random() * 1000)
const fresh = {
id,
name: cut ? '剪切内容' : '选区副本',
canvas, ctx,
opacity: 1, visible: true, locked: false,
transformable: true,
x: 0, y: 0, w: S.imgW, h: S.imgH, rotation: 0,
z: ++S.zCounter
}
S.layers.push(fresh)
if (cut) eraseOnActiveLayer()
reorderLayerCanvas()
updateLayerCanvasStyles()
setActiveLayer(id)
for (const l of S.layers) l._bounds = undefined
tile.width = 0; tile.height = 0
mask.canvas.width = 0; mask.canvas.height = 0
S.pickerComposite = null
return true
}
/** 用当前前景色填充选区(只作用当前层)。
* 填充是「加内容」的操作:当前层锁定(默认只剩原图)时自动落「标注」层,
* 与画笔的兜底一致;Delete/剪切是「减内容」,保持提示不自动建层。 */
function fillOnActiveLayer() {
const layer = ensureWritableLayer()
if (!layer) return false
const sel = S.selection
layer.ctx.save()
if (sel.feather > 0) layer.ctx.filter = 'blur(' + sel.feather + 'px)'
layer.ctx.globalAlpha = S.brushOpacity
layer.ctx.fillStyle = S.color
layer.ctx.fill(sel.path, sel.fillRule)
layer.ctx.restore()
layer._bounds = undefined
S.pickerComposite = null
return true
}
// ============ 命令注册(浮动条 / 右键 / 快捷键共用) ============
// 显式在 open() 时注册,而不是模块顶层副作用:本模块与 commands.js / layers.js
// 处在同一个 ESM 循环里,顶层访问 COMMANDS 可能撞上未初始化的绑定。
let registered = false
export function registerSelectionCommands() {
if (registered) return
registered = true
defineCommand('sel.copy', {
label: '复制为新层', enabled: hasSelection, hint: '先框出一个选区',
run: () => { if (copyToLayer(false)) toast('已复制到新图层', 'success') }
})
defineCommand('sel.cut', {
label: '剪切到新层', enabled: hasSelection, hint: '先框出一个选区',
run: () => { if (copyToLayer(true)) toast('已剪切到新图层', 'success') }
})
defineCommand('sel.delete', {
label: '清除选区内容(当前层)', enabled: hasSelection, hint: '先框出一个选区',
run: () => { if (eraseOnActiveLayer()) toast('已清除当前层选区内容', 'success') }
})
defineCommand('sel.fill', {
label: '填充选区', enabled: hasSelection, hint: '先框出一个选区',
run: () => { if (fillOnActiveLayer()) toast('已填充', 'success') }
})
defineCommand('sel.invert', { label: '反选', view: true, run: invertSelection })
defineCommand('sel.all', { label: '全选', view: true, run: selectAll })
defineCommand('sel.none', { label: '取消选区', view: true, run: clearMarquee })
}
/** 给外部(快捷键/菜单)一行调用 */
export function runSelectionCommand(name) { return runCommand(name) }
/** 供 tools.js 限制画笔/橡皮(选区激活时只画在选区内) */
export function applySelectionClip(ctx) {
if (!hasSelection()) return false
ctx.clip(S.selection.path, S.selection.fillRule)
return true
}
/** 编辑器关闭时清理动画与临时画布 */
export function disposeSelection() {
if (S._antFrame) cancelAnimationFrame(S._antFrame)
S._antFrame = 0
S.selection = null
S.marquee = null
S.lassoPts = null
clearSelectionCanvas()
clearCursorCanvas()
clearOverlay()
}
/** 屏幕坐标 → 选区命中(右键菜单用) */
export function hitSelectionAtEvent(e) {
if (!hasSelection() || !S.selectionCtx) return false
const p = getPos(e)
try {
return S.selectionCtx.isPointInPath(S.selection.path, p.x, p.y, S.selection.fillRule)
} catch (err) { return false }
}
+94
View File
@@ -0,0 +1,94 @@
/* snap.js - 拖动吸附与参考线(v1.9)
*
* 只做两件事:算「要不要吸、吸多少」,以及把参考线画出来。
* 不碰对象的写入 —— 调用方拿到 dx/dy 自己应用到 x/y,再在 render 里画线。
* 这样位图、文字、形状三种拖动可以共用同一套吸附,不会各写一遍阈值。
*
* 吸附目标:画布中线/四边 + 其它可见元素的左/中/右与上/中/下。
* 阈值按屏幕像素给(6px),换算成图片像素后再比较 —— 否则放大图片时
* 吸附范围会跟着放大到几十像素,鼠标还没靠近就被拽走。
*/
'use strict'
import { S } from './state.js'
import { viewScale } from './scale.js'
/** 吸附触发距离(屏幕像素) */
export const SNAP_SCREEN_PX = 6
/** 参考线颜色:洋红,和选中框的橙色区分开 */
const GUIDE_COLOR = '#ff2d95'
function pushBox(targets, box) {
const x2 = box.x + box.w
const y2 = box.y + box.h
targets.x.push(box.x, box.x + box.w / 2, x2)
targets.y.push(box.y, box.y + box.h / 2, y2)
}
/** 在候选线里找「离得最近且不超过阈值」的那条,返回需要平移的量 */
function nearest(targets, sources, tol, axis) {
let best = null
for (let i = 0; i < targets.length; i++) {
for (let j = 0; j < sources.length; j++) {
const delta = targets[i] - sources[j]
const abs = Math.abs(delta)
if (abs > tol) continue
if (!best || abs < Math.abs(best.delta)) best = { delta: delta, at: targets[i], axis: axis }
}
}
return best
}
/**
* 计算吸附位移。
* @param {{x:number,y:number,w:number,h:number}} box 被拖元素的包围盒(已按指针位移算好,未吸附)
* @param {Array<{x:number,y:number,w:number,h:number}>} others 其它元素的包围盒
* @returns {{dx:number, dy:number, guides:Array}}
*/
export function snapMove(box, others) {
const tol = SNAP_SCREEN_PX / Math.max(0.02, viewScale())
const targets = { x: [0, S.imgW / 2, S.imgW], y: [0, S.imgH / 2, S.imgH] }
for (const o of others || []) {
if (!o || !isFinite(o.x) || !isFinite(o.y)) continue
pushBox(targets, o)
}
const sourcesX = [box.x, box.x + box.w / 2, box.x + box.w]
const sourcesY = [box.y, box.y + box.h / 2, box.y + box.h]
const gx = nearest(targets.x, sourcesX, tol, 'x')
const gy = nearest(targets.y, sourcesY, tol, 'y')
const guides = []
if (gx) guides.push(gx)
if (gy) guides.push(gy)
return { dx: gx ? gx.delta : 0, dy: gy ? gy.delta : 0, guides: guides }
}
/** 画参考线(贯穿整个画布 + overlay 外扩区,拖动时一眼看到对齐到哪) */
export function drawGuides(ctx, guides) {
if (!guides || !guides.length || !ctx) return
const scale = viewScale()
const pad = S.overlayPad || 0
ctx.save()
ctx.strokeStyle = GUIDE_COLOR
ctx.lineWidth = 1 / Math.max(0.02, scale)
ctx.setLineDash([6 / Math.max(0.02, scale), 4 / Math.max(0.02, scale)])
for (const g of guides) {
ctx.beginPath()
if (g.axis === 'x') {
ctx.moveTo(g.at, -pad)
ctx.lineTo(g.at, S.imgH + pad)
} else {
ctx.moveTo(-pad, g.at)
ctx.lineTo(S.imgW + pad, g.at)
}
ctx.stroke()
}
ctx.setLineDash([])
ctx.restore()
}
export function clearGuides() {
if (!S.guides) return
S.guides = null
}
+160
View File
@@ -0,0 +1,160 @@
/* state.js - 编辑器唯一状态所有者
* 持有 S(全局状态对象)、ZOOM_* 常量,以及 runtime(可变持有对象)。
* 约定:ES 模块 import 绑定不可重新赋值,所以编辑器根节点 el 不用
* `export let el`,而是放在 runtime.el 里,各模块统一读写 runtime.el。
* 本模块不 import 任何编辑器内部模块(保持叶子节点,避免循环 TDZ)。
*/
'use strict'
// text.js 是零依赖叶子模块,这里引它的默认值常量不会形成循环
import { TEXT_DEFAULTS } from './text.js'
export const ZOOM_MIN = 0.1
export const ZOOM_MAX = 10
export const ZOOM_STEP = 1.15
// ============ 状态 ============
export const S = {
open: false,
tool: 'brush',
color: '#ff4444',
brushSize: 3,
brushHardness: 100, // 画笔硬度 0~100:100=硬边描边,<100=径向渐变软边章
brushOpacity: 1, // 画笔透明度 0.05~1(一笔整体透明度,笔划内不叠加)
prevTool: null, // 吸管工具激活前的工具(取色后切回)
// 画布内最后一次悬停点(图片坐标):用 [ ] 调笔刷大小时要按这个点立刻重画笔刷环,
// 否则光标环会停在旧尺寸,直到用户再动一下鼠标才更新(v1.6)
hoverPos: null,
lastClick: null, // 上一次画布按下 {t,x,y}:自算双击用(dblclick 在画布上不可靠)
// 上一次点击图层名 {id,t}:图层面板重命名也走自算双击(点一下就会重绘面板,
// 浏览器不会在同一个节点上派发 dblclick)
lastNameClick: null,
altPicker: false, // 按住 Alt 的临时吸管(画笔/橡皮下),松开 Alt 回到原工具
pickerComposite: null, // 吸管取样用的合成画布缓存(切工具/画布变化时失效)
// v1.8 快速效果的「可重调」状态:source 是点效果那一刻的像素备份,
// 拖强度滑杆时一律从 source 重算,绝不在上一次结果上叠加(否则来回拖会越拖越糊)。
// layerId 用于判断源是否还对得上当前目标层:切层后滑杆自动置灰,切回即恢复。
fx: { key: null, value: 0, layerId: null, source: null },
// v1.15 图片调节:连续调色(曝光/对比度/白平衡…)。source 是原尺寸基准,
// previewCanvas 是它的降采样副本 —— 拖动滑杆用小的算(6.7ms),松手才用原图算(几十~上百 ms)。
// 两者都只做「输入」,结果永远从基准重算,不在上一次结果上叠加。
adjust: { layerId: null, source: null, previewCanvas: null, params: null },
rectFill: false, // 矩形/圆形是否实心填充
penFill: true, // 钢笔闭合路径是否实心填充(只对闭合路径有意义)
// v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细,
// 否则「调细画笔」会顺手把所有形状的描边一起改掉。
shapeLineWidth: 3, // 矩形/圆形/箭头/钢笔的描边粗细
// v1.17:默认是否画描边。关掉后形状只剩填充(「无描边」),
// 对象上另存 strokeOn,老对象没有这个字段一律视为有描边。
shapeStrokeOn: true,
shapeRadius: 0, // 矩形圆角半径 px(v1.9,仅 rect 有意义)
// v1.10:矢量图形的填充色。null = 跟随描边色(新画的就是「同色实心」,
// 换主色时整体跟着变),一旦单独选过填充色就固定下来(每形状自己存 fillColor)。
shapeFillColor: null,
// v1.11:工具栏色板当前在调哪个颜色。描边与填充是同一个控件上的两个槽,
// 色板(调色器 / 吸管 / 推荐色 / hex)按这个值决定写 S.color 还是 shapeFillColor,
// 否则「三个地方各调各的颜色」会一直存在。
colorTarget: 'stroke', // stroke | fill
// v1.18:色板弹层是否「钉住」。钉住后点画布/点别处都不收起,方便连着调几处颜色。
// 存宿主 KV(跨会话记住):钉过一次就一直钉着,下次打开仍生效。
colorPopPinned: false,
// v1.16:右侧栏宽度(px)。0 = 按默认值走,打开编辑器时从宿主 KV 恢复。
// 宽度统一落在 CSS 变量 --iwb-side-w 上,不再各条规则各写一个魔数。
sideWidth: 0,
textSize: 32, // 新建文字的字号 px
// ---- v1.9 文字样式:这套是「新建文字」的默认值,每段文字自己存一份 ----
textWeight: 'bold', // bold | normal | 900
textFamily: 'sans', // v1.14 字体预设 key:sans 黑体 | serif 宋体 | kai 楷体 | round 圆体
textAlign: 'left', // left | center | right(多行时各行按块宽对齐)
textLineHeight: 1.25, // 行高倍数(1.25 = 老版单行高度,勿随意改)
textStrokeWidth: TEXT_DEFAULTS.strokeWidth, // 描边宽度 px,0 = 无描边
textStrokeColor: TEXT_DEFAULTS.strokeColor,
textBgFill: TEXT_DEFAULTS.bgFill, // 底色块
textBgColor: TEXT_DEFAULTS.bgColor, // 中性近黑,不再是纯黑 #000000
textBgAlpha: TEXT_DEFAULTS.bgAlpha, // 底色透明度(色块按这个不透明度显示,所见即所得)
// 最近使用颜色(最多 6 个,存 ctx.settings,跨会话保留)
recentColors: [],
// 图层系统
layers: [], // 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }]
activeLayerId: null, // 当前活跃位图图层 ID(画笔/橡皮操作目标)
// 画布引用(动态创建的 canvas 元素)
canvasWrap: null,
canvasStack: null,
textCanvas: null,
strokeCanvas: null,
overlayCanvas: null,
textCtx: null,
strokeCtx: null,
overlayCtx: null,
isDrawing: false,
panning: false,
panStart: null,
startX: 0, startY: 0,
history: [],
redoStack: [],
cropRect: null,
cropHandle: null,
cropMoving: false,
moveStart: null,
cropConstraint: { type: 'free', ratio: 0, sizeW: 0, sizeH: 0 },
// 文字图层(独立对象,可选中/移动/缩放/再编辑)
textLayers: [], // [{ id, x, y, text, color, fontSize, opacity, visible, z }]
selectedTextId: null,
textDrag: null, // { mode:'move'|'scale', start:{x,y}, layer:{x,y}, fontSize, baseX }
textEditingId: null,
selectedLayerId: null, // 选择工具当前选中的可编辑位图图层
// 图层多选集合 [{id,type}](v1.6):只为「合并选中图层」服务,
// 不参与单选语义(selectedLayerId / selectedTextId 仍各管各的)。
layerMulti: [],
bitmapDrag: null, // { mode:'move'|'scale', handle, start, layer, pending }
// 形状图层(矩形/箭头,独立对象,可选中/移动/调手柄)
shapeLayers: [], // [{ id, type:'rect'|'arrow', x1,y1,x2,y2, color, lw, fill, opacity, visible, z }]
selectedShapeId: null,
shapeDrag: null, // { mode:'move'|'handle', handle, start:{x,y}, shape:{...}, pending }
penPath: null, // 钢笔绘制中的点序列与预览点
penEditId: null, // 钢笔二次编辑中的形状 id
penDragPt: -1, // 正在拖动的节点下标(-1=无)
penDragBase: null,
penDragPending: null,
zCounter: 0, // 全局 z 序计数器(文字与形状统一排序)
// 图片放置中状态(导入图片时先调整大小/位置再确认)
placingImage: null, // { img, x, y, w, h } 图片坐标
placingHandle: null, // 'move' | 'nw'|'ne'|'sw'|'se'|'n'|'s'|'e'|'w'
placingStart: null, // { mx, my, x, y, w, h }
imgW: 0, imgH: 0,
overlayPad: 0,
originalImage: null, // 打开时的原始图片,用于「复原」
fitW: 0, fitH: 0, // 适应容器时的基准显示尺寸
zoom: 1, // 缩放倍率(基于 fit)
viewX: null, // 画布平移位置(wrap 内 left;null = 居中显示)
viewY: null,
callbacks: null,
spaceDown: false,
_shiftDown: false,
_canvasEventsBound: false,
// ---- v1.1 选区 / 便利性 ----
selection: null, // { kind, path, bbox, feather, active, fillRule, outline }
marquee: null, // 拉框中的临时选区 { x0,y0,x1,y1,kind }
lassoPts: null, // 套索绘制中的点序列
selectionKind: 'rect', // 选区工具的形状:rect | ellipse
selectionFeather: 0, // 羽化 px(0~20)
selectionCanvas: null, // 蚂蚁线专用层(与 overlay 分离,互不擦除)
selectionCtx: null,
cursorCanvas: null, // 笔刷环专用层
cursorCtx: null,
_antFrame: 0, // 蚂蚁线 rAF 句柄
_antOffset: 0,
exportOptions: null, // { preset, format, bg, maxKB, size },来自 ctx.settings
interaction: 'idle', // 轻量交互状态机:idle | marquee | lasso | placing | cropping
renderAll: null, // 由 index.js 注入的统一重绘出口
// 撤销/重做后由 history.js 调用:调节基准与参数必须跟着历史走,
// 否则「撤销把像素还原了、滑杆还显示 +80」—— 参数与画面对不上,再拖一次就叠加。
// 用回调而不是直接 import,避免 history ↔ adjust 循环依赖。
onHistoryRestore: null,
guides: null, // 拖动吸附参考线(图片坐标,松手清空):[{axis:'x'|'y', at, from, to}]
lastExport: null // 观测口:{ bytes, width, height, format, preset }
}
export const runtime = { el: null }
+224
View File
@@ -0,0 +1,224 @@
/* text.js - 文字的字体串、度量与绘制(v1.9)
*
* 为什么单独一个模块:文字要在两处画 —— 落层(layers.js#drawVectorToCanvas)与
* 预览/度量(objects.js)。两边各写一遍必然出现「量出来的框和画出来的字不一样」。
* 这里做成零依赖叶子模块(不 import 任何编辑器模块),objects.js 与 layers.js
* 都只往下依赖它,不会形成循环 import(esbuild 打成 IIFE 时循环 import 会拿到 undefined)。
*
* 坐标语义(与 v1.8 之前保持一致,勿随意改动):
* t.x / t.y 是「文字块」左上角;底色 padding 与描边从这一点向内/外扩展。
* 单行 + 无底色 + 无描边时,textBox() 与老版 textBounds() 完全相等(w=文字宽,h=fontSize×1.25)。
*/
'use strict'
/** 默认行高倍数:必须等于老版的 fontSize×1.25,否则单行文字的选中框会变高 */
export const TEXT_LINE_HEIGHT = 1.25
/**
* 文字默认样式:**唯一的真相源**。
* 以前 '#ff4444' / '#ffffff' / '#000000' / 0.68 散落在 state.js、text.js、
* events.js 三处,改一处另两处不跟,界面上就会出现「同一个概念三种颜色」——
* 用户实测反馈「字体颜色有 3 个位置,那个黑色应该换成默认的参数」正是这么来的。
* 底色默认也不再是纯黑 #000000:纯黑在深色/花色底图上像抠了个洞,
* 而且和「文字色」看起来像是同一件事。改成中性近黑 #101014 + 68% 透明。
*/
export const TEXT_DEFAULTS = {
color: '#ff4444',
strokeWidth: 0,
strokeColor: '#ffffff',
bgFill: false,
bgColor: '#101014',
bgAlpha: 0.68
}
/** 底色块相对字号的 padding 系数 */
const BG_PAD_RATIO = 0.3
let _measureCtx = null
/** 度量用的离屏 ctx:不依赖编辑器 DOM 是否已建好,避免 textBounds 在早期调用时抛错 */
function measureCtx() {
if (!_measureCtx) {
const c = document.createElement('canvas')
c.width = 8
c.height = 8
_measureCtx = c.getContext('2d')
}
return _measureCtx
}
/** 字重:'bold' | 'normal' | '900' …(默认粗体,与老版一致) */
export function weightOf(t) {
const w = t && t.fontWeight
return w == null || w === '' ? 'bold' : String(w)
}
/**
* 字体预设(v1.14):key → { label, stack }。
*
* 为什么只做「系统字体族」而不是内置字体文件:
* 1. 宿主 CSP 是 `default-src 'self'`,font-src 回落它,第三方字体 CDN 会被浏览器直接拦;
* 2. 中文字体动辄 2–64MB(本机宋体 2.3MB / 楷体 2.2MB / 苹方全字重 64MB),
* 插件产物现在才 389KB,内联等于体积涨 5–150 倍;
* 3. 系统字体同步可用,没有「字体没加载完就 measureText」导致框和字错位的时序问题。
* 每个 stack 都是跨平台候选队列:macOS 先命中苹方/宋体,Windows 命中雅黑/宋体,
* 全不命中时退到通用的 sans-serif / serif —— 永远不会渲染失败。
*
* 注意:中文是全角等宽,换字体不改字宽(实测 10 字 48px 在 6 种字体下都是 480px),
* 所以切换不会引起版面跳动;只有拉丁字母和数字会伸缩。
*/
export const TEXT_FONTS = {
sans: {
label: '黑体',
stack: '"PingFang SC", "Microsoft YaHei", "Heiti SC", "Hiragino Sans GB", "Source Han Sans SC", "Noto Sans SC", sans-serif'
},
serif: {
label: '宋体',
stack: '"Songti SC", "SimSun", "STSong", "Source Han Serif SC", "Noto Serif SC", serif'
},
kai: {
label: '楷体',
stack: '"Kaiti SC", "KaiTi", "STKaiti", "AR PL UKai CN", "Noto Serif SC", serif'
},
round: {
label: '圆体',
stack: '"Yuanti SC", "YouYuan", "STYuanti", "PingFang SC", sans-serif'
}
}
export const TEXT_FONT_KEYS = ['sans', 'serif', 'kai', 'round']
export const TEXT_FONT_DEFAULT = 'sans'
/** 把任意输入收敛成已知的字体 key:老对象没有 fontFamily、或存了脏值,都回退到默认 */
export function fontKeyOf(t) {
const k = t && t.fontFamily
return TEXT_FONTS[k] ? k : TEXT_FONT_DEFAULT
}
/** 字体栈串(不含字号字重),选项栏下拉与预览都用它 */
export function fontStackOf(t) {
return TEXT_FONTS[fontKeyOf(t)].stack
}
export function fontOf(t) {
const size = Math.max(4, Number(t && t.fontSize) || 32)
return weightOf(t) + ' ' + size + 'px ' + fontStackOf(t)
}
/** 文字的排布度量:分行、每行宽度、行高、底色 padding、描边宽度 */
export function textMetrics(t) {
const ctx = measureCtx()
const font = fontOf(t)
ctx.font = font
const raw = (t && t.text) == null ? '' : String(t.text)
const lines = raw.split('\n')
const widths = lines.map(line => ctx.measureText(line).width)
const size = Math.max(4, Number(t && t.fontSize) || 32)
const lh = size * (Number(t && t.lineHeight) || TEXT_LINE_HEIGHT)
const w = lines.length ? Math.max.apply(null, widths) : 0
const pad = t && t.bgFill ? Math.round(size * BG_PAD_RATIO) : 0
const sw = Math.max(0, Number(t && t.strokeWidth) || 0)
return { lines, widths, w, h: lh * lines.length, lh, pad, sw, font, size }
}
/** 包围盒(图片坐标):含底色 padding 与描边向外扩出的一半 */
export function textBox(t) {
const m = textMetrics(t)
const half = m.sw / 2
return {
x: t.x - half,
y: t.y - half,
w: Math.max(m.w, 2) + m.pad * 2 + m.sw,
h: Math.max(m.h, 1) + m.pad * 2 + m.sw
}
}
function alignOf(t) {
const a = t && t.align
return a === 'center' || a === 'right' ? a : 'left'
}
/**
* 画一段文字(含底色块、描边、多行、旋转)。
* 底色块与描边都按「块」来画:底色覆盖整块,描边沿字形外沿。
*/
export function drawTextObject(ctx, t) {
const m = textMetrics(t)
ctx.save()
ctx.textBaseline = 'top'
ctx.globalAlpha = t.opacity != null ? t.opacity : 1
const b = textBox(t)
const rot = t.rotation || 0
if (rot) {
const cx = b.x + b.w / 2
const cy = b.y + b.h / 2
ctx.translate(cx, cy)
ctx.rotate(rot * Math.PI / 180)
ctx.translate(-cx, -cy)
}
ctx.font = m.font
const align = alignOf(t)
const boxW = m.w + m.pad * 2
// 底色块:先于文字画,圆角按字号比例给一点(纯直角贴小字会很硬)
if (t.bgFill) {
const r = Math.min(m.pad + 2, Math.min(boxW, m.h + m.pad * 2) / 2)
// 0.55 在浅色/花色底图上偏透,用户容易以为「底色没生效」;0.68 既压得住底图,
// 也还看得见一点背景,是「垫一块板让字立起来」的常用手感。
ctx.globalAlpha = (t.opacity != null ? t.opacity : 1) * (t.bgAlpha == null ? TEXT_DEFAULTS.bgAlpha : t.bgAlpha)
ctx.fillStyle = t.bgColor || TEXT_DEFAULTS.bgColor
const bx = t.x, by = t.y
const bw = boxW, bh = m.h + m.pad * 2
ctx.beginPath()
if (typeof ctx.roundRect === 'function') {
ctx.roundRect(bx, by, bw, bh, r)
} else {
ctx.moveTo(bx + r, by)
ctx.arcTo(bx + bw, by, bx + bw, by + bh, r)
ctx.arcTo(bx + bw, by + bh, bx, by + bh, r)
ctx.arcTo(bx, by + bh, bx, by, r)
ctx.arcTo(bx, by, bx + bw, by, r)
ctx.closePath()
}
ctx.fill()
ctx.globalAlpha = (t.opacity != null ? t.opacity : 1)
}
// 对齐以「块内可用宽度(不含 padding)」为基准:多行时各行按这个宽度对齐
ctx.textAlign = align
const left = t.x + m.pad
const ox = align === 'center' ? left + m.w / 2 : align === 'right' ? left + m.w : left
ctx.lineJoin = 'round'
ctx.miterLimit = 2
for (let i = 0; i < m.lines.length; i++) {
const y = t.y + m.pad + i * m.lh
if (m.sw > 0) {
ctx.lineWidth = m.sw
ctx.strokeStyle = t.strokeColor || TEXT_DEFAULTS.strokeColor
ctx.strokeText(m.lines[i], ox, y)
}
ctx.fillStyle = t.color || TEXT_DEFAULTS.color
ctx.fillText(m.lines[i], ox, y)
}
ctx.restore()
}
/** 从默认样式造一段文字的字段(新建文字 / 老对象补默认值共用) */
export function newTextStyle(src) {
const s = src || {}
return {
fontWeight: weightOf(s),
// 字体 key 过一遍收敛:外部传进来不认识的字符串不会进 ctx.font(脏值会让整个
// 字体串失效、静默退回浏览器默认,文件本身看不出问题,极难排查)
fontFamily: fontKeyOf(s),
align: alignOf(s),
lineHeight: Number(s.lineHeight) || TEXT_LINE_HEIGHT,
strokeWidth: Math.max(0, Number(s.strokeWidth) || 0),
strokeColor: s.strokeColor || TEXT_DEFAULTS.strokeColor,
bgFill: !!s.bgFill,
bgColor: s.bgColor || TEXT_DEFAULTS.bgColor,
bgAlpha: s.bgAlpha == null ? TEXT_DEFAULTS.bgAlpha : Number(s.bgAlpha)
}
}
+497
View File
@@ -0,0 +1,497 @@
/* tools.js - 画笔、橡皮、吸管与合成画布
* 节:绘制工具、合成画布(吸管取样 / 导出 / 裁剪共用)。
* 约定:brushStampCache 是模块级缓存,只在本模块内重建;
* getCompositeCanvas 把所有可见图层+矢量对象合成到一张画布,
* 吸管/导出/裁剪共用它。
*/
'use strict'
import { S, runtime } from './state.js'
import { commitTextInput, getSelectedShape, getSelectedText, layerUnits, renderObjects, shapeBounds } from './objects.js'
import { cancelCrop, clearOverlay, hideCropBar, showCropBar, updateCropInfo } from './crop.js'
import { cancelImagePlacement } from './placement.js'
import { clamp } from './viewport.js'
import { resetOverlayTransform } from './scale.js'
import { getActiveCtx, getActiveLayer, renderLayerPanel } from './layers.js'
import { saveSnapshot } from './history.js'
import { updateBrushParamUI, updateColorUI, updateToolUI } from './events.js'
import { isDrawableLayer } from '../vendor/layer-logic.js'
import { hexToRgb, rgbToHex } from '../vendor/image-math.js'
import { rememberColor } from './recent-colors.js'
// ============ 绘制工具 ============
// hexToRgb / rgbToHex / parseRatio 统一由 shared/image-math.js 提供(可单测)
let brushStampCache = { key: '', canvas: null }
/** 软边笔刷章:径向渐变离屏 canvas */
function getBrushStamp(size, color, hardness) {
const key = size + '|' + color + '|' + hardness
if (brushStampCache.key === key && brushStampCache.canvas) return brushStampCache.canvas
const c = document.createElement('canvas')
c.width = size
c.height = size
const cx = c.getContext('2d')
const half = size / 2
const { r, g, b } = hexToRgb(color)
const grad = cx.createRadialGradient(half, half, half * hardness / 100, half, half, half)
grad.addColorStop(0, `rgba(${r},${g},${b},1)`)
grad.addColorStop(1, `rgba(${r},${g},${b},0)`)
cx.fillStyle = grad
cx.fillRect(0, 0, size, size)
brushStampCache = { key, canvas: c }
return c
}
/** 画笔/橡皮一笔的一段:画在 strokeCanvas(全不透明),透明度由 endStroke 合成时承担
* 橡皮用白色(destination-out 合成时只取 alpha 通道) */
export function strokeSegment(x1, y1, x2, y2) {
const ctx = S.strokeCtx
const size = Math.max(1, S.brushSize)
const color = S.tool === 'eraser' ? '#ffffff' : S.color
ctx.save()
if (S.brushHardness >= 100) {
ctx.strokeStyle = color
ctx.lineWidth = size
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
ctx.beginPath()
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke()
} else {
const stamp = getBrushStamp(size, color, S.brushHardness)
const dist = Math.hypot(x2 - x1, y2 - y1)
const step = Math.max(1, size / 6)
const n = Math.max(0, Math.ceil(dist / step))
for (let i = 0; i <= n; i++) {
const t = n === 0 ? 0 : i / n
ctx.drawImage(stamp, x1 + (x2 - x1) * t - size / 2, y1 + (y2 - y1) * t - size / 2)
}
}
ctx.restore()
S.strokeCanvas.style.opacity = S.brushOpacity
}
export function eraseSegment(x1, y1, x2, y2) {
const ctx = getActiveCtx()
if (!ctx) return
ctx.save()
if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule)
ctx.globalCompositeOperation = 'destination-out'
ctx.globalAlpha = S.brushOpacity
ctx.lineWidth = Math.max(1, S.brushSize)
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
ctx.beginPath()
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.stroke()
ctx.restore()
const active = getActiveLayer()
if (active && active.id === 'draw' && active.sourceCanvas) {
const sourceCtx = active.sourceCanvas.getContext('2d', { willReadFrequently: true })
sourceCtx.save()
sourceCtx.globalCompositeOperation = 'destination-out'
sourceCtx.globalAlpha = S.brushOpacity
sourceCtx.lineWidth = Math.max(1, S.brushSize) * active.w / Math.max(S.imgW, 1)
sourceCtx.lineCap = 'round'
sourceCtx.beginPath()
sourceCtx.moveTo((x1 - active.x) * S.imgW / active.w, (y1 - active.y) * S.imgW / active.w)
sourceCtx.lineTo((x2 - active.x) * S.imgW / active.w, (y2 - active.y) * S.imgW / active.w)
sourceCtx.stroke()
sourceCtx.restore()
}
S.pickerComposite = null
renderObjects()
}
/** 开始一笔 */
/** 若绘制层已被变换(移动/缩放/旋转),先把结果固化并重置变换参数,保证继续绘制的坐标正确 */
function bakeDrawableLayer(layer) {
if (!layer || !isDrawableLayer(layer) || !layer._srcBox) return
layer._srcBox = null
layer.sourceCanvas = null
layer.rotation = 0
layer.x = 0
layer.y = 0
layer.w = S.imgW
layer.h = S.imgH
layer._bounds = undefined
}
export function beginStroke() {
bakeDrawableLayer(getActiveLayer())
S.strokeCanvas.width = S.imgW
S.strokeCanvas.height = S.imgH
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH)
// 橡皮擦直接修改活跃图层,不显示独立轨迹层。
S.strokeCanvas.style.display = S.tool === 'eraser' ? 'none' : 'block'
S.strokeCanvas.style.opacity = S.brushOpacity
}
/** 结束一笔:按透明度一次性合成进活跃图层(画笔=正常合成,橡皮=destination-out) */
export function endStroke() {
for (const l of S.layers) l._bounds = undefined
const ctx = getActiveCtx()
if (!ctx) return
ctx.save()
if (S.selection && S.selection.active) ctx.clip(S.selection.path, S.selection.fillRule)
if (S.tool === 'eraser') {
ctx.globalCompositeOperation = 'destination-out'
}
ctx.globalAlpha = S.brushOpacity
ctx.drawImage(S.strokeCanvas, 0, 0)
ctx.restore()
S.strokeCanvas.style.display = 'none'
const active = getActiveLayer()
if (active && active.id === 'draw' && active.sourceCanvas && active.w > 0 && active.h > 0) {
const sourceCtx = active.sourceCanvas.getContext('2d', { willReadFrequently: true })
sourceCtx.save()
sourceCtx.globalCompositeOperation = S.tool === 'eraser' ? 'destination-out' : 'source-over'
sourceCtx.globalAlpha = S.brushOpacity
sourceCtx.translate(-active.x * S.imgW / active.w, -active.y * S.imgH / active.h)
sourceCtx.scale(S.imgW / active.w, S.imgH / active.h)
sourceCtx.drawImage(S.strokeCanvas, 0, 0)
sourceCtx.restore()
}
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH)
S.pickerComposite = null
}
/** 圆角半径:夹在短边一半以内,避免圆角把矩形吃掉变胶囊/消失 */
function roundedRadius(s, w, h) {
const r = Number(s && s.radius) || 0
if (r <= 0) return 0
return Math.min(r, Math.min(w, h) / 2)
}
/** 圆角矩形路径:不用 ctx.roundRect(老浏览器没有),手写 arcs,行为可控 */
function roundRectPath(ctx, x, y, w, h, r) {
const rr = Math.min(r, Math.min(w, h) / 2)
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()
}
/** 按形状对象绘制(矩形/箭头),预览与最终渲染共用 */
/** 形状描边色:每个形状自己存 color(v1.10 起选项栏可单独调) */
export function strokeOf(s) { return (s && s.color) || S.color }
/** 形状填充色:自己设过 fillColor 就用它,否则跟随描边色(同色实心是默认手感) */
export function fillOf(s) { return (s && s.fillColor) || strokeOf(s) }
export function drawShape(ctx, s) {
ctx.save()
ctx.globalAlpha = s.opacity != null ? s.opacity : 1
const rot = s.rotation || 0
if (rot) {
const b = shapeBounds(s)
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
ctx.translate(cx, cy)
ctx.rotate(rot * Math.PI / 180)
ctx.translate(-cx, -cy)
}
ctx.strokeStyle = strokeOf(s)
ctx.lineWidth = s.lw
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
// v1.17:无描边(strokeOn === false)。老对象没有这个字段,一律当有描边。
// 注意不能靠 lineWidth = 0 实现:canvas 会忽略 0 从而保持上一次的值。
const strokeOn = s.strokeOn !== false
if (s.type === 'pen') {
const pts = Array.isArray(s.pts) ? s.pts : []
if (pts.length > 1) {
ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y)
for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y)
if (s.closed) ctx.closePath()
if (s.closed && s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() }
if (strokeOn) ctx.stroke()
}
} else if (s.type === 'rect') {
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1)
const radius = roundedRadius(s, rw, rh)
if (radius > 0) {
ctx.beginPath()
roundRectPath(ctx, rx, ry, rw, rh, radius)
if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() }
if (strokeOn) ctx.stroke()
} else {
if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fillRect(rx, ry, rw, rh) }
if (strokeOn) ctx.strokeRect(rx, ry, rw, rh)
}
} else if (s.type === 'circle') {
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2)
const rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1)
ctx.beginPath()
ctx.ellipse(rx + rw / 2, ry + rh / 2, Math.max(1, rw / 2), Math.max(1, rh / 2), 0, 0, Math.PI * 2)
if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() }
if (strokeOn) ctx.stroke()
} else if (strokeOn) {
// 箭头:没有可填内部,去掉描边等于不画(UI 也不提供这个入口)
ctx.fillStyle = strokeOf(s)
ctx.beginPath()
ctx.moveTo(s.x1, s.y1)
ctx.lineTo(s.x2, s.y2)
ctx.stroke()
const angle = Math.atan2(s.y2 - s.y1, s.x2 - s.x1)
const headLen = Math.max(12, s.lw * 4)
ctx.beginPath()
ctx.moveTo(s.x2, s.y2)
ctx.lineTo(s.x2 - headLen * Math.cos(angle - Math.PI / 6), s.y2 - headLen * Math.sin(angle - Math.PI / 6))
ctx.moveTo(s.x2, s.y2)
ctx.lineTo(s.x2 - headLen * Math.cos(angle + Math.PI / 6), s.y2 - headLen * Math.sin(angle + Math.PI / 6))
ctx.stroke()
}
ctx.restore()
}
/** 当前工具笔刷半径(图片像素) */
function getToolBrushRadius() {
return Math.max(1, S.brushSize) / 2
}
/** 图片像素 → 屏幕像素 的换算系数 */
function screenScale() {
const rect = S.canvasStack.getBoundingClientRect()
return rect.width ? rect.width / S.imgW : S.zoom
}
/** 清笔刷环专用层(不碰裁剪框 / 选中框 / 蚂蚁线) */
export function clearToolRing() {
const ctx = S.cursorCtx
if (!ctx) return
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)
ctx.restore()
resetOverlayTransform(ctx)
}
/** 圆形笔刷光标:画在独立 cursorCanvas,避免 clearOverlay() 擦掉其它交互层 */
export function drawToolRing(pos) {
clearToolRing()
const ctx = S.cursorCtx || S.overlayCtx
const r = getToolBrushRadius()
const k = 1 / screenScale()
const rMin = 2 * k
const rr = Math.max(r, rMin)
ctx.save()
ctx.lineWidth = k
ctx.strokeStyle = 'rgba(0,0,0,0.8)'
ctx.beginPath()
ctx.arc(pos.x, pos.y, rr, 0, Math.PI * 2)
ctx.stroke()
ctx.strokeStyle = 'rgba(255,255,255,0.9)'
ctx.lineWidth = k
ctx.beginPath()
ctx.arc(pos.x, pos.y, Math.max(rr - k, 0), 0, Math.PI * 2)
ctx.stroke()
ctx.restore()
}
// ============ 合成画布(吸管取样 / 导出 / 裁剪共用) ============
/** 合成所有可见图层到一个临时 canvas */
export function getCompositeCanvas() {
const c = document.createElement('canvas')
c.width = S.imgW
c.height = S.imgH
const cx = c.getContext('2d', { willReadFrequently: true })
// 与 DOM 叠放 / 图层面板 / 命中测试共用同一份 z 序(唯一真源)
cx.globalAlpha = 1
for (const u of layerUnits()) {
if (u.obj.visible === false) continue
const el = u.kind === 'bitmap' ? u.obj.canvas : u.obj._canvas
if (!el) continue
// 位图的 opacity 由 CSS 显示、这里乘 alpha;矢量对象的不透明度已经画进像素
cx.globalAlpha = u.kind === 'bitmap' ? (u.obj.opacity == null ? 1 : u.obj.opacity) : 1
cx.drawImage(el, 0, 0)
}
cx.globalAlpha = 1
return c
}
/** 吸管取样用的合成画布缓存 */
function getPickerComposite() {
if (!S.pickerComposite) {
S.pickerComposite = getCompositeCanvas().getContext('2d', { willReadFrequently: true })
}
return S.pickerComposite
}
/** 取画布坐标处的合成像素颜色 */
export function sampleColor(pos) {
const x = clamp(Math.floor(pos.x), 0, Math.max(0, S.imgW - 1))
const y = clamp(Math.floor(pos.y), 0, Math.max(0, S.imgH - 1))
try {
const d = getPickerComposite().getImageData(x, y, 1, 1).data
return { r: d[0], g: d[1], b: d[2], a: d[3] }
} catch (e) {
return null
}
}
/** 吸管悬停预览浮窗 */
export function showPickerTip(e, s) {
const tip = runtime.el.querySelector('.iwb-editor-picker-tip')
if (!tip) return
const chip = tip.querySelector('.iwb-editor-picker-chip')
const hex = tip.querySelector('.iwb-editor-picker-hex')
if (s && s.a > 0) {
const h = rgbToHex(s.r, s.g, s.b)
chip.style.background = h
chip.style.border = '1px solid rgba(255,255,255,0.3)'
hex.textContent = h
} else {
chip.style.background = 'transparent'
chip.style.border = '1px dashed rgba(255,255,255,0.4)'
hex.textContent = '透明'
}
tip.style.display = 'flex'
tip.style.left = (e.clientX + 16) + 'px'
tip.style.top = (e.clientY + 16) + 'px'
}
export function hidePickerTip() {
const tip = runtime.el.querySelector('.iwb-editor-picker-tip')
if (tip) tip.style.display = 'none'
}
/** 取色完成:切回吸管激活前的工具 */
export function exitPicker() {
// 按住 Alt 的临时吸管:取色后不退出(PS 手感:Alt 按住期间可连续吸色),
// 由 keyup / 窗口失焦时的 endAltPicker() 统一收尾回到原工具
if (S.altPicker) {
S.pickerComposite = null
hidePickerTip()
return
}
S.tool = (S.prevTool && S.prevTool !== 'picker') ? S.prevTool : 'brush'
S.prevTool = null
// 回到的若不是选择/形状类工具,选中态按 setTool 同一套规则清掉,避免画布残留选中框
const back = S.tool
// 与 setTool 同一套规则(v1.3):只有选择工具保留选中态
if (back !== 'select') {
S.selectedLayerId = null
S.selectedTextId = null
S.selectedShapeId = null
}
S.pickerComposite = null
hidePickerTip()
updateToolUI()
updateBrushParamUI()
if (S.tool === 'crop') {
showCropBar()
updateCropInfo()
} else {
cancelCrop()
hideCropBar()
}
// 回到上一个工具后选项栏由 updateToolUI() → renderOptionBar() 按新工具重建
renderObjects()
}
/**
* PS 手感:画笔 / 橡皮下按住 Alt 临时变成吸管,松开 Alt 回到原工具。
* 只在这两个绘制工具下生效;正在描笔时(isDrawing)不打断。
* 取色后不退出吸管(见 exitPicker 的 altPicker 分支),可以按住 Alt 连续吸色。
*/
export function beginAltPicker() {
if (S.altPicker) return
if (S.tool !== 'brush' && S.tool !== 'eraser') return
if (S.isDrawing) return
S.altPicker = true
setTool('picker') // setTool 会把原工具存进 prevTool,松开 Alt 时用它还原
}
/** 松开 Alt / 窗口失焦:结束临时吸管并回到原工具 */
export function endAltPicker() {
if (!S.altPicker) return
S.altPicker = false
exitPicker()
}
/** 统一颜色应用:设置当前色 + 同步选中文字/形状颜色。
* opts.skipHistory:连续取色(拖 SV/色相条)时由调用方在拖动开始时已拍过快照,
* 这里不再逐步 saveSnapshot —— 否则拖一下就是几百张全画质 ImageData。 */
export function applyColorChange(color, opts) {
const skipHistory = !!(opts && opts.skipHistory)
S.color = color
// 只有「确认型」改色才进最近使用:拖 SV 时 skipHistory=true 每帧都调,
// 全记进去会把最近色刷成一串相邻色,毫无用处。
if (!skipHistory) rememberColor(color)
updateColorUI()
const t = getSelectedText()
if (t && !t.locked && t.color !== S.color) {
if (!skipHistory) saveSnapshot()
t.color = S.color
renderObjects()
}
const sh = getSelectedShape()
if (sh && !sh.locked && S.tool !== 'text' && (sh.color !== S.color || sh.strokeOn === false)) {
// v1.17:给「无描边」的形状选颜色 = 想再看见描边,顺手打开。
// 与改色共用同一张快照,撤销一步就能回到「无描边 + 旧色」。
const revive = sh.strokeOn === false
if (!skipHistory) saveSnapshot()
sh.color = S.color
if (revive) { sh.strokeOn = true; S.shapeStrokeOn = true }
renderObjects()
}
}
/** 切换工具(工具栏按钮、快捷键、调色板吸色共用)。保留同类形状选中以便继续编辑。 */
export function setTool(tool) {
if (S.placingImage) cancelImagePlacement()
commitTextInput()
// 用户主动切到别的工具 = 放弃「按住 Alt 临时吸管」,否则松 Alt 会把工具抢回去
if (tool !== 'picker') S.altPicker = false
// 钢笔节点编辑与文字编辑都只属于 V(v1.5):切到任何创建类工具都退出编辑态,
// 否则从 V 带着 penEditId 切到 P 会出现「钢笔下能拖节点但点不动」的半状态。
if (tool !== 'select') { S.penEditId = null; S.penDragPt = -1; S.penDragPending = null }
if (tool === 'picker' && S.tool !== 'picker') S.prevTool = S.tool
if (tool !== 'pen') S.penPath = null
// 选区与裁剪互斥:进裁剪必须清掉选区;离开选区工具要丢弃未完成的拉框/套索
if (tool === 'crop') { S.selection = null; S.marquee = null; S.lassoPts = null }
if (tool !== 'marquee' && tool !== 'lasso') {
if (S.marquee || S.lassoPts) { S.isDrawing = false; S.interaction = 'idle' }
S.marquee = null
S.lassoPts = null
}
S.tool = tool
// 吸管是临时取色工具:必须保留选中态,否则「选中形状 → 按 I 取色」时选中被清掉,
// applyColorChange 找不到对象,颜色只写进画笔色、形状不变(用户反馈 2026-11-04)
// 选中态只属于「选择(V)」与临时吸管(v1.3,用户裁定 2026-11-05):
// 矩形/圆形/箭头/钢笔/文字都只负责新建,切过去就清掉选中 ——
// 否则矢量工具下点到已有图形会被当成拖动它,没法在它上面继续画。
const keepSel = tool === 'select' || tool === 'picker'
if (!keepSel) {
S.selectedLayerId = null
S.selectedTextId = null
S.selectedShapeId = null
}
S.bitmapDrag = null
S.textDrag = null
S.shapeDrag = null
S.pickerComposite = null
S.lastClick = null // 切工具即断掉双击序列,避免拿上一个工具的最后一次点击配对
hidePickerTip()
updateToolUI()
updateBrushParamUI()
if (tool === 'crop') {
showCropBar()
updateCropInfo()
} else {
cancelCrop()
hideCropBar()
}
renderObjects()
renderLayerPanel()
// 让蚂蚁线/浮动条按新的工具与选区状态同步(由 index.js 注入)
if (S.renderAll) S.renderAll()
}
+364
View File
@@ -0,0 +1,364 @@
/* viewport.js - 画布尺寸、缩放平移、旋转辅助与坐标换算
* 节:画布设置、旋转辅助、坐标。
* 约定:所有屏幕坐标 <-> 图片坐标的换算都过 getPos/rotPt/unrotPt,
* 缩放状态只写 S.zoom / S.viewX / S.viewY。
*/
'use strict'
import { S, ZOOM_MAX, ZOOM_MIN } from './state.js'
import { overlayScale, resetOverlayTransform, viewScale } from './scale.js'
import { bindCanvasEvents, updateZoomUI } from './events.js'
import { clearOverlay } from './crop.js'
import { createLayerCanvas, purgeVectorCanvases, renderLayerPanel, styleVectorViewport } from './layers.js'
import { getSelectedShape, getSelectedText, renderObjects, shapeBounds, textBounds } from './objects.js'
// ============ 画布设置 ============
/** 三张交互层(选中框/蚂蚁线/笔刷环)共享同一尺寸与坐标基准,但各自清屏互不影响 */
function syncOverlayCanvas() {
const pad = S.overlayPad || 0
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
const w = Math.round((S.imgW + pad * 2) * scale) + 'px'
const h = Math.round((S.imgH + pad * 2) * scale) + 'px'
for (const c of [S.overlayCanvas, S.selectionCanvas, S.cursorCanvas]) {
if (!c) continue
c.style.left = '0px'
c.style.top = '0px'
c.style.width = w
c.style.height = h
}
}
export function setupCanvas(img) {
purgeVectorCanvases()
// 清除旧的动态图层 canvas
for (const layer of S.layers) {
if (layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas)
}
S.layers = []
// 设置工具 canvas 尺寸
S.textCanvas.width = S.imgW
S.textCanvas.height = S.imgH
S.strokeCanvas.width = S.imgW
S.strokeCanvas.height = S.imgH
S.strokeCanvas.style.display = 'none'
// 裁剪越界区域属于交互工作区,不改变图片本身的画布尺寸。
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
// overlayScale 依赖 fitW,必须先算出适应尺寸再建交互层缓冲
computeFit()
const uiK = overlayScale()
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK)
c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK)
resetOverlayTransform(cx)
}
// 创建图层 1: 原图
const baseCanvas = createLayerCanvas()
const baseCtx = baseCanvas.getContext('2d', { willReadFrequently: true })
baseCtx.clearRect(0, 0, S.imgW, S.imgH)
baseCtx.drawImage(img, 0, 0)
S.layers.push({
id: 'base',
name: '原图',
canvas: baseCanvas,
ctx: baseCtx,
opacity: 1,
visible: true,
locked: true,
z: 0
})
// 默认不再预建「画笔标注」空层(用户裁定 2026-11-04:需要时自己加)。
// 画笔起笔时 ensureWritableLayer() 会自动落一个「标注 N」层兜底,
// 所以这里活动层指向原图(锁定态),不会误画到原图上。
S.activeLayerId = 'base'
S.zCounter = 1
S.textCtx.clearRect(0, 0, S.imgW, S.imgH)
S.strokeCtx.clearRect(0, 0, S.imgW, S.imgH)
clearOverlay()
S.pickerComposite = null
renderObjects()
S.viewX = null
applyView()
renderLayerPanel()
bindCanvasEvents()
}
/**
* 只调整画布尺寸与交互层,不重建图层(裁剪 / 撤销裁剪共用)。
*
* 与 setupCanvas 的分工:setupCanvas 会清空 S.layers 并新建「原图 + 画笔」两层,
* 那是「打开一张新图」的语义。裁剪只是在同一张图上换视窗,像素由调用方先搬好,
* 这里只负责尺寸、交互层、矢量层与视图基准,图层结构原样保留。
*
* ⚠️ 这里会把每个图层 canvas 的像素缓冲清空(canvas.width 赋值即重置),
* 调用方必须在调用前把像素复制出来,调用后写回。
*/
export function resizeWorkspace(w, h) {
S.imgW = Math.max(1, Math.round(w))
S.imgH = Math.max(1, Math.round(h))
S.textCanvas.width = S.imgW
S.textCanvas.height = S.imgH
S.strokeCanvas.width = S.imgW
S.strokeCanvas.height = S.imgH
S.overlayPad = Math.max(96, Math.ceil(Math.max(S.imgW, S.imgH) * 0.18))
computeFit()
const uiK = overlayScale()
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = Math.round((S.imgW + S.overlayPad * 2) * uiK)
c.height = Math.round((S.imgH + S.overlayPad * 2) * uiK)
resetOverlayTransform(cx)
}
purgeVectorCanvases()
for (const layer of S.layers) {
layer.canvas.width = S.imgW
layer.canvas.height = S.imgH
layer._bounds = undefined
}
S.pickerComposite = null
clearOverlay()
S.viewX = null
applyView()
renderObjects()
renderLayerPanel()
}
/** 计算「适应容器」的基准显示尺寸(不限制放大,小图也铺满) */
function computeFit() {
// 底部浮动工具栏(Figma 风格)压在画布下沿,给它预留出高度,
// 否则适应窗口后图片下边缘会被工具栏盖住。
const TOOLBAR_RESERVE = 72
const availW = Math.max(50, S.canvasWrap.clientWidth - 48)
const availH = Math.max(50, S.canvasWrap.clientHeight - 48 - TOOLBAR_RESERVE)
const ratio = Math.min(availW / S.imgW, availH / S.imgH)
S.fitW = Math.max(1, S.imgW * ratio)
S.fitH = Math.max(1, S.imgH * ratio)
}
/**
* 应用当前 zoom 与平移位置到画布显示尺寸与位置(自由平移,无边界限制)。
* @param {object} anchor 可选 { mx, my, px, py }:缩放锚点
*/
function applyView(anchor) {
const w = Math.round(S.fitW * S.zoom)
const h = Math.round(S.fitH * S.zoom)
// 更新所有 canvas 的显示尺寸(位图图层 + 工具层)
for (const layer of S.layers) {
layer.canvas.style.width = w + 'px'
layer.canvas.style.height = h + 'px'
}
S.textCanvas.style.width = S.strokeCanvas.style.width = w + 'px'
S.textCanvas.style.height = S.strokeCanvas.style.height = h + 'px'
syncOverlayCanvas()
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
if (S.transparencyGrid) {
S.transparencyGrid.style.left = Math.round((S.overlayPad || 0) * scale) + 'px'
S.transparencyGrid.style.top = Math.round((S.overlayPad || 0) * scale) + 'px'
S.transparencyGrid.style.width = w + 'px'
S.transparencyGrid.style.height = h + 'px'
}
// 显式固定 stack 尺寸,保证统一坐标基准始终可测量,新增/隐藏图层不会触发布局偏移。
const pad = S.overlayPad || 0
S.canvasStack.style.width = Math.round((S.imgW + pad * 2) * scale) + 'px'
S.canvasStack.style.height = Math.round((S.imgH + pad * 2) * scale) + 'px'
const layerOffset = Math.round(pad * scale)
for (const layer of S.layers) {
layer.canvas.style.left = layerOffset + 'px'
layer.canvas.style.top = layerOffset + 'px'
}
S.textCanvas.style.left = layerOffset + 'px'
S.textCanvas.style.top = layerOffset + 'px'
S.strokeCanvas.style.left = layerOffset + 'px'
S.strokeCanvas.style.top = layerOffset + 'px'
styleVectorViewport(w, h, layerOffset)
let left, top
if (anchor && anchor.mx !== undefined) {
left = anchor.mx - anchor.px * S.zoom
top = anchor.my - anchor.py * S.zoom
} else if (S.viewX !== null) {
left = S.viewX
top = S.viewY
} else {
left = (S.canvasWrap.clientWidth - w) / 2
top = (S.canvasWrap.clientHeight - h) / 2
}
setView(left, top)
updateZoomUI()
}
/** 设置画布平移位置(自由坐标,无边界限制) */
export function setView(x, y) {
S.viewX = x
S.viewY = y
const stack = S.canvasStack
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
const pad = S.overlayPad || 0
// 让原图左上角仍对应 viewX/viewY,外围 padding 不参与画布平移坐标。
stack.style.transform = `translate3d(${Math.round(x - pad * scale)}px, ${Math.round(y - pad * scale)}px, 0)`
}
/** 以指定屏幕坐标(wrap 内)为中心缩放 */
export function zoomStep(factor, mx, my) {
const nz = clamp(S.zoom * factor, ZOOM_MIN, ZOOM_MAX)
if (nz === S.zoom) return
const px = (mx - (S.viewX || 0)) / S.zoom
const py = (my - (S.viewY || 0)) / S.zoom
S.zoom = nz
applyView({ mx, my, px, py })
}
/**
* 适应窗口:先按当前容器尺寸重算基准显示尺寸,再回到 zoom=1 并居中。
* 只写 zoom=1 不够 —— 窗口/侧栏变过之后 fitW/fitH 还是旧值,点了看起来「没反应」。
*/
export function setZoomFit() {
computeFit()
S.zoom = 1
S.viewX = null
applyView()
}
/** 100% 实际像素(PS: Ctrl+1)。S.zoom 是相对 fitW 的倍数,所以要换算。 */
export function setZoomActual() {
computeFit()
S.zoom = clamp(S.fitW ? S.imgW / S.fitW : 1, ZOOM_MIN, ZOOM_MAX)
S.viewX = null
applyView()
}
export function clamp(v, min, max) { return Math.max(min, Math.min(max, v)) }
/**
* 视图缩放:**1 个图片像素 = 多少屏幕 CSS 像素**。
*
* ⚠️ 这不是 S.zoom。S.zoom 是「相对 fitW 的倍数」:图片适应窗口后 fitW ≠ imgW,
* 所以 zoom=1 时屏幕上每个图片像素只占 fitW/imgW 个 CSS 像素。
*
* 所有「屏幕上恒定大小」的界面元素(控制点、描边粗细、虚线间距、命中半径、
* 预览文字)都必须用 X / viewScale() 换算。直接写 X / S.zoom 会让实际屏幕尺寸
* 变成 X * fitW / imgW —— 只跟图片尺寸走、和缩放无关:
* 小图被放大铺满容器时 fitW/imgW 可达 4~8,控制点就会大得离谱;大图则缩成看不见。
*/
// ============ 旋转辅助 ============
export function rotPt(px, py, cx, cy, deg) {
if (!deg) return [px, py]
const a = deg * Math.PI / 180, sn = Math.sin(a), cs = Math.cos(a)
const dx = px - cx, dy = py - cy
return [cx + dx * cs - dy * sn, cy + dx * sn + dy * cs]
}
export function unrotPt(px, py, cx, cy, deg) {
return rotPt(px, py, cx, cy, -(deg || 0))
}
/** 旋转手柄:四个角沿对角线向外偏移(局部坐标) */
function rotationHandlesLocal(b) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
// 26 屏幕像素的间距,换算成图片单位(不能除以 S.zoom,否则随图片尺寸漂移)
const d = 26 / Math.max(viewScale(), 0.0001)
return [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]].map(c => {
const dx = c[0] - cx, dy = c[1] - cy, len = Math.hypot(dx, dy) || 1
return [c[0] + dx / len * d, c[1] + dy / len * d]
})
}
/** 命中旋转手柄(传局部坐标点) */
export function hitRotationHandle(lp, b) {
const pts = rotationHandlesLocal(b)
// 11 屏幕像素的命中半径。原先用 Math.max(..., 8) 托底,但托底值是图片单位,
// 放大显示时会变成巨大的屏幕命中区(误触),故只按 viewScale 换算。
const R = 11 / Math.max(viewScale(), 0.0001)
for (const pt of pts) {
if (Math.hypot(lp[0] - pt[0], lp[1] - pt[1]) < R) return true
}
return false
}
/** 绘制四个角外侧的旋转手柄:细弧 + 末端小箭头(旋转语义,比裸 C 弧更可读) */
export function drawRotationHandles(ctx, b, rot) {
const cx = b.x + b.w / 2, cy = b.y + b.h / 2
const pts = rotationHandlesLocal(b)
const k = Math.max(viewScale(), 0.0001)
const r = 6.5 / k
const lw = 1.5 / k
const ah = 3 / k // 箭头长度
const A0 = Math.PI * 0.2, A1 = Math.PI * 1.72
ctx.save()
ctx.strokeStyle = '#f0b34e'
ctx.fillStyle = '#f0b34e'
ctx.lineWidth = lw
ctx.lineCap = 'round'
for (const pt of pts) {
const w = rotPt(pt[0], pt[1], cx, cy, rot || 0)
ctx.beginPath()
ctx.arc(w[0], w[1], r, A0, A1)
ctx.stroke()
// 弧末端顺时针切线方向的小箭头
const ex = w[0] + Math.cos(A1) * r, ey = w[1] + Math.sin(A1) * r
const ta = A1 + Math.PI / 2
ctx.beginPath()
ctx.moveTo(ex + Math.cos(ta) * ah * 1.4, ey + Math.sin(ta) * ah * 1.4)
ctx.lineTo(ex + Math.cos(ta + 2.4) * ah, ey + Math.sin(ta + 2.4) * ah)
ctx.lineTo(ex + Math.cos(ta - 2.4) * ah, ey + Math.sin(ta - 2.4) * ah)
ctx.closePath()
ctx.fill()
}
ctx.restore()
}
export const ROT_CURSOR = 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'24\' height=\'24\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'black\' stroke-width=\'2\' stroke-linecap=\'round\'><path d=\'M21 12a9 9 0 1 1-3-6.7\'/><polyline points=\'21 3 21 9 15 9\'/></svg>") 12 12, crosshair'
/** 指针是否悬停在当前选中对象(或放置中图片)的旋转手柄上 */
export function isOverRotationHandle(p) {
if (S.placingImage) {
const b = { x: S.placingImage.x, y: S.placingImage.y, w: S.placingImage.w, h: S.placingImage.h }
const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, S.placingImage.rotation || 0)
return hitRotationHandle(lp, b)
}
const t = getSelectedText()
if (t) {
const b = textBounds(t)
const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, t.rotation || 0)
return hitRotationHandle(lp, b)
}
const sh = getSelectedShape()
if (sh) {
const b = shapeBounds(sh)
const lp = unrotPt(p.x, p.y, b.x + b.w / 2, b.y + b.h / 2, sh.rotation || 0)
return hitRotationHandle(lp, b)
}
const layer = S.layers.find(l => l.id === S.selectedLayerId && l.transformable)
if (layer) {
const lp = unrotPt(p.x, p.y, layer.x + layer.w / 2, layer.y + layer.h / 2, layer.rotation || 0)
return hitRotationHandle(lp, layer)
}
return false
}
export function boxCorners(x, y, w, h, rot) {
const cx = x + w / 2, cy = y + h / 2
return [[x, y], [x + w, y], [x + w, y + h], [x, y + h]].map(pt => rotPt(pt[0], pt[1], cx, cy, rot))
}
// ============ 坐标 ============
export function getPos(e) {
// 统一使用 stack 的边界作为坐标基准。图层 canvas 可能被隐藏,或在
// 插入/重排时暂时不参与布局;以具体图层 boundingRect 计算会造成左移。
const rect = S.canvasStack.getBoundingClientRect()
const pad = S.overlayPad || 0
const scale = S.imgW ? (S.fitW * S.zoom) / S.imgW : 1
return {
x: (e.clientX - rect.left) / Math.max(scale, 0.0001) - pad,
y: (e.clientY - rect.top) / Math.max(scale, 0.0001) - pad
}
}
+19
View File
@@ -0,0 +1,19 @@
/* 打包入口(esbuild → IIFE)。
*
* 顺序要求:先 import 编辑器模块 —— 它在模块顶层把 window.__iwbEditor 挂好(编辑器自带约定);
* glue.js 只在模块顶层声明函数,不读 window,故无 TDZ/顺序风险。
*
* manifest 不放在这里:esbuild 的打印器会把单引号改写成双引号,而 scripts/validate.mjs
* 只认单引号。manifest 走 build-plugin.mjs 的 banner 通道(原样写入),注册调用走 footer 通道。
*/
'use strict'
import './editor/index.js'
import editorCss from './editor.css'
import { createGlue } from './glue.js'
;(typeof window !== 'undefined' ? window : globalThis).__IWB_ANNOTATE_FACTORY__ = function (ctx) {
return createGlue(ctx, editorCss)
}
// build-rev: 2026-11-17 (cache-bust)
+137
View File
@@ -0,0 +1,137 @@
/* 宿主胶水:把 window.__iwbEditor(从 iwb-plaus 扩展移植)接到 IWBPluginHost 的 ctx 上。
*
* 数据流(全部走公开契约,不碰宿主内部实现):
* nodeActions.run(node) → ctx.canvas.getNodeImage(node.id) → __iwbEditor.open()
* → onResult(blob|dataURL, mode) → mode==='replace' ? ctx.canvas.setNodeImage
* : ctx.canvas.createImageNode
*
* 注意 mode 字面量来自编辑器 events.js 的按钮绑定,是 'newNode' / 'replace'(不是 'new')。
* CSP:宿主 style-src 允许 'unsafe-inline',故样式用运行时 <style> 注入;
* img-src 允许 data:/blob:,编辑器内部 blob URL 可用。
*/
'use strict'
export function createGlue(ctx, css) {
let styleInjected = false
function ensureStyle() {
if (styleInjected) return
styleInjected = true
try {
const style = document.createElement('style')
style.id = 'iwb-annotate-style'
style.textContent = css
;(document.head || document.documentElement).appendChild(style)
} catch (error) {
styleInjected = false
ctx.log('inject-style-failed', error && error.message)
}
}
function blobToDataUrl(blob) {
return new Promise(function (resolve, reject) {
const reader = new FileReader()
reader.onload = function () { resolve(String(reader.result || '')) }
reader.onerror = function () { reject(reader.error || new Error('读取导出图片失败')) }
reader.readAsDataURL(blob)
})
}
// 编辑器优先给 Blob(省 44MB base64 堆驻留),toBlob 失败时才退化成 dataURL。
function imageToDataUrl(out) {
if (typeof out === 'string') return Promise.resolve(out)
if (out && typeof out.arrayBuffer === 'function') return blobToDataUrl(out)
return Promise.reject(new Error('导出结果不是可用的图片数据'))
}
function baseName(node) {
return String((node && node.name) || 'image').replace(/\.[^.]+$/, '') || 'image'
}
function openEditor(node) {
const id = node && node.id
if (!id) return Promise.reject(new Error('请先选中一个带图的节点'))
const editor = typeof window !== 'undefined' ? window.__iwbEditor : null
if (!editor || typeof editor.open !== 'function') {
return Promise.reject(new Error('标注编辑器未加载'))
}
return Promise.resolve(ctx.canvas.getNodeImage(id)).then(function (image) {
if (!image || !image.dataUrl) {
// getNodeImage 对跨域 http 图只返回 { url }(画布读像素会污染),v1 明确拒绝并给出可操作提示。
throw new Error(image && image.url
? '该节点是远程图片,暂不支持标注(请先转存为本地位图)'
: '该节点没有可编辑的图片')
}
ensureStyle()
return new Promise(function (resolve, reject) {
let settled = false
// onResult 一旦接管(异步编码 + 写回节点),close() 触发的 onClose
// 就不能再抢先结算,否则会变成「节点已写回但 Promise 报取消」。
let handedOff = false
const settle = function (fn) { if (!settled) { settled = true; fn() } }
Promise.resolve(editor.open({
imageBase64: image.dataUrl,
imageName: baseName(node) + '.png',
settings: ctx.settings, // 记住输出预设 / 侧栏开合(宿主提供的命名空间 KV)
onError: function (message) {
settle(function () { reject(new Error(String(message || '编辑失败'))) })
},
onClose: function () {
// 点「退出」:编辑器不产出结果,必须在这里结算,否则 Promise 永远悬挂。
if (handedOff) return
settle(function () { resolve('cancel') })
},
onResult: function (out, mode) {
handedOff = true
imageToDataUrl(out).then(function (dataUrl) {
const replaced = mode === 'replace'
const ok = replaced
? ctx.canvas.setNodeImage(id, dataUrl)
: Boolean(ctx.canvas.createImageNode({ dataUrl: dataUrl, name: baseName(node) + '_edit.png' }))
if (!ok) throw new Error(replaced ? '写回原节点失败' : '新建节点失败')
settle(function () { resolve(mode) })
}).catch(function (error) {
settle(function () { reject(error) })
})
},
})).catch(function (error) {
settle(function () { reject(error) })
})
})
})
}
// 只在图片输入节点(ref)暴露:out/gen/layer 是产图节点,一个节点可能有多张结果或多个图层,
// getNodeImage 只能取 result[0],在漂浮菜单里放"编辑图片"会被误读成"编辑结果图"。
// 产图节点要处理图片,先「复制 / 插入为参考图节点」。
function appliesTo(node) {
if (!node) return false
return node.type === 'ref'
}
ctx.nodeActions.register({
id: 'annotate-node',
title: '标注 / 修图',
icon: 'pencil-ruler',
appliesTo: appliesTo,
run: function (node) { return openEditor(node) },
})
ctx.commands.register({
id: 'annotate-selected',
title: '标注 / 修图:选中节点',
icon: 'pencil-ruler',
run: function () {
const selected = ctx.canvas.getSelectedNode()
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
return openEditor(selected)
},
})
return {
dispose: function () { /* 编辑器自带 close() 与像素释放,这里无额外订阅需要解绑 */ },
}
}
+26
View File
@@ -0,0 +1,26 @@
// 手写 manifest —— 必须保持单引号:scripts/validate.mjs 只认单引号形式,而 esbuild 打印器会改成双引号,
// 所以本文件不经 esbuild 转换,由 build-plugin.mjs 原样放在产物最前面(banner)。
//
// 为什么必须排在最前:校验器用「文件里第一个形如 id 冒号 单引号 的字面量」判定插件 id,
// 排在 bundle 之前才能保证取到的是下面这份 manifest,而不是打包代码里的同形字面量。
// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。
//
// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。
// skin: 'private' = 本插件自带整套调色板(Catppuccin 深色工具 UI),不跟随宿主主题。
// 代价由宿主契约测试钉死:声明 private 的插件不得引用宿主颜色 var(--iwb-*),只能自洽。
var __IWB_ANNOTATE_MANIFEST__ = {
id: 'image-annotate',
name: '标注 / 修图',
version: '__PLUGIN_VERSION__',
apiVersion: 1,
skin: 'private',
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
settings: {
exportPreset: { type: 'string', default: 'original' },
exportFormat: { type: 'string', default: 'png' },
exportBg: { type: 'string', default: 'transparent' },
exportMaxKB: { type: 'number', default: 0 },
exportSize: { type: 'number', default: 800 },
panelsCollapsed: { type: 'boolean', default: false }
},
}
+11
View File
@@ -0,0 +1,11 @@
// 手写注册尾部(build-plugin.mjs 原样追加到产物末尾,不 overlapped with esbuild 的打印器)。
// 时序:bundle 先执行(挂好 __IWB_ANNOTATE_FACTORY__),再注册;factory 由宿主在「启用插件」时才调用。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
global.IWBPluginHost.register(__IWB_ANNOTATE_MANIFEST__, function (ctx) {
return global.__IWB_ANNOTATE_FACTORY__(ctx)
})
})(typeof window !== 'undefined' ? window : globalThis)
// build-rev: 2026-11-17T17 (pointer-self-heal)
+52
View File
@@ -0,0 +1,52 @@
/* 与 canvas/DOM 无关的纯计算,抽出来是为了能被单元测试直接覆盖 */
/** #rgb / #rrggbb → {r,g,b}(0~255) */
export function hexToRgb(hex) {
const h = String(hex || '').replace('#', '')
const v = h.length === 3 ? h.split('').map((c) => c + c).join('') : h
return {
r: parseInt(v.slice(0, 2), 16) || 0,
g: parseInt(v.slice(2, 4), 16) || 0,
b: parseInt(v.slice(4, 6), 16) || 0
}
}
/** {r,g,b} / (r,g,b) → #rrggbb */
export function rgbToHex(r, g, b) {
const to = (v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')
return `#${to(r)}${to(g)}${to(b)}`
}
/** 裁剪比例字符串 "16:9" / "free" → 数值 (w/h);非法返回 0(表示不限制) */
export function parseRatio(str) {
if (str === 'free' || !str) return 0
const parts = String(str).split(':')
if (parts.length === 2) {
const w = parseFloat(parts[0])
const h = parseFloat(parts[1])
if (w > 0 && h > 0) return w / h
}
return 0
}
/**
* 把内容等比缩放并居中放进 box(白底大图 / 覆盖布局共用)
* 内容最长边 = min(boxW, boxH) * ratio
* @returns {{x:number,y:number,w:number,h:number,scale:number}} 无效输入返回全 0 矩形
*/
export function fitRect(srcW, srcH, boxW, boxH, ratio = 1) {
if (!(srcW > 0) || !(srcH > 0) || !(boxW > 0) || !(boxH > 0)) {
return { x: 0, y: 0, w: 0, h: 0, scale: 0 }
}
const r = Math.max(0.01, Math.min(1, ratio))
const maxLen = Math.min(boxW, boxH) * r
const scale = Math.min(maxLen / srcW, maxLen / srcH)
const w = srcW * scale
const h = srcH * scale
return { x: (boxW - w) / 2, y: (boxH - h) / 2, w, h, scale }
}
/** 通用 clamp */
export function clamp(v, min, max) {
return Math.max(min, Math.min(max, v))
}
+41
View File
@@ -0,0 +1,41 @@
/* 图层恢复路径判定 —— 快照端与恢复端共用的唯一真源
* 快照端(editor.js snapshotState)用它决定"要不要拍这份像素",
* 恢复端(editor.js restoreState)用它决定"要不要读这份像素"。
* 两边必须永远一致,否则会出现"快照没拍、恢复却要读"的数据丢失。
*/
/**
* 绘制类图层(画笔标注 / 空白图层):非原图、且没有绑定图片的光栅层
* @param {{id?:string, image?:unknown}} layer
*/
export function isDrawableLayer(layer) {
return !!layer && layer.id !== 'base' && !layer.image
}
/**
* 恢复该图层时走哪条路径
* 'redraw':按 image/sourceCanvas 几何重绘,快照里的 bm.data 永远不会被读取
* —— 这类图层的像素是白存的字节(通常是最大的原图层)
* 'pixels':依赖 putImageData(bm.data),快照必须保留像素
*
* 注意 sourceCanvas 的语义:恢复流程对绘制类图层会先清空 sourceCanvas,
* 因此这里对 drawable 图层一律按"没有 sourceCanvas"处理。
*
* @param {{id?:string, image?:unknown, sourceCanvas?:unknown, transformable?:boolean}} layer
* @returns {'redraw'|'pixels'}
*/
export function restorePath(layer) {
if (!layer) return 'pixels'
const sourceCanvas = isDrawableLayer(layer) ? null : layer.sourceCanvas
if (layer.transformable && (layer.image || sourceCanvas)) return 'redraw'
return 'pixels'
}
/**
* 快照是否可以跳过该图层的像素
* 与 restorePath 完全等价,单独命名是为了让快照端的意图更直白。
*/
export function needsPixelSnapshot(layer) {
return restorePath(layer) === 'pixels'
}
File diff suppressed because it is too large. Load diff
+437
View File
@@ -0,0 +1,437 @@
// 真实站点端到端(开发用,不进 CI)。
//
// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被
// `connect-src 'self' https: …` 拦掉)在 mock 下永远绿,只有带 CSP 的真站能抓出来。
// 它不 mock /plugins/*:走真实 KV + 浏览器 SRI 校验 + 真实画布桥。
//
// 运行:
// node image-annotate/tools/e2e-site.mjs
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-annotate/tools/e2e-site.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/image-annotate/tools
const REPO = path.resolve(HERE, '../..') // <repo>
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
console.error(' npm i -D playwright # 本仓或宿主仓皆可')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node image-annotate/tools/e2e-site.mjs')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-annotate/package.json'), 'utf8')).version
const CFG = { providers: [], canvas: {} }
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const poll = async (fn, timeout = 25000, step = 250) => {
const end = Date.now() + timeout
for (;;) {
let v
try { v = await fn() } catch { v = false }
if (v) return v
if (Date.now() > end) return false
await new Promise((r) => setTimeout(r, step))
}
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } })
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message + ' @ ' + String(e.stack || '').split('\n').slice(1, 4).join(' | ')))
page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
// 造一张真实的 96x64 PNG 作为节点图片
await page.goto('about:blank')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 96; c.height = 64
const x = c.getContext('2d')
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 96, 64)
x.fillStyle = '#ffffff'; x.fillRect(20, 12, 56, 40)
return c.toDataURL('image/png')
})
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
const ws = JSON.parse(JSON.stringify(d.ws))
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ 'image-annotate': { enabled: true, settings: {}, data: {} } }))
}, { cfg: CFG, ws: WS, png: PNG })
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
// ---------- 1) 真实 KV 加载 + SRI + 启用 ----------
const active = await poll(async () => page.evaluate(() => {
const p = window.IWBPluginHost.list().find((x) => x.id === 'image-annotate')
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
}))
check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active))
check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
// 文件名两种都合法:plugins-publish.mjs 产内容寻址名(.<hash12>.js,可 immutable 缓存),
// plugins-publish.sh(带主干守卫的合规通道)产固定名(plugin-image-annotate.js,走 no-cache+ETag)。
// 断言的关键是「必须带 integrity」,与命名策略无关。
check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /^\/plugins\/plugin-image-annotate(\.[a-f0-9]{12})?\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
// ---------- 2) 打开工作区 + 节点存在 ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
// ---------- 3) 入口:节点漂浮菜单(回落右键插件命令)----------
const openEditor = async () => {
await page.locator('.iwb-node[data-node-id="r1"]').click()
const btn = page.locator('.iwb-node-floatbar button[title="标注 / 修图"]')
if (await btn.count()) { await btn.click(); return '漂浮菜单' }
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '标注 / 修图:选中节点' }).click()
return '右键命令'
}
const entry = await openEditor()
check('节点入口可触发(漂浮菜单或右键命令)', true, entry)
// ---------- 4) 编辑器打开(真实 CSP 下注入样式)----------
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
const opened = await page.evaluate(() => {
const el = document.querySelector('#iwb-editor-overlay')
const style = document.getElementById('iwb-annotate-style')
return {
display: getComputedStyle(el).display,
position: getComputedStyle(el).position,
zIndex: getComputedStyle(el).zIndex,
bg: getComputedStyle(el).backgroundColor,
styleInjected: Boolean(style && style.textContent.includes('.iwb-editor-')),
}
})
check('编辑器浮层可见', opened.display === 'flex' && opened.position === 'fixed')
check('样式注入生效(CSP unsafe-inline)', opened.styleInjected)
check('浮层压住宿主 UI', Number(opened.zIndex) >= 999998, 'z=' + opened.zIndex + ' bg=' + opened.bg)
// ---------- 4.5) 剪贴板粘贴:⌘V 把剪贴板图片贴为新图层 ----------
// 合成 ClipboardEvent(带 image/png File),粘贴应进入「图片放置」模式;回车确认后图层面板 +1 项。
// SKIP_PASTE=1 可跳过(隔离「粘贴」与「覆盖写回」两条链路的排查用)。
const SKIP_PASTE = process.env.SKIP_PASTE === '1'
if (!SKIP_PASTE) {
// 先画一个矢量矩形,制造「截图 + 图形」共存场景 —— 这是 z 撞车 / 排序按钮失效的复现前提
const imgBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
await page.mouse.move(imgBox.x + imgBox.width * 0.25, imgBox.y + imgBox.height * 0.25)
await page.mouse.down()
await page.mouse.move(imgBox.x + imgBox.width * 0.75, imgBox.y + imgBox.height * 0.75, { steps: 8 })
await page.mouse.up()
await page.waitForTimeout(200)
const layersBefore = await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length)
await page.evaluate((png) => {
const bin = atob(png.split(',')[1])
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
const dt = new DataTransfer()
dt.items.add(new File([bytes], 'paste.png', { type: 'image/png' }))
document.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }))
}, PNG)
await page.waitForTimeout(800) // FileReader → loadImage → 进入放置模式
await page.keyboard.press('Enter') // 确认放置 → 落层
const pasted = await poll(async () => page.evaluate((n) => document.querySelectorAll('.iwb-editor-layer-list > *').length > n, layersBefore))
check('⌘V 粘贴剪贴板图片 → 确认后图层面板 +1', Boolean(pasted), '图层项 ' + layersBefore + ' → ' + await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length))
// ---------- 4.6) 图层顺序回归(2026-11-04 修):z 唯一 / 选中唯一 / 四个排序按钮 ----------
const panelSeq = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-editor-layer-list .iwb-layer-item'))
.map((n) => n.querySelector('.iwb-layer-name')?.textContent).join(' > '))
const activeCount = () => page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list .iwb-layer-item.active').length)
check('图层面板只有一个选中项(画笔目标改用 ✎ 标记)', (await activeCount()) === 1,
'active=' + await activeCount() + ' / ' + await panelSeq())
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
await page.mouse.click(imgBox.x + imgBox.width * 0.5, imgBox.y + imgBox.height * 0.5)
await page.waitForTimeout(150)
const activeItem = await page.evaluate(() => {
const n = document.querySelector('.iwb-editor-layer-list .iwb-layer-item.active')
return n && { type: n.dataset.layerType, name: n.querySelector('.iwb-layer-name')?.textContent }
})
check('点击「截图+图形」重叠区选中最上层截图(不被下方图形抢走)',
Boolean(activeItem && activeItem.type === 'bitmap' && /图层/.test(activeItem.name)), JSON.stringify(activeItem))
// v1.13 起顶栏四个层级按钮已删除(改为图层拖动 + Ctrl+]/[ 快捷键),
// 这里改为断言「按钮确实没了」+ 用快捷键验证排序仍然可用。
check('顶栏不再有层级排序按钮(改用图层拖动 + Ctrl+]/[)',
(await page.locator('.iwb-editor-layer-btn').count()) === 0 &&
(await page.locator('.iwb-editor-header .iwb-editor-commands').count()) === 0,
'layerBtn=' + await page.locator('.iwb-editor-layer-btn').count())
// v1.18(用户 2026-11-10):撤销 / 重做 / 还原 从顶栏搬到工具条最右,
// 「适应窗口 / 收起侧栏」退到它前面两位。这里断言「末尾是撤销组、视图按钮在其前」
// —— 光看版本号挡不住产物没重建。
const toolsOrder = await page.evaluate(() => {
const kids = Array.from(document.querySelectorAll('.iwb-editor-tools > *'))
const acts = kids.filter((n) => n.dataset && n.dataset.action).map((n) => n.dataset.action)
const hist = kids[kids.length - 1]
return {
tail: acts.slice(-2),
lastIsHistory: Boolean(hist && hist.classList.contains('iwb-editor-history')),
histActs: [...(hist ? hist.querySelectorAll('[data-action]') : [])].map((b) => b.dataset.action),
headerHasHistory: Boolean(document.querySelector('.iwb-editor-header .iwb-editor-history')),
}
})
check('工具栏最右是「撤销/重做/还原」组(视图按钮在其前)',
JSON.stringify(toolsOrder.tail) === JSON.stringify(['zoomFit', 'togglePanels']) &&
toolsOrder.lastIsHistory && toolsOrder.histActs.join(',') === 'undo,redo,reset' &&
!toolsOrder.headerHasHistory, JSON.stringify(toolsOrder))
const before = await panelSeq()
const activeName = await page.evaluate(() => document.querySelector('.iwb-editor-layer-list .iwb-layer-item.active .iwb-layer-name')?.textContent)
await page.keyboard.press('Control+[') // 下移一层
const afterDown = await panelSeq()
check('Ctrl+[ 下移一层改变图层顺序', before !== afterDown, before + ' → ' + afterDown)
await page.keyboard.press('Control+]') // 上移一层
check('Ctrl+] 上移一层恢复原顺序', (await panelSeq()) === before, await panelSeq())
await page.keyboard.press('Control+Shift+[') // 置底
const afterBottom = await panelSeq()
check('Ctrl+Shift+[ 置底生效(元素不会消失)',
afterBottom !== before && afterBottom.endsWith(String(activeName)), afterBottom)
check('置底后原图不再被钉在最底 —— 图层可以压到原图下面(v1.13 解封)',
!afterBottom.endsWith('原图'), afterBottom)
await page.keyboard.press('Control+Shift+]') // 置顶
check('Ctrl+Shift+] 置顶生效', (await panelSeq()) !== afterBottom, await panelSeq())
check('排序后仍只有一个选中项', (await activeCount()) === 1, 'active=' + await activeCount())
// v1.15 图片调节:真站确认面板存在、11 项按参数表生成(DOM 由 adjust.js 生成,
// 构建时漏带就会是 0 行 —— 这类「打包产物缺模块」只有真站能发现)
const adjRowCount = await page.locator('.iwb-editor-adj-row').count()
const adjNames = await page.locator('.iwb-editor-adj-name').allTextContents()
check('右侧栏「图片调节」11 项齐全',
adjRowCount === 11 && adjNames.join('/') === '曝光/明度/对比度/阴影/高光/色相/饱和度/温度/色调/锐度/清晰度',
'rows=' + adjRowCount + ' ' + adjNames.join('/'))
check('调节面板认到了作用层(不是「无图层」)',
(await page.locator('.iwb-editor-adj-target').textContent()) !== '无图层',
await page.locator('.iwb-editor-adj-target').textContent())
// v1.19:右栏常驻调色面板已删(用户 2026-11-10),颜色只剩工具栏弹层一处。
// 真站里 DOM 与 CSS 分别打包,这里同时验「右栏干净」和「弹层头部一行 / 16 色 8 列」——
// 样式漏打包时,头部会退回竖排或色块掉成 6 列,这条会直接露出来。
const sideColor = await page.evaluate(() => ({
hasSide: Boolean(document.querySelector('.iwb-editor-left [data-color-surface]')),
firstSection: (document.querySelector('.iwb-editor-left > section') || {}).className || '',
}))
check('右栏调色模块已删(第一个模块是图片调节)',
sideColor.hasSide === false && /iwb-editor-adj/.test(sideColor.firstSection),
JSON.stringify(sideColor))
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
await page.waitForTimeout(240)
const popShape = await page.evaluate(() => {
const pop = document.querySelector('.iwb-editor-color-pop')
if (!pop) return null
const r = (el) => el.getBoundingClientRect()
const head = r(pop.querySelector('.iwb-color-pop-head'))
const items = [pop.querySelector('[data-action="palettePick"]'),
pop.querySelector('.iwb-editor-color-hex-input'),
pop.querySelector('[data-action="pinColorPop"]')].map((el) => {
const b = r(el)
return { c: b.top + b.height / 2, l: b.left, r: b.right }
})
const sw = [...pop.querySelectorAll('.iwb-editor-color-swatches [data-panel-color]')]
const grid = pop.querySelector('.iwb-editor-color-swatches')
return {
w: Math.round(r(pop).width),
sameRow: items.every((it) =>
Math.abs(it.c - (head.top + head.height / 2)) < 3 && it.l >= head.left - 1 && it.r <= head.right + 1),
common: sw.length,
cols: new Set(sw.map((b) => Math.round(r(b).left))).size,
swatch: sw.length ? Math.round(r(sw[0]).width) : 0,
// v1.20:去色占常用色第一格(20px 同尺寸、第一排最左)
noneFirst: grid.children[0] === pop.querySelector('[data-color-none]'),
cells: grid.children.length,
}
})
check('色板弹层:头部一行(吸管 / 色值 / 图钉同排)+ 去色占常用色第一格 + 15 色 8 列',
Boolean(popShape) && popShape.sameRow && popShape.noneFirst && popShape.cells === 16 &&
popShape.common === 15 && popShape.cols === 8 && popShape.swatch === 20 && popShape.w === 440,
JSON.stringify(popShape))
await page.keyboard.press('Escape')
await page.waitForTimeout(140)
const sideBefore = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width))
const sideGrip = await page.locator('.iwb-editor-side-resizer').boundingBox()
if (sideGrip) {
await page.mouse.move(sideGrip.x + 3, sideGrip.y + 120)
await page.mouse.down()
await page.mouse.move(sideGrip.x + 3 - 70, sideGrip.y + 120, { steps: 6 })
await page.mouse.up()
await page.waitForTimeout(180)
}
const sideAfter = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width))
check('右栏可以拖宽(不再固定 220)', sideAfter >= sideBefore + 60, sideBefore + ' → ' + sideAfter)
await page.locator('.iwb-editor-side-resizer').dblclick()
await page.waitForTimeout(150)
// v1.17:描边可以是「无色」。真站要验的是按钮真的出现在描边槽、点完对象上真的关了,
// 而不只是 CSS 里多了个类 —— 形状消失与否只有跑起来才知道。
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
await page.mouse.move(imgBox.x + imgBox.width * 0.12, imgBox.y + imgBox.height * 0.12)
await page.mouse.down()
await page.mouse.move(imgBox.x + imgBox.width * 0.30, imgBox.y + imgBox.height * 0.30, { steps: 6 })
await page.mouse.up()
await page.waitForTimeout(250)
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
await page.mouse.click(imgBox.x + imgBox.width * 0.21, imgBox.y + imgBox.height * 0.21)
await page.waitForTimeout(200)
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
await page.waitForTimeout(250)
const noneOnStroke = await page.evaluate(() => {
const n = document.querySelector('.iwb-editor-color-pop [data-color-none]')
// v1.20:去色不再 hidden,改用 disabled 表达「这个上下文不能去色」
return Boolean(n) && Boolean(n.offsetParent) && !n.disabled
})
await page.evaluate(() => document.querySelector('.iwb-editor-color-pop [data-color-none]').click())
await page.waitForTimeout(300)
const noStrokeState = await page.evaluate(() => {
const d = window.__iwbEditor.__debug()
const s = d.shapes.find((x) => x.id === d.selectedShapeId)
return s ? { strokeOn: s.strokeOn, fill: s.fill } : null
})
check('真站:描边能置「无」(去掉描边顺手切实心,对象不会消失)',
noneOnStroke && Boolean(noStrokeState) && noStrokeState.strokeOn === false && noStrokeState.fill === true,
JSON.stringify({ noneOnStroke, noStrokeState }))
await page.keyboard.press('Escape')
await page.waitForTimeout(120)
// v1.14 字体选择:真站是带 CSP 的环境,这里确认下拉可用、字体切换真的落到了对象上。
// 系统字体不受 CSP 约束(CSP 管的是网络字体),所以只要 canvas 能画就没问题。
const famDbg = () => page.evaluate(() => window.__iwbEditor.__debug())
const FAM_SEL = '.iwb-editor-optionbar-body select[data-opt-text="fontFamily"]'
await page.locator('.iwb-editor-tool[data-tool="text"]').click()
const famBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
await page.mouse.click(famBox.x + 60, famBox.y + 60)
await page.waitForTimeout(300)
await page.evaluate(() => {
const el = document.querySelector('.iwb-editor-text-input')
if (!el) return
el.focus()
el.value = '字体测试'
el.dispatchEvent(new Event('input', { bubbles: true }))
})
await page.keyboard.press('Enter')
await page.waitForTimeout(400)
const famOpts = await page.locator(FAM_SEL + ' option').allTextContents()
check('真站选项栏出现字体下拉,四档:黑体 / 宋体 / 楷体 / 圆体',
famOpts.length === 4, JSON.stringify(famOpts))
const wSans = ((await famDbg()).texts.find((t) => t.text === '字体测试') || {}).box
await page.selectOption(FAM_SEL, 'serif')
await page.waitForTimeout(320)
const tSerif = (await famDbg()).texts.find((t) => t.text === '字体测试')
check('真站切换宋体生效,且中文宽度不变(全角等宽,版面不跳动)',
Boolean(tSerif && tSerif.fontFamily === 'serif' && wSans && Math.abs(tSerif.box.w - wSans.w) <= 1),
(wSans ? wSans.w : '?') + ' → ' + (tSerif ? tSerif.box.w : '?'))
await page.keyboard.press('Delete')
await page.waitForTimeout(200)
// 复原成画笔工具,避免影响后面「覆盖」链路的画笔取样
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
}
// ---------- 4.7) v1.1:选区 / 单层 Delete / 还原原图 / ≤500KB 预设 ----------
const dbg = () => page.evaluate(() => window.__iwbEditor.__debug())
const v11Box = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
await page.locator('.iwb-editor-tool[data-tool="marquee"]').click()
await page.mouse.move(v11Box.x + v11Box.width * 0.25, v11Box.y + v11Box.height * 0.25)
await page.mouse.down()
await page.mouse.move(v11Box.x + v11Box.width * 0.7, v11Box.y + v11Box.height * 0.7, { steps: 8 })
await page.mouse.up()
await page.waitForTimeout(150)
const v11sel = (await dbg()).selection
check('v1.1 框选 + 浮动操作条出现', Boolean(v11sel && v11sel.w > 5 && v11sel.h > 5) &&
await page.locator('.iwb-editor-sel-bar').isVisible(), JSON.stringify(v11sel))
const v11px = (x, y) => page.evaluate(({ px, py }) => {
const d = window.__iwbEditor.__debug()
// 1.2.1 起默认没有 id='draw' 的预建层:填充落进「当前活动层」,
// 所以这里读活动层像素而不是写死 'draw'
return { base: d.pixel('base', px, py), draw: d.pixel(d.activeLayerId, px, py), activeId: d.activeLayerId }
}, { px: x, py: y })
const vcX = Math.round(v11sel.x + v11sel.w / 2)
const vcY = Math.round(v11sel.y + v11sel.h / 2)
const v11before = await v11px(vcX, vcY)
await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.fill"]').click()
await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.delete"]').click()
const v11after = await v11px(vcX, vcY)
check('v1.1 Delete 只清当前层(base 像素原样)',
v11after.draw[3] === 0 && JSON.stringify(v11after.base) === JSON.stringify(v11before.base),
'draw=' + JSON.stringify(v11after.draw) + ' base=' + JSON.stringify(v11after.base))
await page.keyboard.press('Control+z')
const v11layersBeforeReset = (await dbg()).layers.length
await page.locator('[data-action="reset"]').click()
check('v1.1 还原原图=只剩原图单层(1.2.1 起不预建画笔层)', (await dbg()).layers.length === 1, JSON.stringify((await dbg()).layers))
await page.keyboard.press('Control+z')
check('v1.1 还原原图可 Ctrl+Z 撤销', (await dbg()).layers.length === v11layersBeforeReset,
'层数 ' + v11layersBeforeReset + ' → 2 → ' + (await dbg()).layers.length)
await page.locator('[data-action="toggleExportSettings"]').click()
await page.locator('[data-export-key="preset"][data-export-value="ecom800"]').click()
check('v1.1 ≤500KB 输出预设可切换', (await dbg()).exportOptions.maxKB === 500,
JSON.stringify((await dbg()).exportOptions))
await page.locator('[data-export-key="preset"][data-export-value="original"]').click()
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
// ---------- 5) 覆盖:回写真机画布 ----------
await page.mouse.move(400, 300)
await page.mouse.down()
await page.mouse.move(760, 520, { steps: 8 })
await page.mouse.up()
await page.locator('[data-action="replace"]').click()
const replaced = await poll(async () => page.evaluate((orig) => {
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
const n = (ws.nodes || []).find((x) => x.id === 'r1')
if (!n) return false
const v = n.data && (typeof n.data.data === 'string' ? n.data.data : (n.data.data && (n.data.data.__blob || JSON.stringify(n.data.data))))
return (ws.nodes.length === 1 && v && v !== orig) ? { nodes: ws.nodes.length, changed: true } : false
}, PNG))
check('「覆盖」写回原节点(节点数不变、内容已变)', Boolean(replaced), JSON.stringify(replaced))
check('编辑器导出后关闭', (await page.locator('#iwb-editor-overlay').isVisible().catch(() => false)) === false)
// ---------- 6) 新建:真机画布新增节点 ----------
await openEditor()
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
await page.locator('[data-action="newNode"]').click()
const created = await poll(async () => page.evaluate(() => {
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
return (ws.nodes || []).length === 2 ? { nodes: 2 } : false
}))
check('「新建」在真机画布新增节点', Boolean(created), JSON.stringify(created))
await page.locator('.iwb-canvas').waitFor({ state: 'visible' })
check('画布渲染出 2 个节点', (await page.locator('.iwb-node').count()) === 2)
// ---------- 7) 无 CSP / 运行时错误 ----------
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
File diff suppressed because it is too large. Load diff
+167
View File
@@ -0,0 +1,167 @@
# 位图转矢量(image-vectorize)
把节点的位图描摹成矢量,输出 SVG 或 PNG 节点。引擎是 **potrace**(Peter Selinger 的二值轮廓算法,
这里用它的 JS 移植 `[email protected]`,GPL-2.0)—— 和 Inkscape「位图转矢量」同一个内核。
## 为什么换了引擎(v0.1 → v0.2,2026-11-05)
v0.1 用 VTracer(彩色分层 + 样条拟合,wasm)。实测在文字图上:**中文笔画断裂、抗锯齿边缘起毛刺、
浅色块碎成多层** —— 用户的原话是「看着变矢量了但没法用」,当天就下线了。
v0.2 换 potrace,并且按用户要求**只做单色 / 灰度**(不做彩色):
| 维度 | VTracer(v0.1) | potrace(v0.2) |
|---|---|---|
| 文字保形 | 笔画会断 | 笔画完整(二值轮廓追踪不猜颜色) |
| 毛刺 | 参数调不掉,得先降采样模糊 | `turdSize` 直接吃掉小于 N 像素的碎片 |
| 颜色 | 彩色分层(也是碎层根源) | 单色 / 灰度 N 层,层数可控 2–5 |
| 依赖 | wasm ⇒ 要放宽 CSP `'wasm-unsafe-eval'` | **纯 JS ⇒ 不动 CSP** |
| 体积 | 238KB(wasm base64 内联) | **116KB** |
## 功能
- 三个预设:文字 / 线稿(单色)、菜单 / 图文(灰度 3 层)、抠图轮廓(单色 + 强去毛刺)
- 描摹方式:**灰度分层**(层数 2–5)/ **纯单色**
- 参数:**去小点**(turdSize)、**边缘**(硬朗 / 标准 / 圆润 → alphaMax)、
**精度**(精细 / 标准 / 轻量 → optTolerance 0.05 / 0.15 / 0.4,默认精细)
- 高级(**默认展开**):阈值(自动 / 手动)、反相(黑底白字用负片)、**填充 / 背景色**(同一排,
背景默认白)+「带底」勾选(决定背景色是否写进导出)
- **按孤岛拆分**(默认开):每个连通块输出为一个独立 `<path>` 元素,粘到 Figma 就是多个
可单独选中的图层;关掉则整图合并成一个 path(便于整体缩放/移动)
- 预览:按住空格对比原图;**滚轮/捏合缩放、左键拖动平移、双击复位**(0.2×–8×);面板显示元素数 / 层数 / 体积 / 耗时
- 顶栏按钮(左 → 右):**保存为节点** · **复制 SVG** · **下载 SVG** · 取消(四颗统一描边配色,不用绿色主按钮)
- **保存为节点**:PNG,按输出倍率 1–4× 从矢量重绘后写回画布
- **复制 SVG**:写 `image/svg+xml` + `text/html` + `text/plain` 三种剪贴板口味,
Figma / Illustrator 粘进去就是真矢量
- **下载 SVG**:存成文件
## 按孤岛拆分(v0.3)
potrace 出厂把**整张图所有轮廓**塞进同一个 `<path>` 的 d 里(800×800 菜单图实测 1 个 path /
129 个子路径),靠 `fill-rule="evenodd"` 互相挖洞。所以复制/下载出来粘进 Figma 只是**一个整体**,
想单独挪一个字、一个色块都做不到 —— 这就是 v0.3 加这个开关的原因。
拆分依据不是「按 `M` 切」(那会把孔洞切成实心块,"O" 中间会被填满),而是**几何包含关系**:
```
外轮廓(depth 0) ⊃ 它的孔洞(depth 1) ⊃ 孔洞里的实心块(depth 2 = 另一个孤岛) ⊃ …
```
深度为偶数的轮廓是孤岛外壳,奇数是某个外壳的孔洞。每组(外壳 + 它的孔洞)合成**一个** path,
不同组之间是并列的 `<path>` 元素,不包 `<g>` —— Figma 导入时顶层并列的 path 就是可直接选中的
多个矢量图层,包一层组反而多一层要双击进去。
几个刻意的决定:
- **元素按面积降序输出**:大块先画、压在下层,和原图的遮挡关系一致
- **不改几何**:坐标集合与不拆分时完全一致(harness 有断言),差异只在抗锯齿边缘(实测 0.003%)
- **一个连通块 = 一个元素**:笔画不相连的汉字会分成几块(「三」是三横 = 3 个元素),
这是矢量软件的常态,不是描摹错
- **灰度分层 + 拆分会产生重叠**:每层都各描一遍整图,层与层本来就是你包我我包你,
拆开后同位置会有多个图层。想要干净分离就用「纯单色」,面板会提示
## 灰度分层为什么自己算阈值
上游 `Posterizer` 的 `steps` 传数字时会跑**直方图多级阈值搜索**,`steps: 5` 实测 **28 秒**(指数级),
不可用。这里改成自己算**等像素量分位**再以数组形式传进去(O(pixels)),5 层也只要几十毫秒。
两个必须处理的细节(`engine.js#quantileThresholds`,实测踩过):
1. **主背景色要排除在人口统计之外**。菜单图底色常占 60–80% 像素,不排除的话切点全落在背景里,
文字和背景还是分不开(等于白分层)。
2. **切点必须严格递增**。背景是巨大尖峰,多个切点会算出同一个亮度值 —— 去重后层数变少,
Posterizer 还会算出 0 透明度让整层消失。
## 背景色:默认白底预览,导出仍是透明(v0.3.1)
预览区原来是透明棋盘格,用户第一反应是「看着发虚、不知道图裁到哪」—— 描摹结果本来就是
「白纸上的单色图形」,所以 v0.3.1 起**预览直接铺白底**。背景色可自定义,和填充色放在同一排:
- **背景色只当预览底**:不参与轮廓计算,改它不会重新描摹(面板上的耗时/元素数都不动)
- **导出默认仍透明**:SVG 里没有背景矩形,粘到 Figma / Illustrator 不会凭空多一个底色图层。
想要导出也带底,勾旁边的「**带底**」,这时才在 `<svg>` 的第一个子元素位置插
`<rect width="100%" height="100%" fill="…">`
- 插背景放在**孤岛拆分之后**:拆分只解析 `<path>`,先拆再铺底,背景矩形既不影响元素统计,
也不会被当成一个孤岛
白底 + 白底稿(菜单、白底商品图)会看不出画面边界,所以预览图本身留了一圈 1px 极淡描边 +
细阴影;这是唯一一处「为了看清边界」而加的装饰。
## 预览缩放 / 平移(v0.4)
描摹结果要放大看细节(笔画接缝、圆角有没有被拟合成直线),所以预览区是一块可缩放画布:
| 操作 | 行为 |
|---|---|
| 鼠标滚轮 / 触控板捏合 | 以**光标位置为锚点**缩放(0.2×–8×) |
| 按住左键拖动 / 按住中键拖动 | 平移画布(100% 时也能拖) |
| 水平滚动(`Shift` + 滚轮也是这种) | 只平移,不改倍率 |
| 双击 / 点右下角「172% 复位」/ 按 `0` | 回到 100% 等比铺满 |
| `+` / `-` | 以画面中心缩放 |
三个实现上的取舍:
- **视图状态写进 `.vz-preview` 的 CSS 变量**(`--vz-zoom` / `--vz-pan-x` / `--vz-pan-y`),
由两张 `<img>`(矢量 + 原图)各自 `transform: var(...)` 引用。按住空格切原图时视图**纹丝不动** ——
要是每张图各存一份状态,切过去那一刻画面就会跳。harness 有断言锁这个行为。
- **锚点缩放**才有「指哪放大哪」的感觉。推导:图片中心恒在「预览区中心 + pan」,屏幕点 P 的图上偏移
`d = (P − C − pan) / zoom`,要让 P 不动需 `pan′ = pan + d·(zoom − zoom′)`。
- **滚轮一律缩放,不猜设备**。第一版想区分「鼠标滚轮 vs 触控板双指滑动」,判定条件写成
「`deltaY` 是 ±100 这类整数且 ≥48」—— 结果鼠标开着平滑滚动、或高精度滚轮给小数步长时,
滚轮被当成双指滑动,表现成**拖图不放大**(用户实测踩到)。现在只按主导轴分:
垂直 → 缩放,水平 → 平移。步长按幅度分两档(≥40 用 0.0018,细碎小数用 0.012),
让鼠标一格约 1.2×、触控板小步也跟手。
布局上 `.vz-stage` 从 flex 居中改成 `position: absolute` + `translate(-50%, -50%)`:
缩放锚点要求元素的变换中心稳稳落在预览区正中,flex 居中下图片尺寸一变中心就会漂。
## 复制到剪贴板为什么写三种口味
剪贴板不像文件,只有一个「格式」——它同时可以装多份不同 MIME 的数据,读的一方自己挑。
Figma 认 `image/svg+xml`(或 `text/html` 里的 `<svg>`)当**矢量**,只认 `text/plain` 的软件
(某些编辑器)则退化成一段 SVG 源码。所以一次写入三种口味,谁挑哪个都能用。
Chrome 对可写 MIME 有白名单,**塞了不支持的类型会让整次 `write()` 失败**(不是忽略那一种),
所以先用 `ClipboardItem.supports()` 探测,失败再逐级降级到 `writeText()`。
## 许可
potrace 与其 JS 移植都是 **GPL-2.0**(见 `plugin/vendor/potrace/LICENSE`)。当前用途是**自己用、
不商用**:GPL 的义务由「分发」触发,自用不触发;且本插件产物是**未混淆的单文件可读源码**
(`src/index.js` 既是产物也是源码),即使哪天对外提供,源码是随附的。
若将来要商用/闭源分发,换 MIT 的等价实现,或按 GPL 开源该插件。
## 开发
```bash
npm run build -- image-vectorize # plugin/ → src/index.js(esbuild IIFE)
npm run validate # 契约校验
node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,64 项)
node image-vectorize/tools/e2e-site.mjs # 桌面客户端端到端(市场安装 / SRI / CSP / 真实画布桥)
# 拿真实素材调参数(不进 CI,最快看到效果):
node image-vectorize/tools/trace-cli.mjs ~/Desktop/menu.png --mode gray --levels 3
node image-vectorize/tools/trace-cli.mjs ~/Desktop/logo.png --mode mono --turd 8 --tol 0.05
node image-vectorize/tools/trace-cli.mjs ~/Desktop/logo.png --mode mono --no-split # 看合并版
# → 产物 SVG + 一张「原图 / 结果」对比图(~-/tmp/vz-cli/)
```
发布:本仓只产出 `src/index.js`(构建产物),发布走桌面仓的市场链路,见根 README「发布到市场」:
```bash
npm run build -- image-vectorize && npm run validate
# 桌面仓:node scripts/sync-plugins-from-repo.js && node scripts/gen-market.js
# 再把 market/ 上传到 NAS(market.maqiart.eu.org)
```
改版本时同步 `package.json` 的 `version`(构建时注入 manifest)与桌面仓同步脚本读取的版本。
## 已知限制
- **照片不适合**:potrace 只懂明暗,照片会被压成几块灰阶(这不是 bug,是算法定位)
- 小字号(<24px)文字描摹后仍会变形;灰度模式可缓解(把浅色笔画留在单独一层)
- 超过 3000px 的图自动降到 3000px 再描摹(实测单色 3200px 96ms、灰度 4 层 3000px 179ms;
3600px 起跳到 389ms,所以 3000 是「细节不掉、又不卡主线程」的交点)
- 灰度模式的「灰」是 `fill-opacity` 叠出来的(不是多条不同色 path),所以 SVG 里只有一种 fill 色
- 拆分后元素可能很多(灰度 3 层的菜单图实测 281 个),Figma 导入会慢一点;
单色通常是 10–100 个,最实用
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/image-vectorize",
"private": true,
"version": "0.6.1",
"description": "位图转矢量:potrace(纯 JS)单色/灰度描摹,输出 SVG 与 PNG 节点;对文字、logo、线稿保形好,不需要 wasm",
"ibwPlugin": {
"id": "image-vectorize",
"entry": "src/index.js",
"apiVersion": 1
}
}
+220
View File
@@ -0,0 +1,220 @@
/**
* 描摹引擎:potrace(纯 JS,GPL-2.0)—— 单色 / 灰度分层。
*
* 为什么换成 potrace(2026-11-05 用户裁定后的第二版):
* 上一版用 VTracer(彩色分层 + 样条拟合),文字图上会**断笔画、起毛刺、浅色块碎层**,
* 用户实测「看着变矢量但没法用」。potrace 是「二值轮廓追踪 + 曲线拟合」:
* 对 hard edge(文字、logo、线稿)的保形性明显更好,且 turdSize 天生能吃掉小毛刺。
* 代价是它只懂明暗(不懂颜色),所以只做**单色**与**灰度分层**——
* 用户明确说了「单色/灰度就够」,不再做彩色。
*
* 纯 JS ⇒ 不需要 wasm,**不需要宿主放宽 CSP**(上一版为此加过 'wasm-unsafe-eval',
* 下线时已收回;本版不要再动 CSP)。
*
* 灰度分层为什么自己算阈值:上游 Posterizer 的 `steps` 传数字时会走直方图多级阈值搜索,
* `steps: 5` 实测 28 秒(指数级),完全不可用。改为自己用**等像素量分位**算好阈值数组
* 直接传进去(O(pixels)),5 层也只要几十毫秒。
*/
'use strict'
import Potrace from './vendor/potrace/Potrace.js'
import Posterizer from './vendor/potrace/Posterizer.js'
import { countIslands, splitSvgIslands } from './islands.js'
export const MODES = ['gray', 'mono']
export const LEVELS_MIN = 2
export const LEVELS_MAX = 5
/**
* 描摹上限边(超过就降采样)。potrace 是纯 JS 单线程,实测:
* 单色 3200px 96ms、灰度 4 层 3000px 179ms(3600px 已跳到 389ms,内存压力明显)。
* 所以取 3000 —— 菜单/详情页这类大图的细节不再被降采样吃掉,同时仍在该帧内完成。
*/
export const MAX_TRACE_SIDE = 3000
export const DEFAULTS = {
mode: 'gray', // 'gray' 灰度分层 / 'mono' 纯单色
levels: 3, // 灰度层数(2–5,仅 gray)
threshold: -1, // -1 = 自动(两种模式都支持)
turdSize: 3, // 去小点:面积小于它的碎片直接丢(毛刺/噪点克星)
alphaMax: 1, // 拐角阈值:0 全折线、1 默认、1.334 最圆
// 曲线拟合容差(越小越贴合原图像素边缘,路径数据也越大)。
// 上游默认 0.2 是「视觉上够用」的省数据值;实测 0.2 在文字笔画与圆角处会
// 吃掉约半个像素的弯折,所以这里默认降到 0.05(用户 2026-11-05 要求「边缘精度再高一点」)。
optTolerance: 0.05,
invert: false, // 反相:描摹亮部(黑底白字场景)
color: '#1a1a1a', // mono 的填充色
// 背景色:默认白 —— 预览区直接铺白纸,不铺透明棋盘(用户 2026-11-05 要求)。
// 它**默认只当预览底**,导出仍是透明 SVG(粘到 Figma 不会多一个背景图层);
// 想要导出也带底,用户勾「带底」(bgExport)即可。
bg: '#ffffff',
bgExport: false,
outScale: 1, // 输出尺寸倍率(只放大尺寸,不重算曲线)
// 按孤岛拆分:potrace 出厂把整图所有轮廓塞进一个 path,粘到 Figma 只是一个整体;
// 拆开后每个不连通的图形都是独立 path,可以单独选中/移动(用户 2026-11-05 要求)。
// 默认开 —— 需求来源就是「现在是一个整体,我想分开」。
splitIslands: true,
}
/** 曲线精度三档(UI 用):越大越省路径数据,越小越贴合像素 */
export const TOLERANCE_TONES = { fine: 0.05, normal: 0.15, light: 0.4 }
const clampInt = (v, min, max, dflt) => {
const n = Math.round(Number(v))
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt
}
/** 把 UI / 记忆里的松散参数收敛成引擎能吃的确定值 */
export function normalizeParams(p) {
const src = p || {}
return {
mode: src.mode === 'mono' ? 'mono' : 'gray',
levels: clampInt(src.levels, LEVELS_MIN, LEVELS_MAX, DEFAULTS.levels),
threshold: Number(src.threshold) >= 0 ? clampInt(src.threshold, 0, 255, 128) : -1,
turdSize: clampInt(src.turdSize, 0, 64, DEFAULTS.turdSize),
alphaMax: (() => {
const n = Number(src.alphaMax)
return Number.isFinite(n) ? Math.min(1.334, Math.max(0, n)) : DEFAULTS.alphaMax
})(),
optTolerance: (() => {
const n = Number(src.optTolerance)
return Number.isFinite(n) ? Math.min(2, Math.max(0.01, n)) : DEFAULTS.optTolerance
})(),
invert: Boolean(src.invert),
color: /^#[0-9a-f]{6}$/i.test(String(src.color || '')) ? String(src.color) : DEFAULTS.color,
bg: /^#[0-9a-f]{6}$/i.test(String(src.bg || '')) ? String(src.bg) : DEFAULTS.bg,
bgExport: src.bgExport === undefined ? DEFAULTS.bgExport : Boolean(src.bgExport),
outScale: Math.min(4, Math.max(1, Number(src.outScale) || 1)),
splitIslands: src.splitIslands === undefined ? DEFAULTS.splitIslands : Boolean(src.splitIslands),
}
}
/**
* 等像素量分位阈值:把亮度直方图按像素数切成 levels 段,返回 levels-1 个切点。
*
* 两个必须处理的坑(实测,不是理论问题):
* 1. **主背景色要排除在人口统计之外**。电商图/菜单图里底色常占 60–80% 像素,
* 不排除的话三个切点里有两个会落在背景里,文字还是跟背景分不开(等于没分层)。
* 2. **切点必须严格递增**。背景是一个巨大的尖峰,多个切点会算出同一个亮度值,
* 去重后层数变少(Posterizer 还会算出 0 透明度,整层消失)。
*/
function quantileThresholds(imageData, levels) {
const hist = new Uint32Array(256)
const data = imageData.data
let total = 0
for (let i = 0; i < data.length; i += 4) {
const a = data[i + 3] / 255
// 与 potrace 内部一致:透明按白底合成后再算亮度
const r = 255 + (data[i] - 255) * a
const g = 255 + (data[i + 1] - 255) * a
const b = 255 + (data[i + 2] - 255) * a
hist[Math.round(0.299 * r + 0.587 * g + 0.114 * b)]++
total++
}
if (!total) return []
// 1) 排除主背景峰(最常见的那个亮度)
let bg = 0
let bgCount = 0
for (let v = 0; v < 256; v++) if (hist[v] > bgCount) { bgCount = hist[v]; bg = v }
const counted = total - bgCount
// 内容太少(几乎纯色图)就退化成等间距,别硬分层
if (counted < total * 0.02) {
const out = []
for (let k = 1; k < levels; k++) out.push(Math.round((255 * k) / levels))
return out
}
// 2) 在「非背景」像素上取等量分位(背景 bin 当 0 处理,但仍参与 value 轴)
const saved = hist[bg]
hist[bg] = 0
const cuts = []
const per = counted / levels
let acc = 0
let next = per
for (let v = 0; v < 256 && cuts.length < levels - 1; v++) {
acc += hist[v]
while (acc >= next && cuts.length < levels - 1) {
cuts.push(v)
next += per
}
}
hist[bg] = saved
// 3) 强制严格递增 + 留出余量(相邻层差至少 1 个亮度级)
const out = []
for (const c of cuts) {
let v = c
if (out.length && v <= out[out.length - 1]) v = out[out.length - 1] + 1
if (v > 254) break
out.push(v)
}
return out
}
/**
* 描摹主入口(同步)。
* @param {{width:number,height:number,data:Uint8ClampedArray}} imageData
* @param {object} params
* @returns {{svg:string, ms:number, paths:number, levels:number}}
*/
export function traceImageData(imageData, params) {
const p = normalizeParams(params)
const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())
const t0 = now()
let svg = ''
let levels = 1
if (p.mode === 'mono') {
const potrace = new Potrace({
threshold: p.threshold >= 0 ? p.threshold : Potrace.THRESHOLD_AUTO,
turdSize: p.turdSize,
alphaMax: p.alphaMax,
optCurve: true,
optTolerance: p.optTolerance,
blackOnWhite: !p.invert,
color: p.color,
})
potrace.loadImageData(imageData)
svg = potrace.getSVG()
} else {
const cuts = quantileThresholds(imageData, p.levels)
levels = cuts.length + 1
const posterizer = new Posterizer({
// 传数组 ⇒ 跳过上游的直方图多级阈值搜索(那玩意 5 层要 28s)
steps: cuts.length ? cuts : [128],
threshold: p.threshold >= 0 ? p.threshold : Potrace.THRESHOLD_AUTO,
turdSize: p.turdSize,
alphaMax: p.alphaMax,
optCurve: true,
optTolerance: p.optTolerance,
blackOnWhite: !p.invert,
fillStrategy: 'median', // 灰度:每层取该层亮度中位数
color: '#000000', // 灰度靠 fill-opacity 叠出来,底色固定黑
})
posterizer.loadImageData(imageData)
svg = posterizer.getSVG()
}
// 拆分放在计时之内:用户看到的耗时应该包含这次操作的全部成本
let elements = (String(svg).match(/<path/g) || []).length
let islands = 0
if (p.splitIslands) {
const split = splitSvgIslands(svg)
svg = split.svg
elements = split.elements
islands = split.islands
} else {
islands = countIslands(svg) || elements
}
// 背景矩形放在拆分之后插:先拆(只解析 path),再铺底,
// 这样「带底」既不影响孤岛统计,也不会被拆分逻辑当成一个元素。
if (p.bgExport) {
svg = svg.replace(/<svg\b[^>]*>/i, function (tag) {
return tag + '\n<rect width="100%" height="100%" fill="' + p.bg + '"/>'
})
}
return { svg, ms: Math.round(now() - t0), paths: elements, elements, islands, levels }
}
+125
View File
@@ -0,0 +1,125 @@
/* 打包入口(esbuild → IIFE)。
*
* 数据流(全部走公开契约):
* nodeActions.run(node) → ctx.canvas.getNodeImage → createVectorizer().open({imageDataUrl})
* → 「保存为节点」→ PNG Blob → ctx.canvas.createImageNode
* → 「下载 SVG」→ 本地落盘(不进宿主)
*
* manifest 不放在这里:esbuild 的打印器会把单引号改写成双引号,而 scripts/validate.mjs
* 只认单引号。manifest 走 build-plugin.mjs 的 banner 通道,注册调用走 footer 通道。
*/
'use strict'
import vectorizeCss from './ui.css'
import { createVectorizer } from './ui.js'
import { loadImage } from './trace.js'
;(typeof window !== 'undefined' ? window : globalThis).__IWB_VECTORIZE_FACTORY__ = function (ctx) {
let styleInjected = false
function ensureStyle() {
if (styleInjected) return
try {
const style = document.createElement('style')
style.id = 'iwb-vectorize-style'
style.textContent = vectorizeCss
;(document.head || document.documentElement).appendChild(style)
styleInjected = true
} catch (error) {
ctx.log('vectorize-style-failed', error && error.message)
}
}
function blobToDataUrl(blob) {
return new Promise(function (resolve, reject) {
const reader = new FileReader()
reader.onload = function () { resolve(String(reader.result || '')) }
reader.onerror = function () { reject(reader.error || new Error('读取图片失败')) }
reader.readAsDataURL(blob)
})
}
// 取图:dataUrl 直接赋给 img.src(img-src 放行 data:,不污染画布);
// 远程 url 才走 fetch 转 blob:(data: URL 发请求会被 connect-src 拦,姊妹插件踩过这个坑)。
async function resolveImage(nodeId) {
const image = await ctx.canvas.getNodeImage(nodeId)
if (!image) throw new Error('该节点没有可描摹的图片')
if (image.dataUrl) return image.dataUrl
if (!image.url) throw new Error('该节点没有可描摹的图片')
let resp
try {
resp = await fetch(image.url)
} catch (error) {
throw new Error('远程图片无法读取(可能被跨域限制):请先转存为本地位图')
}
if (!resp.ok) throw new Error('远程图片无法读取(可能被跨域限制):请先转存为本地位图')
const blob = await resp.blob()
// 先确认能解码,避免把坏数据丢给 UI 才报错
const objectUrl = URL.createObjectURL(blob)
try {
await loadImage(objectUrl)
} finally {
URL.revokeObjectURL(objectUrl)
}
return blobToDataUrl(blob)
}
let active = null
async function runOne(node) {
if (!node || !node.id) throw new Error('请先选中一个带图的节点')
ensureStyle()
const imageDataUrl = await resolveImage(node.id)
if (active) { try { active.close() } catch (e) { /* 上一个窗口可能已关闭 */ } }
return new Promise(function (resolve, reject) {
let settled = false
const settle = function (fn) { if (!settled) { settled = true; fn() } }
active = createVectorizer({
settings: ctx.settings,
onSaveNode: async function (blob, name) {
const dataUrl = await blobToDataUrl(blob)
const created = ctx.canvas.createImageNode({ dataUrl: dataUrl, name: name })
if (!created) throw new Error('写回画布失败')
ctx.log('vectorize: ' + name + ' ' + Math.round(blob.size / 1024) + 'KB')
settle(function () { resolve(name) })
},
onClose: function () {
active = null
settle(function () { resolve('cancel') })
},
onError: function (message) {
settle(function () { reject(new Error(String(message || '描摹失败'))) })
},
})
Promise.resolve(active.open({ imageDataUrl: imageDataUrl, name: node.name })).catch(function (error) {
active = null
settle(function () { reject(error) })
})
})
}
ctx.nodeActions.register({
id: 'vectorize-node',
title: '位图转矢量',
icon: 'pen-tool',
appliesTo: function (node) { return Boolean(node) && node.type === 'ref' },
run: function (node) { return runOne(node) },
})
ctx.commands.register({
id: 'vectorize-selected',
title: '位图转矢量:选中节点',
icon: 'pen-tool',
run: function () {
const selected = ctx.canvas.getSelectedNode()
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
return runOne(selected)
},
})
return {}
}
+276
View File
@@ -0,0 +1,276 @@
/**
* 孤岛拆分:把 potrace 输出的「一个复合 path」拆成「一个孤岛一个 path 元素」。
*
* 为什么需要(用户 2026-11-05 提的需求):
* potrace 把**整张图所有轮廓**塞进同一个 `<path>` 的 d 里(实测 800×800 菜单图是
* 1 个 path / 129 个子路径,靠 `fill-rule="evenodd"` 互相挖洞)。所以复制或下载出来的
* SVG,粘到 Figma 里只是**一个整体**,想单独挪一个字、一个色块都做不到。
*
* 为什么不能按 `M` 直接切:切开会把孔洞变成实心块 —— "O" 的中间会被填满。
* 正确的分组依据是**几何包含关系**:
* 外轮廓(depth 0) ⊃ 它的孔洞(depth 1) ⊃ 孔洞里的实心块(depth 2,另一个孤岛) …
* 所以「深度为偶数」的轮廓是孤岛的外壳,「深度为奇数」的是某个外壳的孔洞。
* 每组 = 一个外壳 + 它下面所有深度更深的子孙,合成**一个** path(孔洞必须跟外壳同
* path,evenodd 才能挖出洞);不同组之间是并列的 `<path>` 元素。
*
* 只认 potrace 实际输出的命令集(M / C / L / Z,全绝对坐标,见 vendor/potrace/utils.js
* 的 renderCurve)。不做通用 SVG 解析 —— 那是另一件事,别在这里长成半成品解析器。
*/
'use strict'
const TOKEN = /[MLCZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi
const EPS = 1e-6
/** 三次贝塞尔采样(不含起点、含终点):够给「点在轮廓内」判定用 */
function sampleCubic(poly, p0, p1, p2, p3) {
const steps = 4
for (let k = 1; k <= steps; k++) {
const t = k / steps
const mt = 1 - t
const a = mt * mt * mt
const b = 3 * mt * mt * t
const c = 3 * mt * t * t
const d = t * t * t
poly.push([
a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0],
a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1],
])
}
}
function bboxOf(poly) {
let x0 = Infinity
let y0 = Infinity
let x1 = -Infinity
let y1 = -Infinity
for (let i = 0; i < poly.length; i++) {
const p = poly[i]
if (p[0] < x0) x0 = p[0]
if (p[0] > x1) x1 = p[0]
if (p[1] < y0) y0 = p[1]
if (p[1] > y1) y1 = p[1]
}
return { x0, y0, x1, y1 }
}
/** 有向面积(鞋带公式);这里只用绝对值做「谁包着谁」的粗排 */
function shoelace(poly) {
let sum = 0
for (let i = 0, n = poly.length; i < n; i++) {
const a = poly[i]
const b = poly[(i + 1) % n]
sum += a[0] * b[1] - b[0] * a[1]
}
return sum / 2
}
function bboxContains(outer, inner) {
return inner.x0 >= outer.x0 - EPS && inner.x1 <= outer.x1 + EPS &&
inner.y0 >= outer.y0 - EPS && inner.y1 <= outer.y1 + EPS
}
/** 射线法:点是否在折线多边形内 */
function pointInPoly(pt, poly) {
let inside = false
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const xi = poly[i][0]
const yi = poly[i][1]
const xj = poly[j][0]
const yj = poly[j][1]
if ((yi > pt[1]) !== (yj > pt[1]) && pt[0] < ((xj - xi) * (pt[1] - yi)) / (yj - yi) + xi) inside = !inside
}
return inside
}
/**
* 解析 d 为子路径数组。每个子路径带:原样 d 片段、采样折线、bbox、面积。
* @param {string} d
* @returns {Array<{d:string, poly:number[][], bbox:object, area:number}>}
*/
export function parseSubpaths(d) {
const tokens = String(d || '').match(TOKEN)
const subs = []
if (!tokens || !tokens.length) return subs
const isNum = (k) => k < tokens.length && !/^[MLCZ]$/i.test(tokens[k])
const at = (k) => (isNum(k) ? Number(tokens[k]) : NaN)
let cur = null
let last = [0, 0]
let i = 0
while (i < tokens.length) {
const tok = tokens[i]
const cmd = tok.length === 1 ? tok.toUpperCase() : ''
if (cmd === 'M') {
const x = at(i + 1)
const y = at(i + 2)
if (!Number.isFinite(x) || !Number.isFinite(y)) break
i += 3
cur = { d: 'M ' + x + ' ' + y, poly: [[x, y]] }
subs.push(cur)
last = [x, y]
continue
}
if (!cur) { i += 1; continue }
if (cmd === 'C') {
const p1 = [at(i + 1), at(i + 2)]
const p2 = [at(i + 3), at(i + 4)]
const p3 = [at(i + 5), at(i + 6)]
if (!p1.concat(p2, p3).every(Number.isFinite)) break
i += 7
cur.d += ' C ' + p1[0] + ' ' + p1[1] + ', ' + p2[0] + ' ' + p2[1] + ', ' + p3[0] + ' ' + p3[1]
sampleCubic(cur.poly, last, p1, p2, p3)
last = p3
continue
}
if (cmd === 'L') {
// renderCurve 的 CORNER 输出 `L p1 p2`:两个连续直线点(p1 是拐点、p2 是段落终点)
const p1 = [at(i + 1), at(i + 2)]
if (!Number.isFinite(p1[0]) || !Number.isFinite(p1[1])) break
const p2 = [at(i + 3), at(i + 4)]
if (Number.isFinite(p2[0]) && Number.isFinite(p2[1])) {
i += 5
cur.d += ' L ' + p1[0] + ' ' + p1[1] + ' ' + p2[0] + ' ' + p2[1]
cur.poly.push(p1, p2)
last = p2
} else {
i += 3
cur.d += ' L ' + p1[0] + ' ' + p1[1]
cur.poly.push(p1)
last = p1
}
continue
}
if (cmd === 'Z') { i += 1; cur.d += ' Z'; continue }
i += 1
}
const out = []
for (const s of subs) {
if (s.poly.length < 3) continue
const area = Math.abs(shoelace(s.poly))
if (!(area > EPS)) continue
s.bbox = bboxOf(s.poly)
s.area = area
out.push(s)
}
return out
}
/**
* 按几何包含把子路径分组,每组是一个「孤岛」(外壳 + 它的孔洞)。
* @returns {Array<{root:number, idxs:number[], area:number}>}
*/
export function groupSubpaths(subs) {
const n = subs.length
const parent = new Array(n).fill(-1)
const order = subs.map((s, i) => i).sort((a, b) => subs[b].area - subs[a].area)
for (let k = 0; k < n; k++) {
const ci = order[k]
// 已按面积降序,从近到远找第一个「bbox 包住且首点在内」的 —— 就是最小外壳
for (let j = k - 1; j >= 0; j--) {
const pi = order[j]
if (!bboxContains(subs[pi].bbox, subs[ci].bbox)) continue
if (!pointInPoly(subs[ci].poly[0], subs[pi].poly)) continue
parent[ci] = pi
break
}
}
const depth = new Array(n).fill(0)
const resolveDepth = (i) => {
const stack = []
let c = i
while (parent[c] >= 0 && depth[c] === 0 && stack.indexOf(c) < 0) {
stack.push(c)
c = parent[c]
}
let base = depth[c]
for (let k = stack.length - 1; k >= 0; k--) {
base += 1
depth[stack[k]] = base
}
return depth[i]
}
for (let i = 0; i < n; i++) resolveDepth(i)
const groups = new Map()
for (let i = 0; i < n; i++) {
// 归属根 = 最近的「深度为偶数」的祖先(偶数层是实心外壳,奇数层是孔洞)
let c = i
let guard = 0
while (depth[c] % 2 === 1 && parent[c] >= 0 && guard++ < 512) c = parent[c]
if (!groups.has(c)) groups.set(c, [])
groups.get(c).push(i)
}
const out = []
groups.forEach((idxs, root) => {
idxs.sort((a, b) => a - b) // 保持 potrace 原始顺序,输出稳定
out.push({ root, idxs, area: subs[root].area })
})
return out
}
/**
* 拆一个 d:返回每个孤岛的 d 片段(≥2 个才有意义,1 个原样返回)。
* @param {string} d
* @returns {string[]}
*/
export function splitPathData(d) {
const subs = parseSubpaths(d)
if (subs.length <= 1) return subs.length ? [d] : []
const groups = groupSubpaths(subs)
if (groups.length <= 1) return [d]
// 面积大的先输出 ⇒ 在 Figma 里压在下层(和原图遮挡关系一致)
groups.sort((a, b) => b.area - a.area)
return groups.map((g) => g.idxs.map((i) => subs[i].d).join(' '))
}
/**
* 把整份 SVG 里的每个 `<path>` 按孤岛拆成多个 `<path>`,其余属性(fill / fill-opacity /
* fill-rule / stroke)原样复制。不包 `<g>` —— Figma 导入时顶层并列的 path 就是可单独
* 选中的多个矢量图层,包一层组反而多一层要双击进去。
*
* @param {string} svg
* @returns {{svg:string, elements:number, islands:number}}
*/
export function splitSvgIslands(svg) {
const text = String(svg || '')
let elements = 0
let islands = 0
const out = text.replace(/<path\b([^>]*?)\/?>/g, (whole, attrs) => {
const dMatch = /\bd="([^"]*)"/.exec(attrs)
if (!dMatch) { elements += 1; islands += 1; return whole }
const parts = splitPathData(dMatch[1])
if (!parts.length) return whole
const rest = attrs.replace(/\bd="[^"]*"/, '').replace(/\s+/g, ' ').trim()
const tail = rest ? ' ' + rest : ''
elements += parts.length
islands += parts.length
return parts.map((p) => '<path d="' + p + '"' + tail + '/>').join('\n\t')
})
return { svg: out, elements, islands }
}
/**
* 只数孤岛数(给「拆分关闭」时也显示真实元素数用)。
* @param {string} svg
*/
export function countIslands(svg) {
const re = /<path\b[^>]*\bd="([^"]*)"/g
let m
let total = 0
while ((m = re.exec(String(svg || '')))) {
const subs = parseSubpaths(m[1])
total += subs.length <= 1 ? 1 : groupSubpaths(subs).length
}
return total
}
+34
View File
@@ -0,0 +1,34 @@
// 手写 manifest —— 必须保持单引号:scripts/validate.mjs 只认单引号形式,而 esbuild 打印器会改成双引号,
// 所以本文件不经 esbuild 转换,由 build-plugin.mjs 原样放在产物最前面(banner)。
//
// 为什么必须排在最前:校验器用「文件里第一个形如 id 冒号 单引号 的字面量」判定插件 id,
// 排在 bundle 之前才能保证取到的是下面这份 manifest。
// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。
//
// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。
// skin: 'private' = 自绘深色工具 UI(#1b1b22 系列),不跟随宿主主题。
// 代价由宿主契约测试钉死:声明 private 的插件不得引用宿主颜色 var(--iwb-*),只能自洽。
var __IWB_VECTORIZE_MANIFEST__ = {
id: 'image-vectorize',
name: '位图转矢量',
version: '__PLUGIN_VERSION__',
apiVersion: 1,
skin: 'private',
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
settings: {
preset: { type: 'string', default: 'text' },
mode: { type: 'string', default: 'gray' },
levels: { type: 'number', default: 3 },
threshold: { type: 'number', default: -1 },
turdSize: { type: 'number', default: 3 },
alphaMax: { type: 'number', default: 1 },
optTolerance: { type: 'number', default: 0.05 },
invert: { type: 'boolean', default: false },
color: { type: 'string', default: '#1a1a1a' },
bg: { type: 'string', default: '#ffffff' },
bgExport: { type: 'boolean', default: false },
outScale: { type: 'number', default: 2 },
advOpen: { type: 'boolean', default: true },
splitIslands: { type: 'boolean', default: true }
},
}
@@ -0,0 +1,9 @@
// 手写注册尾部(build-plugin.mjs 原样追加到产物末尾,不 overlapped with esbuild 的打印器)。
// 时序:bundle 先执行(挂好 __IWB_VECTORIZE_FACTORY__),再注册;factory 由宿主在「启用插件」时才调用。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
global.IWBPluginHost.register(__IWB_VECTORIZE_MANIFEST__, function (ctx) {
return global.__IWB_VECTORIZE_FACTORY__(ctx)
})
})(typeof window !== 'undefined' ? window : globalThis)
+87
View File
@@ -0,0 +1,87 @@
/* 描摹前处理与 SVG 输出工具(与引擎无关的纯工具函数)。
*
* 上一版(VTracer)里的降噪、背景层剔除、viewBox 修补在这里**全部删掉**了:
* - 降噪:potrace 的 turdSize 天生去小点,不需要先降采样糊一遍;
* - 背景层剔除:potrace 按明暗分层,白底自然成为最亮的一层,不再需要删 path;
* - viewBox 修补:potrace 自己就输出 width/height/viewBox(实测),不用二次拼接。
* 留下的只有:读图 → 必要时降采样 → 生成 PNG / 统计。
*/
'use strict'
import { MAX_TRACE_SIDE } from './engine.js'
/** 读 data URL 成 <img>(走浏览器解码,与画布语义一致) */
export function loadImage(dataUrl) {
return new Promise(function (resolve, reject) {
const img = new Image()
img.onload = function () { resolve(img) }
img.onerror = function () { reject(new Error('图片解码失败')) }
img.src = dataUrl
})
}
/**
* 准备描摹用的像素:potrace 是单线程纯 JS,超过 MAX_TRACE_SIDE 会明显卡主线程,
* 所以先按长边夹取(**只缩不放**)。
* @returns {{canvas:HTMLCanvasElement, w:number, h:number, srcW:number, srcH:number, clamped:boolean}}
*/
export function prepareSource(img) {
const srcW = img.naturalWidth || img.width
const srcH = img.naturalHeight || img.height
const longSide = Math.max(srcW, srcH)
const k = longSide > MAX_TRACE_SIDE ? MAX_TRACE_SIDE / longSide : 1
const w = Math.max(1, Math.round(srcW * k))
const h = Math.max(1, Math.round(srcH * k))
const canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
const ctx = canvas.getContext('2d', { willReadFrequently: true })
ctx.imageSmoothingEnabled = true
ctx.drawImage(img, 0, 0, w, h)
return { canvas, w, h, srcW, srcH, clamped: k < 1 }
}
/** SVG 字符串 → <img>(导出时把矢量光栅化) */
export function svgToImage(svg) {
return new Promise(function (resolve, reject) {
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
const url = URL.createObjectURL(blob)
const img = new Image()
img.onload = function () { URL.revokeObjectURL(url); resolve(img) }
img.onerror = function () { URL.revokeObjectURL(url); reject(new Error('矢量渲染失败')) }
img.src = url
})
}
/**
* 把矢量结果光栅化成 PNG(保存为节点用)。outScale 只影响像素尺寸 ——
* 曲线按 viewBox 缩放渲染,所以 2× 是真的更清晰,不是插值放大。
*/
export async function svgToPngBlob(svg, baseW, baseH, outScale) {
const img = await svgToImage(svg)
const k = Math.max(1, Math.min(4, Number(outScale) || 1))
const w = Math.max(1, Math.round(baseW * k))
const h = Math.max(1, Math.round(baseH * k))
const canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
const ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, w, h)
return new Promise(function (resolve, reject) {
canvas.toBlob(function (blob) {
if (blob) resolve(blob)
else reject(new Error('PNG 编码失败'))
}, 'image/png')
})
}
/** 统计:路径数、填充色数、字节数(面板上「体积」那个数字) */
export function svgStats(svg) {
const text = String(svg)
const paths = (text.match(/<path/g) || []).length
const fills = []
const re = /fill="([^"]+)"/g
let m
while ((m = re.exec(text))) if (fills.indexOf(m[1]) < 0) fills.push(m[1])
return { paths: paths, colors: fills.length, bytes: text.length }
}
+526
View File
@@ -0,0 +1,526 @@
/* 位图转矢量:全屏模态。深色,与「标注 / 修图」同一套视觉语言。
CSP:由宿主 style-src 'unsafe-inline' 放行,运行时注入 <style>。 */
.vz-root {
position: fixed;
inset: 0;
z-index: 2147483000;
display: flex;
align-items: center;
justify-content: center;
background: rgba(10, 10, 14, 0.72);
font: 13px/1.5 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
color: #e6e6ef;
}
.vz-modal {
display: flex;
flex-direction: column;
width: 100vw;
height: 100vh;
min-width: 0;
min-height: 0;
max-width: none;
background: #1b1b22;
border: 0;
border-radius: 0;
box-shadow: none;
overflow: hidden;
}
/* ---------- 顶栏 ---------- */
.vz-header {
display: flex;
align-items: center;
gap: 10px;
flex: 0 0 auto;
height: 52px;
padding: 0 14px;
background: #202029;
border-bottom: 1px solid #2e2e3a;
}
.vz-title {
font-size: 13px;
font-weight: 500;
color: #f0f0f7;
white-space: nowrap;
}
.vz-title em {
font-style: normal;
color: #8b8b9e;
font-weight: 400;
margin-left: 8px;
}
.vz-title em b {
color: #d6d6e4;
font-weight: 500;
}
.vz-spacer { flex: 1 1 auto; }
.vz-btn {
height: 32px;
padding: 0 14px;
border: 1px solid #3c3c4c;
border-radius: 7px;
background: #2a2a35;
color: #d8d8e4;
font-size: 12px;
cursor: pointer;
white-space: nowrap;
}
.vz-btn:hover { background: #34343f; border-color: #4a4a5c; }
.vz-btn:active { background: #2f2f3a; }
.vz-btn:disabled { opacity: 0.45; cursor: default; }
/* 顶栏「保存为节点 / 复制 SVG / 下载 SVG」三颗走上面这套灰色描边配色。
「关闭」单独用编辑器主色调(.vz-seg 选中态同款 #33566f)填充,与产出操作区分、防误点。
2026-11-19:原「取消」改名「关闭」并按主色调取色(行为不变,仍是 data-act="cancel" 退出编辑器)。 */
.vz-btn-close {
background: #33566f;
border-color: #33566f;
color: #eaf6ff;
}
.vz-btn-close:hover { background: #3d6480; border-color: #4a7394; }
.vz-btn-close:active { background: #2c4a60; }
/* ---------- 主体 ---------- */
.vz-body {
display: flex;
flex: 1 1 auto;
min-height: 0;
}
.vz-preview {
position: relative;
flex: 1 1 auto;
min-width: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
overflow: hidden;
/* 预览区直接用白底,不铺透明棋盘:描摹结果默认就是「白纸上的单色图形」,
棋盘格既干扰判断形状,也让深色细笔画看起来发虚(实测用户第一反应是「糊」)。
矢量 SVG 本身仍不含背景矩形,导出/复制到 Figma 依旧是透明底。 */
background-color: #ffffff;
/* 缩放 / 平移的**唯一真源**:矢量图与原图两张 img 共用这套变量,
所以按住空格对比时,视图完全不动(各自存一份状态迟早会对不上)。
量纲:zoom 无单位;pan 是**屏幕像素**(先 scale 后 translate,平移量不被缩放放大)。 */
--vz-zoom: 1;
--vz-pan-x: 0px;
--vz-pan-y: 0px;
cursor: grab;
/* 触屏 / 触控板手势全部自己处理,别让浏览器抢去做页面滚动 */
touch-action: none;
}
.vz-preview.is-panning { cursor: grabbing; }
/* 白底之上用一圈极淡的描边 + 细阴影标出画面边界:
白底稿(如菜单/白底商品图)与预览区同色时,否则看不出图到哪里。
绝对定位 + 50%/50% 是为了让 transform 的中心锚点稳定落在预览区正中(缩放锚点计算依赖这一点);
max-* 用 calc(100% - 40px) 抵掉 .vz-preview 的 20px padding(百分比相对 padding box 算)。 */
.vz-stage {
position: absolute;
left: 50%;
top: 50%;
max-width: calc(100% - 40px);
max-height: calc(100% - 40px);
display: block;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.07);
transform:
translate(-50%, -50%)
translate(var(--vz-pan-x), var(--vz-pan-y))
scale(var(--vz-zoom));
transform-origin: 50% 50%;
/* 拖动时每帧改 transform,提前提层,避免整块重绘掉帧(最多两张图,内存代价可忽略) */
will-change: transform;
/* 拖动时别触发 img 的原生拖拽(会拽出一个半透明缩略图,手势直接断掉) */
user-select: none;
-webkit-user-drag: none;
}
.vz-stage[hidden] { display: none; }
/* 白底预览上的常驻小标签:浅色胶囊 + 细描边,深色版本在纯白画面里过于抢眼 */
.vz-badge {
position: absolute;
top: 14px;
left: 14px;
padding: 4px 9px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.92);
border: 1px solid rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
color: #55555f;
font-size: 11px;
letter-spacing: 0.2px;
}
.vz-hint {
position: absolute;
bottom: 14px;
left: 50%;
transform: translateX(-50%);
padding: 5px 11px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.92);
border: 1px solid rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
color: #55555f;
font-size: 11px;
pointer-events: none;
white-space: nowrap;
}
/* 缩放倍率:只有真的缩放过才出现(100% 时挂 hidden,不占视线)。
它同时是「现在没在 1:1」的唯一视觉信号 —— 用户放大看细节后容易忘记自己还缩着。 */
.vz-zoom {
position: absolute;
right: 14px;
bottom: 14px;
display: flex;
align-items: center;
gap: 6px;
padding: 4px 9px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.94);
border: 1px solid rgba(0, 0, 0, 0.12);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
color: #45454f;
font-size: 11px;
font-variant-numeric: tabular-nums;
cursor: pointer;
user-select: none;
}
.vz-zoom[hidden] { display: none; }
.vz-zoom b { font-weight: 600; }
.vz-zoom span { color: #9a9aa8; }
.vz-zoom:hover { border-color: rgba(0, 0, 0, 0.22); }
.vz-zoom:hover span { color: #45454f; }
/* 描摹中/出错的浮层 */
.vz-status {
position: absolute;
top: 14px;
right: 14px;
display: flex;
align-items: center;
gap: 8px;
padding: 5px 11px;
border-radius: 7px;
font-size: 11px;
background: rgba(18, 18, 24, 0.88);
border: 1px solid #33333f;
color: #b9b9cc;
}
.vz-status[hidden] { display: none; }
.vz-status.is-busy { color: #ffd08a; border-color: #5a4526; }
.vz-status.is-error { color: #ff9c9c; border-color: #5c2c2c; max-width: 60%; }
.vz-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
flex: 0 0 auto;
}
.vz-status.is-busy .vz-dot { animation: vz-pulse 1s ease-in-out infinite; }
@keyframes vz-pulse { 0%, 100% { opacity: 0.25; } 50% { opacity: 1; } }
/* ---------- 参数面板 ---------- */
.vz-panel {
flex: 0 0 auto;
width: 312px;
padding: 12px 15px 14px;
background: #1e1e26;
border-left: 1px solid #2e2e3a;
overflow-y: auto;
}
.vz-panel::-webkit-scrollbar { width: 8px; }
.vz-panel::-webkit-scrollbar-thumb { background: #3a3a48; border-radius: 4px; }
/* 组间距比「看着舒服」再紧一点:高级参数默认展开(用户要求),
六组内容在 88vh 里要刚好放得下,否则最后一行「填充 / 背景」会贴着底边被裁 */
.vz-group + .vz-group { margin-top: 12px; padding-top: 10px; border-top: 1px solid #2b2b36; }
.vz-group-title {
font-size: 11px;
color: #7e7e94;
letter-spacing: 0.6px;
margin-bottom: 9px;
text-transform: none;
}
/* 预设 */
.vz-presets {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.vz-preset {
display: flex;
flex-direction: column;
gap: 2px;
padding: 7px 9px;
border: 1px solid #37374a;
border-radius: 8px;
background: #262631;
color: #d5d5e2;
font-size: 12px;
text-align: left;
cursor: pointer;
}
.vz-preset small {
color: #7b7b91;
font-size: 10px;
line-height: 1.35;
}
.vz-preset:hover { background: #2e2e3b; border-color: #45455a; }
.vz-preset.active {
background: #1f3a30;
border-color: #2f7d5b;
color: #d8ffe9;
}
.vz-preset.active small { color: #79b79b; }
/* 分段控件 */
.vz-row { margin-bottom: 8px; }
/* 按模式隐藏的行(层数只在灰度、阈值只在手动)必须真的消失。
踩过的坑:flex/块级元素上加 `hidden` 属性,如果 CSS 里另有 display 声明就会失效,
于是「隐藏」只变成视觉上还在 —— 这里直接 !important 兜住所有形态。 */
.vz-row[hidden] { display: none !important; }
.vz-row:last-child { margin-bottom: 0; }
.vz-row-label {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
color: #b6b6c8;
margin-bottom: 6px;
}
.vz-row-label span { color: #6f6f85; font-size: 11px; }
.vz-seg {
display: flex;
gap: 0;
border: 1px solid #3a3a4a;
border-radius: 7px;
overflow: hidden;
}
.vz-seg button {
flex: 1 1 0;
height: 28px;
border: 0;
border-right: 1px solid #3a3a4a;
background: #24242e;
color: #a8a8bd;
font-size: 11.5px;
cursor: pointer;
white-space: nowrap;
}
.vz-seg button:last-child { border-right: 0; }
.vz-seg button:hover { background: #2c2c38; color: #d0d0e0; }
.vz-seg button.active { background: #33566f; color: #eaf6ff; }
/* 滑杆 */
.vz-range {
display: flex;
align-items: center;
gap: 9px;
}
.vz-range input[type="range"] {
flex: 1 1 auto;
min-width: 0;
height: 4px;
-webkit-appearance: none;
appearance: none;
background: #3a3a4a;
border-radius: 2px;
outline: none;
}
.vz-range input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 13px;
height: 13px;
border-radius: 50%;
background: #cfcfdd;
border: 0;
cursor: pointer;
}
.vz-range input[type="range"]:disabled { opacity: 0.4; }
.vz-range input[type="range"]:disabled::-webkit-slider-thumb { cursor: default; }
.vz-range-val {
flex: 0 0 auto;
min-width: 34px;
text-align: right;
font-size: 11.5px;
color: #d0d0e0;
font-variant-numeric: tabular-nums;
}
/* 高级参数折叠:首屏只露高频项,低频参数收起来但一档可达 */
.vz-adv-toggle {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
height: 30px;
padding: 0 10px;
border: 1px solid #37374a;
border-radius: 7px;
background: #24242e;
color: #a8a8bd;
font-size: 11.5px;
cursor: pointer;
}
.vz-adv-toggle:hover { background: #2c2c38; color: #d0d0e0; }
.vz-adv-toggle span { color: #6f6f85; }
/* 单色填充色(仅「纯单色」生效)。原生 color input 在深色面板里默认边框很亮,
去掉内边距与外框,只留一块颜色本身,和滑杆行视觉一致 */
.vz-color {
flex: 0 0 auto;
width: 42px;
height: 22px;
padding: 0;
border: 1px solid #45455a;
border-radius: 6px;
background: transparent;
cursor: pointer;
}
.vz-color::-webkit-color-swatch-wrapper { padding: 2px; }
.vz-color::-webkit-color-swatch { border: none; border-radius: 4px; }
.vz-color:disabled { cursor: default; }
/* 填充 / 背景并排(用户要求放一排)+ 「带底」小勾选。
色块从 42px 收到 34px,两个并排仍能塞进 312px 面板且不挤掉标签。 */
.vz-swatches {
display: flex;
align-items: center;
gap: 6px;
flex: 0 0 auto;
}
.vz-swatches .vz-color { width: 34px; }
.vz-mini {
display: inline-flex;
align-items: center;
gap: 4px;
height: 22px;
padding: 0 6px;
border: 1px solid #3c3c4c;
border-radius: 6px;
background: #24242e;
color: #a8a8bd;
font-size: 11px;
white-space: nowrap;
cursor: pointer;
}
.vz-mini:hover { border-color: #4a4a5c; color: #d0d0e0; }
.vz-mini input {
width: 11px;
height: 11px;
margin: 0;
accent-color: #2f9c69;
cursor: pointer;
}
/* 勾选开关(按孤岛拆分):原生 checkbox 在深色面板里太小、且难以点中。
用 label 包一层,点整块都能切换;focus-visible 保留键盘可达的焦点环。 */
.vz-row-switch {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.vz-row-text {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
font-size: 12px;
color: #b6b6c8;
}
.vz-row-text span {
color: #6f6f85;
font-size: 10.5px;
line-height: 1.4;
}
.vz-switch {
position: relative;
flex: 0 0 auto;
width: 34px;
height: 20px;
cursor: pointer;
}
.vz-switch input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
opacity: 0;
cursor: pointer;
}
.vz-switch i {
position: absolute;
inset: 0;
border-radius: 999px;
background: #3a3a4a;
transition: background 0.15s ease;
pointer-events: none;
}
.vz-switch i::after {
content: '';
position: absolute;
top: 2px;
left: 2px;
width: 16px;
height: 16px;
border-radius: 50%;
background: #b9b9c9;
transition: transform 0.15s ease, background 0.15s ease;
}
.vz-switch input:checked + i { background: #2f7d5b; }
.vz-switch input:checked + i::after { transform: translateX(14px); background: #ffffff; }
.vz-switch input:focus-visible + i { box-shadow: 0 0 0 2px rgba(90, 200, 160, 0.45); }
.vz-adv { margin-top: 10px; }
.vz-adv[hidden] { display: none; }
/* 统计 */
.vz-stats {
display: flex;
gap: 14px;
flex-wrap: wrap;
font-size: 11.5px;
color: #8f8fa4;
}
.vz-stats b { color: #d8d8e6; font-weight: 500; }
.vz-note {
margin-top: 9px;
font-size: 10.5px;
line-height: 1.55;
color: #6b6b80;
}
/* 窄屏:面板转到底部 */
@media (max-width: 900px) {
.vz-modal { width: 100vw; height: 100vh; min-width: 0; }
.vz-body { flex-direction: column; }
.vz-panel { width: auto; max-height: 46%; border-left: 0; border-top: 1px solid #2e2e3a; }
}
+829
View File
@@ -0,0 +1,829 @@
/* 「位图转矢量」的 UI 与交互(potrace 版:单色 / 灰度)。
*
* 设计取舍:
* 1. 面板只渲染一次,参数变化走 syncControls() 回写控件值 —— 重建 innerHTML 会打断滑杆拖动;
* 2. 预览用 <img src="blob:"> 而不是 innerHTML 插 SVG —— 宿主 CSP 下更安全,也避免每次重绘解析 DOM;
* 3. potrace 是**同步**纯 JS(800px 几十毫秒),所以没有上一版那种 busy/pending 重入状态机,
* 只保留 150ms 防抖 + seq 票据(关闭时让在途回调失效);
* 4. 参数记忆走 ctx.settings(宿主命名空间 KV),下次打开回到上次的参数。
*
* 面板刻意做小:用户只做单色/灰度,高频就「方式 + 层数 + 去小点」三个,
* 阈值/反相/颜色收进高级(0 层级优先,低频 1 层级)。
*/
'use strict'
import { DEFAULTS, LEVELS_MIN, LEVELS_MAX, TOLERANCE_TONES, normalizeParams } from './engine.js'
import { loadImage, prepareSource, svgToPngBlob, svgStats } from './trace.js'
import { traceImageData } from './engine.js'
const SETTING_KEYS = ['preset', 'mode', 'levels', 'threshold', 'turdSize', 'alphaMax', 'optTolerance', 'invert', 'color', 'bg', 'bgExport', 'outScale', 'advOpen', 'splitIslands']
/** 三个预设:都围绕「自己出图」的实际场景,不放没用的组合 */
const PRESETS = {
text: { label: '文字 / 线稿', hint: '单色 · 保笔画', mode: 'mono', turdSize: 2, alphaMax: 1, levels: 3 },
menu: { label: '菜单 / 图文', hint: '灰度 3 层', mode: 'gray', levels: 3, turdSize: 4, alphaMax: 1 },
cutout: { label: '抠图轮廓', hint: '单色 · 去毛刺', mode: 'mono', turdSize: 12, alphaMax: 1.1, levels: 3 },
}
const HINTS = {
turdSize: '抹掉小于该像素面积的碎片(毛刺 / 噪点)',
alphaMax: '越小越硬朗(多折线),越大越圆',
}
function esc(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
})
}
function segHTML(group, options, current) {
return options.map(function (pair) {
const active = String(pair[0]) === String(current) ? ' active' : ''
return '<button type="button" class="' + active.trim() + '" data-seg="' + group + '" data-value="' + pair[0] + '">' + esc(pair[1]) + '</button>'
}).join('')
}
function rangeHTML(name, label, min, max, step, value, hint) {
return '<div class="vz-row">' +
'<div class="vz-row-label">' + esc(label) + (hint ? '<span>' + esc(hint) + '</span>' : '') + '</div>' +
'<div class="vz-range">' +
'<input type="range" data-param="' + name + '" min="' + min + '" max="' + max + '" step="' + step + '" value="' + value + '">' +
'<span class="vz-range-val" data-val="' + name + '">' + value + '</span>' +
'</div></div>'
}
function panelHTML(params, preset, outScale, advOpen) {
const presets = Object.keys(PRESETS).map(function (key) {
const p = PRESETS[key]
return '<button type="button" class="vz-preset' + (key === preset ? ' active' : '') + '" data-preset="' + key + '">' +
esc(p.label) + '<small>' + esc(p.hint) + '</small></button>'
}).join('')
return '' +
'<div class="vz-group"><div class="vz-group-title">预设</div><div class="vz-presets">' + presets + '</div></div>' +
'<div class="vz-group">' +
'<div class="vz-row"><div class="vz-row-label">描摹方式</div><div class="vz-seg" data-seg-group="mode">' +
segHTML('mode', [['gray', '灰度分层'], ['mono', '纯单色']], params.mode) + '</div></div>' +
'<div class="vz-row" data-only="gray"><div class="vz-row-label">层数<span>多一层,浅色块更容易分离</span></div><div class="vz-seg" data-seg-group="levels">' +
[2, 3, 4, 5].map(function (n) { return '<button type="button" data-seg="levels" data-value="' + n + '">' + n + '</button>' }).join('') +
'</div></div>' +
'</div>' +
'<div class="vz-group">' +
rangeHTML('turdSize', '去小点', 0, 40, 1, params.turdSize, HINTS.turdSize) +
'<div class="vz-row"><div class="vz-row-label">边缘<span>拐角处理</span></div><div class="vz-seg" data-seg-group="alphaTone">' +
'<button type="button" data-seg="alphaTone" data-value="hard">硬朗</button>' +
'<button type="button" data-seg="alphaTone" data-value="normal">标准</button>' +
'<button type="button" data-seg="alphaTone" data-value="round">圆润</button></div></div>' +
'<div class="vz-row"><div class="vz-row-label">精度<span>越高越贴合原图,曲线数据略多</span></div><div class="vz-seg" data-seg-group="precision">' +
'<button type="button" data-seg="precision" data-value="fine">精细</button>' +
'<button type="button" data-seg="precision" data-value="normal">标准</button>' +
'<button type="button" data-seg="precision" data-value="light">轻量</button></div></div>' +
'</div>' +
'<div class="vz-group">' +
'<div class="vz-row"><div class="vz-row-label">输出倍率<span>PNG 按矢量重绘,真清晰</span></div><div class="vz-seg" data-seg-group="outScale">' +
[1, 2, 3, 4].map(function (n) { return '<button type="button" data-seg="outScale" data-value="' + n + '">' + n + '×</button>' }).join('') +
'</div></div>' +
'<div class="vz-row vz-row-switch">' +
'<div class="vz-row-text">按孤岛拆分<span>每个连通块一个图层,粘到 Figma 可单独选中;笔画不连的汉字会分成几块</span></div>' +
'<label class="vz-switch"><input type="checkbox" data-check="splitIslands"' + (params.splitIslands ? ' checked' : '') + '><i></i></label>' +
'</div>' +
'</div>' +
'<div class="vz-group">' +
'<div class="vz-stats">' +
'<span><b data-stat="elements">–</b> 元素</span>' +
'<span><b data-stat="levels">–</b> 层</span>' +
'<span><b data-stat="bytes">–</b></span>' +
'<span><b data-stat="ms">–</b></span>' +
'</div>' +
'</div>' +
'<div class="vz-group">' +
'<button type="button" class="vz-adv-toggle" data-act="adv" aria-expanded="' + (advOpen ? 'true' : 'false') + '">高级参数<span data-adv-caret>' + (advOpen ? '▴' : '▾') + '</span></button>' +
'<div class="vz-adv" data-adv' + (advOpen ? '' : ' hidden') + '>' +
'<div class="vz-row"><div class="vz-row-label">阈值<span>自动按直方图取,手动可救极端图</span></div><div class="vz-seg" data-seg-group="thrMode">' +
'<button type="button" data-seg="thrMode" data-value="auto">自动</button>' +
'<button type="button" data-seg="thrMode" data-value="manual">手动</button></div></div>' +
'<div data-thr-row hidden>' + rangeHTML('threshold', '阈值取值', 0, 255, 1, params.threshold >= 0 ? params.threshold : 128, '') + '</div>' +
'<div class="vz-row"><div class="vz-row-label">反相<span>黑底白字时打开</span></div><div class="vz-seg" data-seg-group="invert">' +
segHTML('invert', [['0', '正片'], ['1', '负片']], params.invert ? 1 : 0) + '</div></div>' +
'<div class="vz-row"><div class="vz-row-label">填充 / 背景<span>填充仅「纯单色」生效 · 背景作预览底</span></div>' +
'<div class="vz-swatches">' +
'<input type="color" class="vz-color" data-color="color" value="' + esc(params.color) + '" title="填充色(纯单色生效)">' +
'<input type="color" class="vz-color" data-color="bg" value="' + esc(params.bg) + '" title="背景色(预览底;勾「带底」写入导出)">' +
'<label class="vz-mini" title="导出 / 复制时把背景色一起写进 SVG(默认不带,粘到 Figma 是透明底)">' +
'<input type="checkbox" data-check="bgExport"' + (params.bgExport ? ' checked' : '') + '><span>带底</span></label>' +
'</div></div>' +
'</div>' +
'</div>'
}
function viewHTML(name) {
return '' +
'<div class="vz-root">' +
'<div class="vz-modal" role="dialog" aria-modal="true" aria-label="位图转矢量">' +
'<header class="vz-header">' +
'<span class="vz-title">位图转矢量<em data-meta>' + esc(name) + '</em></span>' +
'<div class="vz-spacer"></div>' +
// 顺序:主操作在左,取消在最右(用户 2026-11-09 要求与原先互换)。
// 四颗按钮同一套描边配色,不再给主操作上绿色填充 —— 用户口径「颜色都用取消按钮的配色」。
'<button type="button" class="vz-btn" data-act="save">保存为节点</button>' +
'<button type="button" class="vz-btn" data-act="copy">复制 SVG</button>' +
'<button type="button" class="vz-btn" data-act="svg">下载 SVG</button>' +
'<button type="button" class="vz-btn vz-btn-close" data-act="cancel">关闭</button>' +
'</header>' +
'<div class="vz-body">' +
'<div class="vz-preview" data-preview>' +
'<img class="vz-stage" data-stage="vector" alt="矢量预览" draggable="false">' +
'<img class="vz-stage" data-stage="original" alt="原图" draggable="false" hidden>' +
'<div class="vz-badge" data-badge>矢量预览</div>' +
'<div class="vz-status" data-status hidden><i class="vz-dot"></i><span data-status-text></span></div>' +
'<div class="vz-hint">空格 对比原图 · 滚轮缩放 · 拖动平移 · 双击复位</div>' +
'<div class="vz-zoom" data-zoom-chip hidden title="点击回到 100%"><b data-zoom-val>100%</b><span>复位</span></div>' +
'</div>' +
'<aside class="vz-panel" data-panel></aside>' +
'</div></div></div>'
}
/** 边缘预设 → alphaMax(越圆 alphaMax 越大) */
const ALPHA_TONE = { hard: 0.4, normal: 1, round: 1.2 }
const toneOf = (alphaMax) => (alphaMax <= 0.6 ? 'hard' : alphaMax >= 1.1 ? 'round' : 'normal')
/** 容差 → 精度档(0.05 精细 / 0.15 标准 / 0.4 轻量) */
const tolToneOf = (tol) => (tol <= 0.08 ? 'fine' : tol >= 0.3 ? 'light' : 'normal')
export function createVectorizer(options) {
const settings = options.settings
const onSaveNode = options.onSaveNode
const onError = options.onError
const onClose = options.onClose
let root = null
let els = null
let source = null
let params = normalizeParams(DEFAULTS)
let preset = 'text'
let outScale = 2
let advOpen = true
let currentSvg = ''
let lastElements = 0
let lastIslands = 0
let currentBlobUrl = ''
let seq = 0
let debounceTimer = 0
let spaceDown = false
// 预览视图(缩放 + 平移):zoom=1 / pan=0 就是原始「等比铺满」,双击或点倍率胶囊复位
let zoom = 1
let panX = 0
let panY = 0
let drag = null
// ---------- 设置读写 ----------
function readSettings() {
const out = {}
if (!settings || typeof settings.get !== 'function') return out
for (const key of SETTING_KEYS) {
let value
try { value = settings.get(key) } catch (e) { continue }
if (value === undefined || value === null || value === '') continue
if (key === 'invert' || key === 'bgExport') value = value === true || value === 'true' || value === 1 || value === '1'
if (key === 'splitIslands') value = !(value === false || value === 'false' || value === 0 || value === '0')
if (key === 'advOpen') value = !(value === false || value === 'false' || value === 0 || value === '0')
out[key] = value
}
return out
}
function writeSettings() {
if (!settings || typeof settings.set !== 'function') return
try {
settings.set('preset', preset)
settings.set('mode', params.mode)
settings.set('levels', params.levels)
settings.set('threshold', params.threshold)
settings.set('turdSize', params.turdSize)
settings.set('alphaMax', params.alphaMax)
settings.set('optTolerance', params.optTolerance)
settings.set('invert', params.invert)
settings.set('color', params.color)
settings.set('bg', params.bg)
settings.set('bgExport', params.bgExport)
settings.set('outScale', outScale)
settings.set('advOpen', advOpen)
settings.set('splitIslands', params.splitIslands)
} catch (e) { /* 记忆失败不影响主流程 */ }
}
// ---------- 状态 ----------
function setStatus(kind, text) {
if (!els) return
const box = els.status
if (!kind) { box.hidden = true; box.className = 'vz-status'; return }
box.hidden = false
box.className = 'vz-status is-' + kind
els.statusText.textContent = text || ''
}
function setStats(stats, ms, levels) {
if (!els) return
const put = function (key, text) {
const node = els.panel.querySelector('[data-stat="' + key + '"]')
if (node) node.textContent = text
}
if (!stats) { put('elements', '–'); put('levels', '–'); put('bytes', '–'); put('ms', '–'); return }
const elements = stats.elements === undefined ? stats.paths : stats.elements
// 关闭拆分时元素数和真实孤岛数不等 —— 明说「合并」,否则用户会以为描摹少画了东西
put('elements', stats.islands && stats.islands !== elements
? elements + '(' + stats.islands + ' 孤岛合并)'
: String(elements))
put('levels', String(levels || 1))
put('bytes', stats.bytes >= 1024 * 1024
? (stats.bytes / 1024 / 1024).toFixed(1) + 'MB'
: Math.round(stats.bytes / 1024) + 'KB')
put('ms', ms === undefined || ms === null ? '–' : ms + 'ms')
}
/** 把 params 回写到控件(不重建 DOM,避免拖动滑杆时被打断) */
function syncControls() {
if (!els) return
const panel = els.panel
panel.querySelectorAll('[data-preset]').forEach(function (btn) {
btn.classList.toggle('active', btn.dataset.preset === preset)
})
panel.querySelectorAll('[data-param]').forEach(function (input) {
const key = input.dataset.param
input.value = key === 'threshold' && params.threshold < 0 ? 128 : params[key]
const out = panel.querySelector('[data-val="' + key + '"]')
if (out) out.textContent = input.value
})
// 层数只在灰度下有含义;颜色只在单色下有含义 —— 直接隐藏而不是假装可调
panel.querySelectorAll('[data-only="gray"]').forEach(function (row) {
row.hidden = params.mode !== 'gray'
})
panel.querySelectorAll('[data-seg-group="levels"] button').forEach(function (btn) {
btn.classList.toggle('active', Number(btn.dataset.value) === params.levels)
})
panel.querySelectorAll('[data-seg-group="mode"] button').forEach(function (btn) {
btn.classList.toggle('active', btn.dataset.value === params.mode)
})
panel.querySelectorAll('[data-seg-group="alphaTone"] button').forEach(function (btn) {
btn.classList.toggle('active', btn.dataset.value === toneOf(params.alphaMax))
})
panel.querySelectorAll('[data-seg-group="precision"] button').forEach(function (btn) {
btn.classList.toggle('active', btn.dataset.value === tolToneOf(params.optTolerance))
})
panel.querySelectorAll('[data-seg-group="invert"] button').forEach(function (btn) {
btn.classList.toggle('active', (btn.dataset.value === '1') === params.invert)
})
panel.querySelectorAll('[data-seg-group="thrMode"] button').forEach(function (btn) {
btn.classList.toggle('active', (btn.dataset.value === 'manual') === (params.threshold >= 0))
})
panel.querySelectorAll('[data-seg-group="outScale"] button').forEach(function (btn) {
btn.classList.toggle('active', Number(btn.dataset.value) === outScale)
})
panel.querySelectorAll('[data-check]').forEach(function (input) {
input.checked = Boolean(params[input.dataset.check])
})
const thrRow = panel.querySelector('[data-thr-row]')
if (thrRow) thrRow.hidden = params.threshold < 0
// 填充色只在单色下有含义(灰度靠 layer 自身亮度),背景色两种模式都能用
panel.querySelectorAll('[data-color]').forEach(function (input) {
const key = input.dataset.color
input.value = key === 'bg' ? params.bg : params.color
const locked = key === 'color' && params.mode !== 'mono'
input.disabled = locked
input.style.opacity = locked ? '0.45' : ''
})
applyPreviewBg()
}
/** 预览底色:只改 CSS,不重描摹(背景不参与轮廓计算) */
function applyPreviewBg() {
if (!els || !els.preview) return
els.preview.style.backgroundColor = params.bg
}
function releasePreview() {
if (currentBlobUrl) {
URL.revokeObjectURL(currentBlobUrl)
currentBlobUrl = ''
}
}
function showVector(svg) {
if (!els) return
releasePreview()
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
currentBlobUrl = URL.createObjectURL(blob)
els.vector.src = currentBlobUrl
els.vector.hidden = false
updateBadge()
}
function updateBadge() {
if (!els) return
els.vector.hidden = spaceDown
els.original.hidden = !spaceDown
els.badge.textContent = spaceDown ? '原图' : '矢量预览'
}
// ---------- 预览视图:缩放 / 平移 ----------
//
// 为什么把状态写进 CSS 变量而不是直接改每张图的 style.transform:
// 预览里有「矢量」和「原图」两张 img 靠显隐切换做对比,各存一份视图状态迟早对不上
// (按住空格那一瞬间画面会跳)。变量挂在 .vz-preview 上,两张图共用,天然同步。
const ZOOM_MIN = 0.2
const ZOOM_MAX = 8
function applyView() {
if (!els || !els.preview) return
els.preview.style.setProperty('--vz-zoom', String(zoom))
els.preview.style.setProperty('--vz-pan-x', panX + 'px')
els.preview.style.setProperty('--vz-pan-y', panY + 'px')
const changed = zoom !== 1 || panX !== 0 || panY !== 0
if (els.zoomVal) els.zoomVal.textContent = Math.round(zoom * 100) + '%'
// 倍率胶囊只在真的缩放过时出现:100% 状态挂个「100% 复位」纯属噪音
if (els.zoomChip) els.zoomChip.hidden = !changed
}
function resetView() {
zoom = 1
panX = 0
panY = 0
drag = null
if (els && els.preview) els.preview.classList.remove('is-panning')
applyView()
}
/**
* 以屏幕点 (clientX, clientY) 为锚点缩放 —— 鼠标下的像素在缩放前后停在原处,
* 否则「想放大看这个字」会变成「放大完还得把它找回来」。
*
* 推导:图片中心恒在「预览区中心 + pan」,屏幕点 P 对应的图上偏移 d = (P - C - pan) / zoom,
* 要让 P 不动即 C + pan + d·zoom = C + pan' + d·zoom′ ⇒ pan′ = pan + d·(zoom − zoom′)。
*/
function zoomAt(clientX, clientY, factor) {
if (!els || !els.preview) return
const next = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, zoom * factor))
if (Math.abs(next - zoom) < 1e-4) return
const rect = els.preview.getBoundingClientRect()
const dx = (clientX - (rect.left + rect.width / 2) - panX) / zoom
const dy = (clientY - (rect.top + rect.height / 2) - panY) / zoom
panX -= dx * (next - zoom)
panY -= dy * (next - zoom)
zoom = next
applyView()
}
function zoomAtCenter(factor) {
if (!els || !els.preview) return
const rect = els.preview.getBoundingClientRect()
zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, factor)
}
function onPreviewWheel(event) {
event.preventDefault()
// 滚轮 = 缩放,无条件(用户口径:中键滚轮就是放大缩小)。
// 早先靠「deltaY 是 ±100 整数」猜设备来区分鼠标滚轮与触控板双指滑动,结果鼠标驱动
// 一旦给小数步长(平滑滚动 / 高精度滚轮)就落进平移分支,表现成「滚轮拖图不放大」。
// 现在只按主导轴分:水平滚动(含 Shift+滚轮,Chrome 会转成 deltaX)才平移。
if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
panX += event.deltaX
applyView()
return
}
if (!event.deltaY) return
// 步长分两档:鼠标滚轮一格 ±100,触控板是细碎小数步 —— 后者要给更大增益才跟得上手
const step = event.ctrlKey ? 0.01 : Math.abs(event.deltaY) >= 40 ? 0.0018 : 0.012
zoomAt(event.clientX, event.clientY, Math.exp(-event.deltaY * step))
}
function onPreviewPointerDown(event) {
if (!els || !els.preview) return
// 左键拖动 = 平移;中键拖动也平移(设计软件的肌肉记忆,顺手)
if (event.button !== 0 && event.button !== 1) return
if (event.target.closest('.vz-zoom')) return
// 挡掉 img 原生拖拽与中键自动滚动(Windows 上会弹四向圆盘,手势直接断掉)
event.preventDefault()
drag = { x: event.clientX, y: event.clientY, panX: panX, panY: panY, id: event.pointerId }
els.preview.classList.add('is-panning')
try { els.preview.setPointerCapture(event.pointerId) } catch (e) { /* 没有 capture 也能拖,只是移出元素会断 */ }
}
function onPreviewPointerMove(event) {
if (!drag || !els || !els.preview || event.pointerId !== drag.id) return
panX = drag.panX + (event.clientX - drag.x)
panY = drag.panY + (event.clientY - drag.y)
applyView()
}
function onPreviewPointerUp(event) {
if (!drag) return
if (event && event.pointerId !== undefined && event.pointerId !== drag.id) return
if (els && els.preview) {
els.preview.classList.remove('is-panning')
try { els.preview.releasePointerCapture(drag.id) } catch (e) { /* 已经释放过 */ }
}
drag = null
}
function onPreviewDblClick(event) {
if (event.target.closest('.vz-zoom')) return
resetView()
}
// ---------- 描摹 ----------
function retrace() {
if (!source) return
const ticket = ++seq
try {
const prepared = prepareSource(source.img)
const ctx = prepared.canvas.getContext('2d', { willReadFrequently: true })
const data = ctx.getImageData(0, 0, prepared.w, prepared.h)
const out = traceImageData(data, params)
if (ticket !== seq || !els) return
currentSvg = out.svg
showVector(currentSvg)
const stats = svgStats(currentSvg)
stats.elements = out.elements
stats.islands = out.islands
lastElements = out.elements
lastIslands = out.islands
setStats(stats, out.ms, out.levels)
setStatus(null)
if (prepared.clamped) {
setStatus('busy', '大图已降到 ' + prepared.w + '×' + prepared.h + ' 再描摹')
window.setTimeout(function () { if (ticket === seq) setStatus(null) }, 2600)
} else if (params.mode === 'gray' && params.splitIslands && out.elements > 40) {
// 灰度是「每层各描一遍」,层与层之间本来就有重叠的大轮廓,
// 拆开后同位置会出现多个重复图层(在 Figma 里选一个会选中好几个)。
// 这不是拆分 bug,是分层描摹的性质 —— 明说,别让用户以为是重复元素。
setStatus('busy', '灰度按层各拆一遍(' + out.elements + ' 个元素,层间会重叠);要干净分离改用「纯单色」')
window.setTimeout(function () { if (ticket === seq) setStatus(null) }, 4200)
}
els.meta.textContent = source.name + ' · ' + prepared.srcW + '×' + prepared.srcH
} catch (error) {
if (ticket !== seq) return
currentSvg = ''
setStats(null)
const msg = error && error.message ? error.message : String(error)
setStatus('error', '描摹失败:' + msg)
if (typeof onError === 'function') onError(error)
}
}
function scheduleRetrace() {
window.clearTimeout(debounceTimer)
debounceTimer = window.setTimeout(function () { writeSettings(); retrace() }, 120)
}
// ---------- 复制到剪贴板 ----------
/**
* 把 SVG 放进剪贴板,尽量让设计软件(Figma / Illustrator / Sketch)认成**矢量**而不是文本。
*
* 三种「口味」各有用途,缺一不可:
* - `image/svg+xml`:真正的矢量 MIME,Illustrator / Inkscape 直接吃;
* - `text/html` 里带 `<svg>`:Figma 走 HTML 解析分支时会认成矢量;
* - `text/plain`:兜底(也有软件只读纯文本里的 SVG 源码)。
* Chrome 对可写 MIME 有白名单,塞了不支持的类型会**整次 write 失败**,
* 所以先用 `ClipboardItem.supports()` 探测,失败再逐级降级。
*/
async function writeSvgToClipboard(svgText) {
const nav = typeof navigator === 'undefined' ? null : navigator
const Item = typeof window === 'undefined' ? null : window.ClipboardItem
const plain = new Blob([svgText], { type: 'text/plain' })
const html = new Blob([svgText], { type: 'text/html' })
let svgFlavor = false
if (nav && nav.clipboard && typeof nav.clipboard.write === 'function' && typeof Item === 'function') {
try {
svgFlavor = typeof Item.supports !== 'function' || Item.supports('image/svg+xml')
} catch (e) {
svgFlavor = false
}
const tryWrite = async function (withSvg) {
const flavors = { 'text/plain': plain, 'text/html': html }
if (withSvg) flavors['image/svg+xml'] = new Blob([svgText], { type: 'image/svg+xml' })
await nav.clipboard.write([new Item(flavors)])
}
try {
await tryWrite(svgFlavor)
return svgFlavor ? 'svg' : 'text'
} catch (error) {
// 某个口味被拒会让整次写入失败:去掉矢量口味再试一次
if (svgFlavor) {
try {
await tryWrite(false)
return 'text'
} catch (error2) { /* 落到 writeText */ }
}
}
}
if (nav && nav.clipboard && typeof nav.clipboard.writeText === 'function') {
await nav.clipboard.writeText(svgText)
return 'text'
}
return ''
}
async function copySvg(button) {
if (!currentSvg) { setStatus('error', '还没有可复制的矢量结果'); return }
const label = button.textContent
button.disabled = true
try {
const how = await writeSvgToClipboard(currentSvg)
if (!how) throw new Error('当前环境不允许写剪贴板')
button.textContent = '已复制'
// 明确告诉用户粘过去是「散的」还是「一个整体」—— 这是本版最容易被搞混的开关
const shape = params.splitIslands
? ',粘过去是 ' + lastElements + ' 个独立元素'
: ',粘过去是 1 个整体' + (lastIslands > 1 ? '(' + lastIslands + ' 个孤岛已合并)' : '')
setStatus('busy', how === 'svg'
? '已复制矢量' + shape + ',直接粘到 Figma / Illustrator 即可'
: '已复制 SVG 源码' + shape + '(粘不进去的话改用「下载 SVG」再拖入)')
const text = els ? els.statusText.textContent : ''
window.setTimeout(function () {
if (els && els.statusText.textContent === text) setStatus(null)
}, 2600)
} catch (error) {
setStatus('error', '复制失败:' + (error && error.message ? error.message : String(error)))
} finally {
window.setTimeout(function () {
if (els) { button.disabled = false; button.textContent = label }
}, 1200)
}
}
// ---------- 输出 ----------
function downloadSvg() {
if (!currentSvg) { setStatus('error', '还没有可下载的矢量结果'); return }
const blob = new Blob([currentSvg], { type: 'image/svg+xml;charset=utf-8' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = source.base + '-vector.svg'
document.body.appendChild(a)
a.click()
a.remove()
window.setTimeout(function () { URL.revokeObjectURL(url) }, 4000)
}
async function saveNode(button) {
if (!currentSvg) { setStatus('error', '还没有可保存的矢量结果'); return }
button.disabled = true
const label = button.textContent
button.textContent = '生成中…'
try {
const prepared = prepareSource(source.img)
const blob = await svgToPngBlob(currentSvg, prepared.srcW, prepared.srcH, outScale)
await onSaveNode(blob, source.base + '.png')
close()
} catch (error) {
setStatus('error', error && error.message ? error.message : String(error))
button.disabled = false
button.textContent = label
}
}
// ---------- 事件 ----------
function onPanelInput(event) {
// 勾选开关(按孤岛拆分):只影响输出形态,不动预设,但要立刻重出结果 + 更新统计
const check = event.target.closest('[data-check]')
if (check && els.panel.contains(check)) {
params[check.dataset.check] = check.checked
writeSettings()
retrace()
return
}
const swatch = event.target.closest('[data-color]')
if (swatch && els.panel.contains(swatch)) {
if (!/^#[0-9a-f]{6}$/i.test(swatch.value)) return
if (swatch.dataset.color === 'bg') {
// 背景只影响预览底,不参与轮廓计算 —— 没勾「带底」时完全不用重描摹
params.bg = swatch.value
applyPreviewBg()
writeSettings()
if (params.bgExport) scheduleRetrace()
return
}
params.color = swatch.value
preset = ''
scheduleRetrace()
return
}
const input = event.target.closest('[data-param]')
if (!input || !els.panel.contains(input)) return
const key = input.dataset.param
const raw = Number(input.value)
if (key === 'threshold') {
params.threshold = Math.max(0, Math.min(255, Math.round(raw)))
} else if (key === 'turdSize') {
params.turdSize = Math.max(0, Math.min(40, Math.round(raw)))
}
const out = els.panel.querySelector('[data-val="' + key + '"]')
if (out) out.textContent = input.value
preset = ''
scheduleRetrace()
}
function onPanelClick(event) {
const adv = event.target.closest('[data-act="adv"]')
if (adv) {
const box = els.panel.querySelector('[data-adv]')
if (box) {
const open = box.hidden
box.hidden = !open
advOpen = open
adv.setAttribute('aria-expanded', String(open))
const caret = adv.querySelector('[data-adv-caret]')
if (caret) caret.textContent = open ? '▴' : '▾'
writeSettings()
}
return
}
const presetBtn = event.target.closest('[data-preset]')
if (presetBtn) {
const key = presetBtn.dataset.preset
if (!PRESETS[key]) return
preset = key
params = normalizeParams(Object.assign({}, params, PRESETS[key]))
syncControls()
writeSettings()
retrace()
return
}
const seg = event.target.closest('[data-seg]')
if (!seg) return
const name = seg.dataset.seg
const value = seg.dataset.value
if (name === 'mode') {
params.mode = value === 'mono' ? 'mono' : 'gray'
preset = ''
} else if (name === 'levels') {
params.levels = Math.max(LEVELS_MIN, Math.min(LEVELS_MAX, Number(value) || 3))
preset = ''
} else if (name === 'alphaTone') {
params.alphaMax = ALPHA_TONE[value] === undefined ? 1 : ALPHA_TONE[value]
preset = ''
} else if (name === 'precision') {
params.optTolerance = TOLERANCE_TONES[value] === undefined ? DEFAULTS.optTolerance : TOLERANCE_TONES[value]
preset = ''
} else if (name === 'invert') {
params.invert = value === '1'
preset = ''
} else if (name === 'thrMode') {
params.threshold = value === 'manual' ? 128 : -1
preset = ''
} else if (name === 'outScale') {
outScale = Math.max(1, Math.min(4, Number(value) || 1))
writeSettings()
syncControls()
return
} else {
return
}
syncControls()
scheduleRetrace()
}
function onRootClick(event) {
const act = event.target.closest('[data-act]')
if (!act) return
const name = act.dataset.act
if (name === 'cancel') { close(); return }
if (name === 'copy') { copySvg(act); return }
if (name === 'svg') { downloadSvg(); return }
if (name === 'save') { saveNode(act); return }
}
function onKeyDown(event) {
if (!root) return
if (event.key === 'Escape') {
event.preventDefault()
event.stopPropagation()
close()
return
}
// 视图快捷键:0 复位、+/- 以中心缩放。在滑杆 / 数字框里打字时不抢键
const keyTag = (event.target && event.target.tagName) || ''
if (keyTag !== 'INPUT' && keyTag !== 'TEXTAREA' && keyTag !== 'SELECT') {
if (event.key === '0') { event.preventDefault(); resetView(); return }
if (event.key === '+' || event.key === '=') { event.preventDefault(); zoomAtCenter(1.25); return }
if (event.key === '-' || event.key === '_') { event.preventDefault(); zoomAtCenter(0.8); return }
}
if (event.code === 'Space' && !spaceDown && !event.repeat) {
const tag = (event.target && event.target.tagName) || ''
if (tag === 'INPUT' || tag === 'TEXTAREA') return
event.preventDefault()
spaceDown = true
updateBadge()
}
}
function onKeyUp(event) {
if (event.code === 'Space' && spaceDown) {
spaceDown = false
updateBadge()
}
}
function onBlur() {
if (spaceDown) { spaceDown = false; updateBadge() }
}
function close() {
if (!root) return
seq++
window.clearTimeout(debounceTimer)
document.removeEventListener('keydown', onKeyDown, true)
document.removeEventListener('keyup', onKeyUp, true)
window.removeEventListener('blur', onBlur)
releasePreview()
const node = root
root = null
els = null
// 视图状态跟着会话走:下次打开从「等比铺满」开始
zoom = 1
panX = 0
panY = 0
drag = null
node.remove()
if (typeof onClose === 'function') onClose()
}
// ---------- 打开 ----------
async function open(request) {
if (root) close()
const stored = readSettings()
preset = PRESETS[stored.preset] ? stored.preset : 'text'
params = normalizeParams(Object.assign({}, DEFAULTS, PRESETS[preset], stored))
outScale = Math.max(1, Math.min(4, Math.round(Number(stored.outScale) || 2)))
advOpen = stored.advOpen === undefined ? true : Boolean(stored.advOpen)
const img = await loadImage(request.imageDataUrl)
const name = String(request.name || 'image.png')
const base = name.replace(/\.[^.]+$/, '') || 'image'
source = { img, name, base, srcW: img.naturalWidth || img.width, srcH: img.naturalHeight || img.height }
root = document.createElement('div')
root.innerHTML = viewHTML(name)
document.body.appendChild(root)
els = {
root,
modal: root.querySelector('.vz-modal'),
preview: root.querySelector('.vz-preview'),
panel: root.querySelector('[data-panel]'),
vector: root.querySelector('[data-stage="vector"]'),
original: root.querySelector('[data-stage="original"]'),
badge: root.querySelector('[data-badge]'),
zoomChip: root.querySelector('[data-zoom-chip]'),
zoomVal: root.querySelector('[data-zoom-val]'),
status: root.querySelector('[data-status]'),
statusText: root.querySelector('[data-status-text]'),
meta: root.querySelector('[data-meta]'),
}
els.original.src = request.imageDataUrl
els.meta.textContent = name + ' · ' + source.srcW + '×' + source.srcH
els.panel.innerHTML = panelHTML(params, preset, outScale, advOpen)
root.addEventListener('click', onRootClick)
// 预览视图手势:滚轮/捏合缩放、拖动平移、双击复位、点倍率胶囊复位
els.preview.addEventListener('wheel', onPreviewWheel, { passive: false })
els.preview.addEventListener('pointerdown', onPreviewPointerDown)
els.preview.addEventListener('pointermove', onPreviewPointerMove)
els.preview.addEventListener('pointerup', onPreviewPointerUp)
els.preview.addEventListener('pointercancel', onPreviewPointerUp)
// capture 被系统抢走(切窗口、拖出屏幕)时也要收尾,否则光标会一直卡在 grabbing
els.preview.addEventListener('lostpointercapture', onPreviewPointerUp)
els.preview.addEventListener('dblclick', onPreviewDblClick)
els.preview.addEventListener('click', function (event) {
if (event.target.closest('.vz-zoom')) resetView()
})
els.panel.addEventListener('input', onPanelInput)
els.panel.addEventListener('click', onPanelClick)
document.addEventListener('keydown', onKeyDown, true)
document.addEventListener('keyup', onKeyUp, true)
window.addEventListener('blur', onBlur)
syncControls()
setStats(null)
resetView()
retrace()
return { close }
}
return { open, close }
}
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+458
View File
@@ -0,0 +1,458 @@
'use strict';
var Potrace = require('./Potrace');
var utils = require('./utils');
/**
* Takes multiple samples using {@link Potrace} with different threshold
* settings and combines output into a single file.
*
* @param {Posterizer~Options} [options]
* @constructor
*/
function Posterizer(options) {
this._potrace = new Potrace();
this._calculatedThreshold = null;
this._params = {
threshold: Potrace.THRESHOLD_AUTO,
blackOnWhite: true,
steps: Posterizer.STEPS_AUTO,
background: Potrace.COLOR_TRANSPARENT,
fillStrategy: Posterizer.FILL_DOMINANT,
rangeDistribution: Posterizer.RANGES_AUTO
};
if (options) {
this.setParameters(options);
}
}
// Inherit constants from Potrace class
for (var key in Potrace) {
if (Object.prototype.hasOwnProperty.call(Potrace, key) && key === key.toUpperCase()) {
Posterizer[key] = Potrace[key];
}
}
Posterizer.STEPS_AUTO = -1;
Posterizer.FILL_SPREAD = 'spread';
Posterizer.FILL_DOMINANT = 'dominant';
Posterizer.FILL_MEDIAN = 'median';
Posterizer.FILL_MEAN = 'mean';
Posterizer.RANGES_AUTO = 'auto';
Posterizer.RANGES_EQUAL = 'equal';
Posterizer.prototype = {
/**
* Fine tuning to color ranges.
*
* If last range (featuring most saturated color) is larger than 10% of color space (25 units)
* then we want to add another color stop, that hopefully will include darkest pixels, improving presence of
* shadows and line art
*
* @param ranges
* @private
*/
_addExtraColorStop: function(ranges) {
var blackOnWhite = this._params.blackOnWhite;
var lastColorStop = ranges[ranges.length - 1];
var lastRangeFrom = blackOnWhite ? 0 : lastColorStop.value;
var lastRangeTo = blackOnWhite ? lastColorStop.value : 255;
if (lastRangeTo - lastRangeFrom > 25 && lastColorStop.colorIntensity !== 1) {
var histogram = this._getImageHistogram();
var levels = histogram.getStats(lastRangeFrom, lastRangeTo).levels;
var newColorStop = levels.mean + levels.stdDev <= 25 ? levels.mean + levels.stdDev
: levels.mean - levels.stdDev <= 25 ? levels.mean - levels.stdDev
: 25;
var newStats = (blackOnWhite ? histogram.getStats(0, newColorStop) : histogram.getStats(newColorStop, 255));
var color = newStats.levels.mean;
ranges.push({
value: Math.abs((blackOnWhite ? 0 : 255) - newColorStop),
colorIntensity: isNaN(color) ? 0 : ((blackOnWhite ? 255 - color : color) / 255)
});
}
return ranges;
},
/**
* Calculates color intensity for each element of numeric array
*
* @param {number[]} colorStops
* @returns {{ levels: number, colorIntensity: number }[]}
* @private
*/
_calcColorIntensity: function(colorStops) {
var blackOnWhite = this._params.blackOnWhite;
var colorSelectionStrat = this._params.fillStrategy;
var histogram = colorSelectionStrat !== Posterizer.FILL_SPREAD ? this._getImageHistogram() : null;
var fullRange = Math.abs(this._paramThreshold() - (blackOnWhite ? 0 : 255));
return colorStops.map(function(threshold, index) {
var nextValue = index + 1 === colorStops.length ? (blackOnWhite ? -1 : 256) : colorStops[index + 1];
var rangeStart = Math.round(blackOnWhite ? nextValue + 1 : threshold);
var rangeEnd = Math.round(blackOnWhite ? threshold : nextValue - 1);
var factor = index / (colorStops.length - 1);
var intervalSize = rangeEnd - rangeStart;
var stats = histogram.getStats(rangeStart, rangeEnd);
var color = -1;
if (stats.pixels === 0) {
return {
value: threshold,
colorIntensity: 0
};
}
switch (colorSelectionStrat) {
case Posterizer.FILL_SPREAD:
// We want it to be 0 (255 when white on black) at the most saturated end, so...
color = (blackOnWhite ? rangeStart : rangeEnd)
+ (blackOnWhite ? 1 : -1) * intervalSize * Math.max(0.5, fullRange / 255) * factor;
break;
case Posterizer.FILL_DOMINANT:
color = histogram.getDominantColor(rangeStart, rangeEnd, utils.clamp(intervalSize, 1, 5));
break;
case Posterizer.FILL_MEAN:
color = stats.levels.mean;
break;
case Posterizer.FILL_MEDIAN:
color = stats.levels.median;
break;
}
// We don't want colors to be too close to each other, so we introduce some spacing in between
if (index !== 0) {
color = blackOnWhite
? utils.clamp(color, rangeStart, rangeEnd - Math.round(intervalSize * 0.1))
: utils.clamp(color, rangeStart + Math.round(intervalSize * 0.1), rangeEnd);
}
return {
value: threshold,
colorIntensity: color === -1 ? 0 : ((blackOnWhite ? 255 - color : color) / 255)
};
});
},
/**
* @returns {Histogram}
* @private
*/
_getImageHistogram: function() {
return this._potrace._luminanceData.histogram();
},
/**
* Processes threshold, steps and rangeDistribution parameters and returns normalized array of color stops
* @returns {*}
* @private
*/
_getRanges: function() {
var steps = this._paramSteps();
if (!Array.isArray(steps)) {
return this._params.rangeDistribution === Posterizer.RANGES_AUTO
? this._getRangesAuto()
: this._getRangesEquallyDistributed();
}
// Steps is array of thresholds and we want to preprocess it
var colorStops = [];
var threshold = this._paramThreshold();
var lookingForDarkPixels = this._params.blackOnWhite;
steps.forEach(function(item) {
if (colorStops.indexOf(item) === -1 && utils.between(item, 0, 255)) {
colorStops.push(item);
}
});
if (!colorStops.length) {
colorStops.push(threshold);
}
colorStops = colorStops.sort(function (a, b) {
return a < b === lookingForDarkPixels ? 1 : -1;
});
if (lookingForDarkPixels && colorStops[0] < threshold) {
colorStops.unshift(threshold);
} else if (!lookingForDarkPixels && colorStops[colorStops.length - 1] < threshold) {
colorStops.push(threshold);
}
return this._calcColorIntensity(colorStops);
},
/**
* Calculates given (or lower) number of thresholds using automatic thresholding algorithm
* @returns {*}
* @private
*/
_getRangesAuto: function() {
var histogram = this._getImageHistogram();
var steps = this._paramSteps(true);
var colorStops;
if (this._params.threshold === Potrace.THRESHOLD_AUTO) {
colorStops = histogram.multilevelThresholding(steps);
} else {
var threshold = this._paramThreshold();
colorStops = this._params.blackOnWhite
? histogram.multilevelThresholding(steps - 1, 0, threshold)
: histogram.multilevelThresholding(steps - 1, threshold, 255);
if (this._params.blackOnWhite) {
colorStops.push(threshold);
} else {
colorStops.unshift(threshold);
}
}
if (this._params.blackOnWhite) {
colorStops = colorStops.reverse();
}
return this._calcColorIntensity(colorStops);
},
/**
* Calculates color stops and color representing each segment, returning them
* from least to most intense color (black or white, depending on blackOnWhite parameter)
*
* @private
*/
_getRangesEquallyDistributed: function() {
var blackOnWhite = this._params.blackOnWhite;
var colorsToThreshold = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold();
var steps = this._paramSteps();
var stepSize = colorsToThreshold / steps;
var colorStops = [];
var i = steps - 1,
factor,
threshold;
while (i >= 0) {
factor = i / (steps - 1);
threshold = Math.min(colorsToThreshold, (i + 1) * stepSize);
threshold = blackOnWhite ? threshold : 255 - threshold;
i--;
colorStops.push(threshold);
}
return this._calcColorIntensity(colorStops);
},
/**
* Returns valid steps value
* @param {Boolean} [count=false]
* @returns {number|number[]}
* @private
*/
_paramSteps: function(count) {
var steps = this._params.steps;
if (Array.isArray(steps)) {
return count ? steps.length : steps;
}
if (steps === Posterizer.STEPS_AUTO && this._params.threshold === Potrace.THRESHOLD_AUTO) {
return 4;
}
var blackOnWhite = this._params.blackOnWhite;
var colorsCount = blackOnWhite ? this._paramThreshold() : 255 - this._paramThreshold();
return steps === Posterizer.STEPS_AUTO
? (colorsCount > 200 ? 4 : 3)
: Math.min(colorsCount, Math.max(2, steps));
},
/**
* Returns valid threshold value
* @returns {number}
* @private
*/
_paramThreshold: function() {
if (this._calculatedThreshold !== null) {
return this._calculatedThreshold;
}
if (this._params.threshold !== Potrace.THRESHOLD_AUTO) {
this._calculatedThreshold = this._params.threshold;
return this._calculatedThreshold;
}
var twoThresholds = this._getImageHistogram().multilevelThresholding(2);
this._calculatedThreshold = this._params.blackOnWhite ? twoThresholds[1] : twoThresholds[0];
this._calculatedThreshold = this._calculatedThreshold || 128;
return this._calculatedThreshold;
},
/**
* Running potrace on the image multiple times with different thresholds and returns an array
* of path tags
*
* @param {Boolean} [noFillColor]
* @returns {string[]}
* @private
*/
_pathTags: function(noFillColor) {
var ranges = this._getRanges();
var potrace = this._potrace;
var blackOnWhite = this._params.blackOnWhite;
if (ranges.length >= 10) {
ranges = this._addExtraColorStop(ranges);
}
potrace.setParameters({ blackOnWhite: blackOnWhite });
var actualPrevLayersOpacity = 0;
return ranges.map(function(colorStop) {
var thisLayerOpacity = colorStop.colorIntensity;
if (thisLayerOpacity === 0) {
return '';
}
// NOTE: With big number of layers (something like 70) there will be noticeable math error on rendering side.
// In Chromium at least image will end up looking brighter overall compared to the same layers painted in solid colors.
// However it works fine with sane number of layers, and it's not like we can do much about it.
var calculatedOpacity = (!actualPrevLayersOpacity || thisLayerOpacity === 1)
? thisLayerOpacity
: ((actualPrevLayersOpacity - thisLayerOpacity) / (actualPrevLayersOpacity - 1));
calculatedOpacity = utils.clamp(parseFloat(calculatedOpacity.toFixed(3)), 0, 1);
actualPrevLayersOpacity = actualPrevLayersOpacity + (1 - actualPrevLayersOpacity) * calculatedOpacity;
potrace.setParameters({ threshold: colorStop.value });
var element = noFillColor ? potrace.getPathTag('') : potrace.getPathTag();
element = utils.setHtmlAttr(element, 'fill-opacity', calculatedOpacity.toFixed(3));
var canBeIgnored = calculatedOpacity === 0 || element.indexOf(' d=""') !== -1;
// var c = Math.round(Math.abs((blackOnWhite ? 255 : 0) - 255 * thisLayerOpacity));
// element = utils.setHtmlAttr(element, 'fill', 'rgb('+c+', '+c+', '+c+')');
// element = utils.setHtmlAttr(element, 'fill-opacity', '');
return canBeIgnored ? '' : element;
});
},
/**
* Loads image.
*
* @param {string|Buffer|Jimp} target Image source. Could be anything that {@link Jimp} can read (buffer, local path or url). Supported formats are: PNG, JPEG or BMP
* @param {Function} callback
*/
loadImage: function(target, callback) {
var self = this;
this._potrace.loadImage(target, function(err) {
self._calculatedThreshold = null;
callback.call(self, err);
});
},
/**
* 本项目新增:直接吃浏览器 ImageData(同步),与 Potrace#loadImageData 对应。
* 灰度分层不需要异步读图 ⇒ 调用方拿到的就是同步结果,省掉一层回调。
*/
loadImageData: function(imageData) {
this._potrace.loadImageData(imageData);
this._calculatedThreshold = null;
},
/**
* Sets parameters. Accepts same object as {Potrace}
*
* @param {Posterizer~Options} params
*/
setParameters: function(params) {
if (!params) {
return;
}
this._potrace.setParameters(params);
if (params.steps && !Array.isArray(params.steps) && (!utils.isNumber(params.steps) || !utils.between(params.steps, 1, 255))) {
throw new Error('Bad \'steps\' value');
}
for (var key in this._params) {
if (this._params.hasOwnProperty(key) && params.hasOwnProperty(key)) {
this._params[key] = params[key];
}
}
this._calculatedThreshold = null;
},
/**
* Returns image as <symbol> tag. Always has viewBox specified
*
* @param {string} id
*/
getSymbol: function(id) {
var width = this._potrace._luminanceData.width;
var height = this._potrace._luminanceData.height;
var paths = this._pathTags(true);
return '<symbol viewBox="0 0 ' + width + ' ' + height + '" id="' + id + '">' +
paths.join('') +
'</symbol>';
},
/**
* Generates SVG image
* @returns {String}
*/
getSVG: function() {
var width = this._potrace._luminanceData.width,
height = this._potrace._luminanceData.height;
var tags = this._pathTags(false);
var svg = '<svg xmlns="http://www.w3.org/2000/svg" ' +
'width="' + width + '" ' +
'height="' + height + '" ' +
'viewBox="0 0 ' + width + ' ' + height + '" ' +
'version="1.1">\n\t' +
(this._params.background !== Potrace.COLOR_TRANSPARENT
? '<rect x="0" y="0" width="100%" height="100%" fill="' + this._params.background + '" />\n\t'
: '') +
tags.join('\n\t') +
'\n</svg>';
return svg.replace(/\n(?:\t*\n)+(\t*)/g, '\n$1');
}
};
module.exports = Posterizer;
/**
* Posterizer options
*
* @typedef {Potrace~Options} Posterizer~Options
* @property {Number} [steps] - Number of samples that needs to be taken (and number of layers in SVG). (default: Posterizer.STEPS_AUTO, which most likely will result in 3, sometimes 4)
* @property {*} [fillStrategy] - How to select fill color for color ranges - equally spread or dominant. (default: Posterizer.FILL_DOMINANT)
* @property {*} [rangeDistribution] - How to choose thresholds in-between - after equal intervals or automatically balanced. (default: Posterizer.RANGES_AUTO)
*/
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
'use strict';
var Point = require('./Point');
var utils = require('../utils');
var Histogram;
/**
* Represents a bitmap where each pixel can be a number in range of 0..255
* Used internally to store luminance data.
*
* @param {Number} w
* @param {Number} h
* @constructor
*/
function Bitmap(w, h) {
this._histogram = null;
this.width = w;
this.height = h;
this.size = w * h;
this.arrayBuffer = new ArrayBuffer(this.size);
this.data = new Uint8Array(this.arrayBuffer);
}
module.exports = Bitmap;
Histogram = require('./Histogram');
Bitmap.prototype = {
/**
* Returns pixel value
*
* @param {Number|Point} x - index, point or x
* @param {Number} [y]
*/
getValueAt: function(x, y) {
var index = (typeof x === 'number' && typeof y !== 'number') ? x : this.pointToIndex(x, y);
return this.data[index];
},
/**
* Converts {@link Point} to index value
*
* @param {Number} index
* @returns {Point}
*/
indexToPoint: function(index) {
var point = new Point();
if (utils.between(index, 0, this.size)) {
point.y = Math.floor(index / this.width);
point.x = index - point.y * this.width;
} else {
point.x = -1;
point.y = -1;
}
return point;
},
/**
* Calculates index for point or coordinate pair
*
* @param {Number|Point} pointOrX
* @param {Number} [y]
* @returns {Number}
*/
pointToIndex: function(pointOrX, y) {
var _x = pointOrX,
_y = y;
if (pointOrX instanceof Point) {
_x = pointOrX.x;
_y = pointOrX.y;
}
if (!utils.between(_x, 0, this.width) || !utils.between(_y, 0, this.height)) {
return -1;
}
return this.width * _y + _x;
},
/**
* Makes a copy of current bitmap
*
* @param {Function} [iterator] optional callback, used for processing pixel value. Accepted arguments: value, index
* @returns {Bitmap}
*/
copy: function(iterator) {
var bm = new Bitmap(this.width, this.height),
iteratorPresent = typeof iterator === 'function',
i;
for (i = 0; i < this.size; i++) {
bm.data[i] = iteratorPresent ? iterator(this.data[i], i) : this.data[i];
}
return bm;
},
histogram: function() {
var Histogram = require('./Histogram');
if (this._histogram) {
return this._histogram;
}
this._histogram = new Histogram(this);
return this._histogram;
}
};
+21
View File
@@ -0,0 +1,21 @@
'use strict';
/**
* Curve type
*
* @param n
* @constructor
* @protected
*/
function Curve(n) {
this.n = n;
this.tag = new Array(n);
this.c = new Array(n * 3);
this.alphaCurve = 0;
this.vertex = new Array(n);
this.alpha = new Array(n);
this.alpha0 = new Array(n);
this.beta = new Array(n);
}
module.exports = Curve;
+425
View File
@@ -0,0 +1,425 @@
"use strict";
// Histogram
var utils = require('../utils');
var Jimp = null; try { Jimp = require('jimp'); } catch(e) {}
var Bitmap = require('./Bitmap');
var COLOR_DEPTH = 256;
var COLOR_RANGE_END = COLOR_DEPTH - 1;
/**
* Calculates array index for pair of indexes. We multiple column (x) by 256 and then add row to it,
* this way `(index(i, j) + 1) === index(i, j + i)` thus we can reuse `index(i, j)` we once calculated
*
* Note: this is different from how indexes calculated in {@link Bitmap} class, keep it in mind.
*
* @param x
* @param y
* @returns {*}
* @private
*/
function index(x, y) {
return COLOR_DEPTH * x + y;
}
function normalizeMinMax(levelMin, levelMax) {
/**
* Shared parameter normalization for methods 'multilevelThresholding', 'autoThreshold', 'getDominantColor' and 'getStats'
*
* @param levelMin
* @param levelMax
* @returns {number[]}
* @private
*/
levelMin = typeof levelMin === 'number' ? utils.clamp(Math.round(levelMin), 0, COLOR_RANGE_END) : 0;
levelMax = typeof levelMax === 'number' ? utils.clamp(Math.round(levelMax), 0, COLOR_RANGE_END) : COLOR_RANGE_END;
if (levelMin > levelMax) {
throw new Error('Invalid range "'+ levelMin + '...' + levelMax + '"');
}
return [levelMin, levelMax];
}
/**
* 1D Histogram
*
* @param {Number|Bitmap|Jimp} imageSource - Image to collect pixel data from. Or integer to create empty histogram for image of specific size
* @param [mode] Used only for Jimp images. {@link Bitmap} currently can only store 256 values per pixel, so it's assumed that it contains values we are looking for
* @constructor
* @protected
*/
function Histogram(imageSource, mode) {
this.data = null;
this.pixels = 0;
this._sortedIndexes = null;
this._cachedStats = {};
this._lookupTableH = null;
if (typeof imageSource === 'number') {
this._createArray(imageSource);
} else if (imageSource instanceof Bitmap) {
this._collectValuesBitmap(imageSource);
} else if (Jimp && imageSource instanceof Jimp) {
this._collectValuesJimp(imageSource, mode);
} else {
throw new Error('Unsupported image source');
}
}
Histogram.MODE_LUMINANCE = 'luminance';
Histogram.MODE_R = 'r';
Histogram.MODE_G = 'g';
Histogram.MODE_B = 'b';
Histogram.prototype = {
/**
* Initializes data array for an image of given pixel size
* @param imageSize
* @returns {Uint8Array|Uint16Array|Uint32Array}
* @private
*/
_createArray: function(imageSize) {
var ArrayType = imageSize <= Math.pow(2, 8) ? Uint8Array
: imageSize <= Math.pow(2, 16) ? Uint16Array : Uint32Array;
this.pixels = imageSize;
return this.data = new ArrayType(COLOR_DEPTH);
},
/**
* Aggregates color data from {@link Jimp} instance
* @param {Jimp} source
* @param mode
* @private
*/
_collectValuesJimp: function(source, mode) {
var pixelData = source.bitmap.data;
var data = this._createArray(source.bitmap.width * source.bitmap.height);
source.scan(0, 0, source.bitmap.width, source.bitmap.height, function(x, y, idx) {
var val = mode === Histogram.MODE_R ? pixelData[idx]
: mode === Histogram.MODE_G ? pixelData[idx + 1]
: mode === Histogram.MODE_B ? pixelData[idx + 2]
: utils.luminance(pixelData[idx], pixelData[idx + 1], pixelData[idx + 2]);
data[val]++;
});
},
/**
* Aggregates color data from {@link Bitmap} instance
* @param {Bitmap} source
* @private
*/
_collectValuesBitmap: function(source) {
var data = this._createArray(source.size);
var len = source.data.length;
var color;
for (var i = 0; i < len; i++) {
color = source.data[i];
data[color]++
}
},
/**
* Returns array of color indexes in ascending order
* @param refresh
* @returns {*}
* @private
*/
_getSortedIndexes: function(refresh) {
if (!refresh && this._sortedIndexes) {
return this._sortedIndexes;
}
var data = this.data;
var indexes = new Array(COLOR_DEPTH);
var i = 0;
for (i; i < COLOR_DEPTH; i++) {
indexes[i] = i;
}
indexes.sort(function(a, b) {
return data[a] > data[b] ? 1 : data[a] < data[b] ? -1 : 0;
});
this._sortedIndexes = indexes;
return indexes;
},
/**
* Builds lookup table H from lookup tables P and S.
* see {@link http://www.iis.sinica.edu.tw/page/jise/2001/200109_01.pdf|this paper} for more details
*
* @returns {Float64Array}
* @private
*/
_thresholdingBuildLookupTable: function() {
var P = new Float64Array(COLOR_DEPTH * COLOR_DEPTH);
var S = new Float64Array(COLOR_DEPTH * COLOR_DEPTH);
var H = new Float64Array(COLOR_DEPTH * COLOR_DEPTH);
var pixelsTotal = this.pixels;
var i, j, idx, tmp;
// diagonal
for (i = 1; i < COLOR_DEPTH; ++i) {
idx = index(i, i);
tmp = this.data[i] / pixelsTotal;
P[idx] = tmp;
S[idx] = i * tmp;
}
// calculate first row (row 0 is all zero)
for (i = 1; i < COLOR_DEPTH - 1; ++i) {
tmp = this.data[i + 1] / pixelsTotal;
idx = index(1, i);
P[idx+1] = P[idx] + tmp;
S[idx+1] = S[idx] + (i + 1) * tmp;
}
// using row 1 to calculate others
for (i = 2; i < COLOR_DEPTH; i++) {
for (j=i+1; j < COLOR_DEPTH; j++) {
P[index(i, j)] = P[index(1, j)] - P[index(1, i-1)];
S[index(i, j)] = S[index(1, j)] - S[index(1, i-1)];
}
}
// now calculate H[i][j]
for (i = 1; i < COLOR_DEPTH; ++i) {
for (j = i + 1; j < COLOR_DEPTH; j++) {
idx = index(i, j);
H[idx] = P[idx] !== 0 ? S[idx] * S[idx] / P[idx] : 0;
}
}
return this._lookupTableH = H;
},
/**
* Implements Algorithm For Multilevel Thresholding
* Receives desired number of color stops, returns array of said size. Could be limited to a range levelMin..levelMax
*
* Regardless of levelMin and levelMax values it still relies on between class variances for the entire histogram
*
* @param amount - how many thresholds should be calculated
* @param [levelMin=0] - histogram segment start
* @param [levelMax=255] - histogram segment end
* @returns {number[]}
*/
multilevelThresholding: function (amount, levelMin, levelMax) {
levelMin = normalizeMinMax(levelMin, levelMax);
levelMax = levelMin[1];
levelMin = levelMin[0];
amount = Math.min(levelMax - levelMin - 2, ~~amount);
if (amount < 1) {
return [];
}
if (!this._lookupTableH) {
this._thresholdingBuildLookupTable();
}
var H = this._lookupTableH;
var colorStops = null;
var maxSig = 0;
if (amount > 4) {
console.log('[Warning]: Threshold computation for more than 5 levels may take a long time');
}
function iterateRecursive (startingPoint, prevVariance, indexes, previousDepth) {
startingPoint = (startingPoint || 0) + 1;
prevVariance = prevVariance || 0;
indexes = indexes || (new Array(amount));
previousDepth = previousDepth || 0;
var depth = previousDepth + 1; // t
var variance;
for (var i = startingPoint; i < levelMax - amount + previousDepth; i++) {
variance = prevVariance + H[index(startingPoint, i)];
indexes[depth - 1] = i;
if (depth + 1 < amount + 1) {
// we need to go deeper
iterateRecursive(i, variance, indexes, depth);
} else {
// enough, we can compare values now
variance += H[index(i + 1, levelMax)];
if (maxSig < variance) {
maxSig = variance;
colorStops = indexes.slice();
}
}
}
}
iterateRecursive(levelMin || 0);
return colorStops ? colorStops : [];
},
/**
* Automatically finds threshold value using Algorithm For Multilevel Thresholding
*
* @param {number} [levelMin]
* @param {number} [levelMax]
* @returns {null|number}
*/
autoThreshold: function(levelMin, levelMax) {
var value = this.multilevelThresholding(1, levelMin, levelMax);
return value.length ? value[0] : null;
},
/**
* Returns dominant color in given range. Returns -1 if not a single color from the range present on the image
*
* @param [levelMin=0]
* @param [levelMax=255]
* @param [tolerance=1]
* @returns {number}
*/
getDominantColor: function(levelMin, levelMax, tolerance) {
levelMin = normalizeMinMax(levelMin, levelMax);
levelMax = levelMin[1];
levelMin = levelMin[0];
tolerance = tolerance || 1;
var colors = this.data,
dominantIndex = -1,
dominantValue = -1,
i, j, tmp;
if (levelMin === levelMax) {
return colors[levelMin] ? levelMin : -1;
}
for (i=levelMin; i <= levelMax; i++) {
tmp = 0;
for (j = ~~(tolerance / -2); j < tolerance; j++) {
tmp += utils.between(i + j, 0, COLOR_RANGE_END) ? colors[i + j] : 0;
}
var summIsBigger = tmp > dominantValue;
var summEqualButMainColorIsBigger = dominantValue === tmp && (dominantIndex < 0 || colors[i] > colors[dominantIndex]);
if (summIsBigger || summEqualButMainColorIsBigger) {
dominantIndex = i;
dominantValue = tmp;
}
}
return dominantValue <= 0 ? -1 : dominantIndex;
},
/**
* Returns stats for histogram or its segment.
*
* Returned object contains median, mean and standard deviation for pixel values;
* peak, mean and median number of pixels per level and few other values
*
* If no pixels colors from specified range present on the image - most values will be NaN
*
* @param {Number} [levelMin=0] - histogram segment start
* @param {Number} [levelMax=255] - histogram segment end
* @param {Boolean} [refresh=false] - if cached result can be returned
* @returns {{levels: {mean: (number|*), median: *, stdDev: number, unique: number}, pixelsPerLevel: {mean: (number|*), median: (number|*), peak: number}, pixels: number}}
*/
getStats: function(levelMin, levelMax, refresh) {
levelMin = normalizeMinMax(levelMin, levelMax);
levelMax = levelMin[1];
levelMin = levelMin[0];
if (!refresh && this._cachedStats[levelMin + '-' + levelMax]) {
return this._cachedStats[levelMin + '-' + levelMax];
}
var data = this.data;
var sortedIndexes = this._getSortedIndexes();
var pixelsTotal = 0;
var medianValue = null;
var meanValue;
var medianPixelIndex;
var pixelsPerLevelMean;
var pixelsPerLevelMedian;
var tmpSumOfDeviations = 0;
var tmpPixelsIterated = 0;
var allPixelValuesCombined = 0;
var i, tmpPixels, tmpPixelValue;
var uniqueValues = 0; // counter for levels that's represented by at least one pixel
var mostPixelsPerLevel = 0;
// Finding number of pixels and mean
for (i = levelMin; i <= levelMax; i++) {
pixelsTotal += data[i];
allPixelValuesCombined += data[i] * i;
uniqueValues += data[i] === 0 ? 0 : 1;
if (mostPixelsPerLevel < data[i]) {
mostPixelsPerLevel = data[i];
}
}
meanValue = allPixelValuesCombined / pixelsTotal;
pixelsPerLevelMean = pixelsTotal / (levelMax - levelMin);
pixelsPerLevelMedian = pixelsTotal / uniqueValues;
medianPixelIndex = Math.floor(pixelsTotal / 2);
// Finding median and standard deviation
for (i = 0; i < COLOR_DEPTH; i++) {
tmpPixelValue = sortedIndexes[i];
tmpPixels = data[tmpPixelValue];
if (tmpPixelValue < levelMin || tmpPixelValue > levelMax) {
continue;
}
tmpPixelsIterated += tmpPixels;
tmpSumOfDeviations += Math.pow(tmpPixelValue - meanValue, 2) * tmpPixels;
if (medianValue === null && tmpPixelsIterated >= medianPixelIndex) {
medianValue = tmpPixelValue;
}
}
return this._cachedStats[levelMin + '-' + levelMax] = {
// various pixel counts for levels (0..255)
levels: {
mean: meanValue,
median: medianValue,
stdDev: Math.sqrt(tmpSumOfDeviations / pixelsTotal),
unique: uniqueValues
},
// what's visually represented as bars
pixelsPerLevel: {
mean: pixelsPerLevelMean,
median: pixelsPerLevelMedian,
peak: mostPixelsPerLevel
},
pixels: pixelsTotal
};
}
};
module.exports = Histogram;
+13
View File
@@ -0,0 +1,13 @@
'use strict';
var Point = require('./Point');
function Opti() {
this.pen = 0;
this.c = [new Point(), new Point()];
this.t = 0;
this.s = 0;
this.alpha = 0;
}
module.exports = Opti;
+14
View File
@@ -0,0 +1,14 @@
'use strict';
function Path() {
this.area = 0;
this.len = 0;
this.curve = {};
this.pt = [];
this.minX = 100000;
this.minY = 100000;
this.maxX = -1;
this.maxY = -1;
}
module.exports = Path;
+14
View File
@@ -0,0 +1,14 @@
'use strict';
function Point(x, y) {
this.x = x || 0;
this.y = y || 0;
}
Point.prototype = {
copy: function() {
return new Point(this.x, this.y);
}
};
module.exports = Point;
+11
View File
@@ -0,0 +1,11 @@
'use strict';
function Quad() {
this.data = [0,0,0,0,0,0,0,0,0];
}
Quad.prototype.at = function(x, y) {
return this.data[x * 3 + y];
};
module.exports = Quad;
+11
View File
@@ -0,0 +1,11 @@
'use strict';
function Sum(x, y, xy, x2, y2) {
this.x = x;
this.y = y;
this.xy = xy;
this.x2 = x2;
this.y2 = y2;
}
module.exports = Sum;
+253
View File
@@ -0,0 +1,253 @@
'use strict';
var Point = require('./types/Point');
var attrRegexps = {};
function getAttrRegexp(attrName) {
if (attrRegexps[attrName]) {
return attrRegexps[attrName];
}
attrRegexps[attrName] = new RegExp(' ' + attrName + '="((?:\\\\(?=")"|[^"])+)"', 'i');
return attrRegexps[attrName];
}
function setHtmlAttribute(html, attrName, value) {
var attr = ' ' + attrName + '="' + value + '"';
if (html.indexOf(' ' + attrName + '="') === -1) {
html = html.replace(/<[a-z]+/i, function(beginning) { return beginning + attr; });
} else {
html = html.replace(getAttrRegexp(attrName), attr);
}
return html;
}
function fixed(number) {
return number.toFixed(3).replace('.000', '');
}
function mod(a, n) {
return a >= n ? a % n : a>=0 ? a : n-1-(-1-a) % n;
}
function xprod(p1, p2) {
return p1.x * p2.y - p1.y * p2.x;
}
function cyclic(a, b, c) {
if (a <= c) {
return (a <= b && b < c);
} else {
return (a <= b || b < c);
}
}
function sign(i) {
return i > 0 ? 1 : i < 0 ? -1 : 0;
}
function quadform(Q, w) {
var v = new Array(3), i, j, sum;
v[0] = w.x;
v[1] = w.y;
v[2] = 1;
sum = 0.0;
for (i=0; i<3; i++) {
for (j=0; j<3; j++) {
sum += v[i] * Q.at(i, j) * v[j];
}
}
return sum;
}
function interval(lambda, a, b) {
var res = new Point();
res.x = a.x + lambda * (b.x - a.x);
res.y = a.y + lambda * (b.y - a.y);
return res;
}
function dorth_infty(p0, p2) {
var r = new Point();
r.y = sign(p2.x - p0.x);
r.x = -sign(p2.y - p0.y);
return r;
}
function ddenom(p0, p2) {
var r = dorth_infty(p0, p2);
return r.y * (p2.x - p0.x) - r.x * (p2.y - p0.y);
}
function dpara(p0, p1, p2) {
var x1, y1, x2, y2;
x1 = p1.x - p0.x;
y1 = p1.y - p0.y;
x2 = p2.x - p0.x;
y2 = p2.y - p0.y;
return x1 * y2 - x2 * y1;
}
function cprod(p0, p1, p2, p3) {
var x1, y1, x2, y2;
x1 = p1.x - p0.x;
y1 = p1.y - p0.y;
x2 = p3.x - p2.x;
y2 = p3.y - p2.y;
return x1 * y2 - x2 * y1;
}
function iprod(p0, p1, p2) {
var x1, y1, x2, y2;
x1 = p1.x - p0.x;
y1 = p1.y - p0.y;
x2 = p2.x - p0.x;
y2 = p2.y - p0.y;
return x1*x2 + y1*y2;
}
function iprod1(p0, p1, p2, p3) {
var x1, y1, x2, y2;
x1 = p1.x - p0.x;
y1 = p1.y - p0.y;
x2 = p3.x - p2.x;
y2 = p3.y - p2.y;
return x1 * x2 + y1 * y2;
}
function ddist(p, q) {
return Math.sqrt((p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y));
}
module.exports = {
luminance: function (r, g, b) {
return Math.round(0.2126 * r + 0.7153 * g + 0.0721 * b);
},
between: function(val, min, max) {
return val >= min && val <= max;
},
clamp: function(val, min, max) {
return Math.min(max, Math.max(min, val));
},
isNumber: function(val) {
return typeof val === 'number';
},
setHtmlAttr: setHtmlAttribute,
/**
* Generates path instructions for given curve
*
* @param {Curve} curve
* @param {Number} [scale]
* @returns {string}
*/
renderCurve: function(curve, scale) {
scale = scale || { x: 1, y: 1 };
var startingPoint = curve.c[(curve.n - 1) * 3 + 2];
var path = [
'M '
+ fixed(startingPoint.x * scale.x) + ' '
+ fixed(startingPoint.y * scale.y)
];
curve.tag.forEach(function(tag, i) {
var i3 = i * 3;
var p0 = curve.c[i3];
var p1 = curve.c[i3 + 1];
var p2 = curve.c[i3 + 2];
if (tag === "CURVE") {
path.push(
'C '
+ fixed(p0.x * scale.x) + ' ' + fixed(p0.y * scale.y) + ', '
+ fixed(p1.x * scale.x) + ' ' + fixed(p1.y * scale.y) + ', '
+ fixed(p2.x * scale.x) + ' ' + fixed(p2.y * scale.y)
);
} else if (tag === "CORNER") {
path.push(
'L '
+ fixed(p1.x * scale.x) + ' ' + fixed(p1.y * scale.y) + ' '
+ fixed(p2.x * scale.x) + ' ' + fixed(p2.y * scale.y)
);
}
});
return path.join(' ');
},
bezier: function bezier(t, p0, p1, p2, p3) {
var s = 1 - t, res = new Point();
res.x = s*s*s*p0.x + 3*(s*s*t)*p1.x + 3*(t*t*s)*p2.x + t*t*t*p3.x;
res.y = s*s*s*p0.y + 3*(s*s*t)*p1.y + 3*(t*t*s)*p2.y + t*t*t*p3.y;
return res;
},
tangent: function tangent(p0, p1, p2, p3, q0, q1) {
var A, B, C, a, b, c, d, s, r1, r2;
A = cprod(p0, p1, q0, q1);
B = cprod(p1, p2, q0, q1);
C = cprod(p2, p3, q0, q1);
a = A - 2 * B + C;
b = -2 * A + 2 * B;
c = A;
d = b * b - 4 * a * c;
if (a===0 || d<0) {
return -1.0;
}
s = Math.sqrt(d);
r1 = (-b + s) / (2 * a);
r2 = (-b - s) / (2 * a);
if (r1 >= 0 && r1 <= 1) {
return r1;
} else if (r2 >= 0 && r2 <= 1) {
return r2;
} else {
return -1.0;
}
},
mod: mod,
xprod: xprod,
cyclic: cyclic,
sign: sign,
quadform: quadform,
interval: interval,
dorth_infty: dorth_infty,
ddenom: ddenom,
dpara: dpara,
cprod: cprod,
iprod: iprod,
iprod1: iprod1,
ddist: ddist
};
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
// 引擎单文件打包(开发用):把 plugin/engine.js + potrace 打成 IIFE 全局 VZEngine,便于在
// 浏览器里直接跑参数实验(tools/trace-cli.mjs 用它)。发布不走这里 —— 发布走根目录
// scripts/build-plugin.mjs(esbuild → 单文件 IIFE 插件)。
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { createRequire } from 'node:module'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const PLUGIN = path.resolve(HERE, '../plugin')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const REPO = path.resolve(HERE, '../..')
export function esbuildModule() {
for (const base of [HOST_REPO, REPO, process.cwd()]) {
try {
return createRequire(path.join(base, 'package.json'))('esbuild')
} catch {
/* 试下一个 */
}
}
throw new Error('找不到 esbuild(宿主仓 node_modules 里应该有)')
}
export function bundleEngine(outfile = '/tmp/vz-engine.bundle.js') {
const esbuild = esbuildModule()
esbuild.buildSync({
entryPoints: [path.join(PLUGIN, 'engine.js')],
bundle: true,
format: 'iife',
globalName: 'VZEngine',
platform: 'browser',
target: ['chrome110'],
outfile,
logLevel: 'error',
})
return outfile
}
+276
View File
@@ -0,0 +1,276 @@
// 真实站点端到端(开发用,不进 CI)。
//
// 与 harness 的分工:harness 用合成宿主,能验功能但不能验真实 CSP/网络;这里走真站 ——
// 真实的 `_headers`(**不含 wasm-unsafe-eval**)、真实 KV、浏览器 SRI 校验、真实画布桥。
// v0.2 是纯 JS potrace,所以这里反而要断言「wasm 仍被 CSP 拦住」——防止有人为了别的功能
// 悄悄把 'wasm-unsafe-eval' 加回去。
//
// 运行:
// node image-vectorize/tools/e2e-site.mjs
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-vectorize/tools/e2e-site.mjs
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const PLUGIN_ID = 'image-vectorize'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-vectorize/package.json'), 'utf8')).version
const CFG = { providers: [], canvas: {} }
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const poll = async (fn, timeout = 25000, step = 250) => {
const end = Date.now() + timeout
for (;;) {
let v
try { v = await fn() } catch { v = false }
if (v) return v
if (Date.now() > end) return false
await sleep(step)
}
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
const browser = await chromium.launch()
// 剪贴板要显式授权(真站是 https,安全上下文成立;本地 file/about:blank 测不到这条)
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } })
try {
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(BASE).origin })
} catch (error) {
console.log('(剪贴板授权失败,相关断言会跳过:' + (error && error.message) + ')')
}
const page = await context.newPage()
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
await page.goto('about:blank')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 320; c.height = 320
const g = c.getContext('2d')
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 320, 320)
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(96, 96, 58, 0, Math.PI * 2); g.fill()
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(170, 130, 120, 84, 12); g.fill()
g.fillStyle = '#111111'; g.font = 'bold 38px "PingFang SC", sans-serif'; g.fillText('菜单', 96, 250)
return c.toDataURL('image/png')
})
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
const ws = JSON.parse(JSON.stringify(d.ws))
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ [d.id]: { enabled: true, settings: {}, data: {} } }))
}, { cfg: CFG, ws: WS, png: PNG, id: PLUGIN_ID })
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
// ---------- 1) 真实 KV 加载 + SRI ----------
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
const active = await poll(async () => page.evaluate((id) => {
const p = window.IWBPluginHost.list().find((x) => x.id === id)
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
}, PLUGIN_ID))
check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active))
check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
check('插件脚本用 SRI(sha256) 加载',
scripts.some((s) => s.src.indexOf('/plugins/plugin-' + PLUGIN_ID + '.') === 0 && /^sha256-/.test(s.integrity)),
JSON.stringify(scripts.map((s) => s.src)))
// ---------- 2) 宿主 CSP 不再放行 wasm(v0.2 纯 JS,不需要放宽) ----------
const cspProbe = await page.evaluate(async () => {
try {
const b = Uint8Array.from(atob('AGFzbQEAAAA='), (c) => c.charCodeAt(0))
await WebAssembly.instantiate(b)
return 'ok'
} catch (e) { return 'blocked: ' + e.message }
})
check('宿主 CSP 仍禁止 wasm 编译(本插件是纯 JS,不该再放宽)', cspProbe.indexOf('blocked') === 0, cspProbe.slice(0, 120))
// ---------- 3) 打开工作区 ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
// ---------- 4) 入口 → 模态 ----------
await page.locator('.iwb-node[data-node-id="r1"]').click()
const floatBtn = page.locator('.iwb-node-floatbar button[title="位图转矢量"]')
let entry = ''
if (await floatBtn.count()) {
await floatBtn.click()
entry = '漂浮菜单'
} else {
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '位图转矢量' }).first().click()
entry = '右键命令'
}
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 30000 })
check('节点入口可触发(' + entry + ')', true)
check('样式注入生效(CSP unsafe-inline)', await page.evaluate(() => {
const s = document.getElementById('iwb-vectorize-style')
return Boolean(s && s.textContent.indexOf('.vz-') >= 0)
}))
// 用户 2026-11-09:取消与保存为节点互换,四颗按钮同一套描边配色(绿色主按钮已去掉)。
// 这条同时是「线上真的是新版」的活体证据 —— 光看版本号挡不住产物没重建。
check('顶栏顺序 保存为节点→复制→下载→取消,四颗同色', await page.evaluate(() => {
const btns = [...document.querySelectorAll('.vz-header .vz-btn')]
if (btns.map((b) => b.dataset.act).join(',') !== 'save,copy,svg,cancel') return false
const colors = new Set(btns.map((b) => getComputedStyle(b).backgroundColor + '|' + getComputedStyle(b).color))
return colors.size === 1
}))
// ---------- 5) 真站 CSP 下引擎能跑 ----------
const paths = await poll(async () => {
// 统计项是「元素」,合并模式下会带后缀「(N 孤岛合并)」,只取前面的数字
const t = await page.locator('[data-stat="elements"]').textContent()
const m = /^\s*(\d+)/.exec(t || '')
return m && Number(m[1]) > 0 ? m[1] : false
}, 30000)
check('真站描摹成功(纯 JS 引擎,无 wasm)', Boolean(paths), '元素=' + paths)
check('默认按孤岛拆分(元素数 > 层数)', Number(paths) > 3, '元素=' + paths)
check('预览为 blob: SVG', await page.evaluate(() => {
const v = document.querySelector('[data-stage="vector"]')
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
}))
const stats = await page.evaluate(() => ({
levels: Number(document.querySelector('[data-stat="levels"]').textContent),
bytes: document.querySelector('[data-stat="bytes"]').textContent,
ms: document.querySelector('[data-stat="ms"]').textContent,
}))
check('灰度层数正常(3 层)', stats.levels >= 3, JSON.stringify(stats))
// ---------- 5.5) 面板形态:高级默认打开 + 精度默认精细 ----------
check('高级参数默认展开', await page.evaluate(() => {
const box = document.querySelector('[data-adv]')
return Boolean(box && !box.hidden)
}))
check('精度默认「精细」', await page.evaluate(() => {
const a = document.querySelector('[data-seg-group="precision"] button.active')
return Boolean(a && a.dataset.value === 'fine')
}))
// v0.3.1:预览白底 + 填充/背景并排(真站 CSP 下 CSS 得真生效,不能只信本地)
check('预览区白底、无棋盘格', await page.evaluate(() => {
const cs = getComputedStyle(document.querySelector('.vz-preview'))
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(cs.backgroundColor)
return Boolean(m) && Number(m[1]) > 240 && cs.backgroundImage === 'none'
}))
check('「填充 / 背景」两个色块并排在同一行', await page.evaluate(() => {
const a = document.querySelector('[data-color="color"]')
const b = document.querySelector('[data-color="bg"]')
if (!a || !b) return false
const ra = a.getBoundingClientRect()
const rb = b.getBoundingClientRect()
return Math.abs(ra.top - rb.top) < 2 && rb.left > ra.right - 1
}))
// v0.4.0:预览缩放 / 平移(真站上鼠标手势得真能走通,不能只信本地合成宿主)
const pvBox = await page.locator('.vz-preview').boundingBox()
await page.mouse.move(pvBox.x + pvBox.width / 2 + 40, pvBox.y + pvBox.height / 2 - 20)
await page.mouse.wheel(0, -300)
await sleep(220)
// 断言「换算比例」而不是「比容器大」:正方形图 fit 进宽屏预览后本来就比容器窄,
// 拿 rect.width > clientWidth 会比较,放大了也可能不成立(实测真站 549 vs 1011)
check('滚轮放大预览、倍率胶囊出现', await page.evaluate(() => {
const p = document.querySelector('.vz-preview')
const v = document.querySelector('[data-stage="vector"]')
const z = Number(p.style.getPropertyValue('--vz-zoom') || 1)
const chip = document.querySelector('[data-zoom-chip]')
const ratio = v.getBoundingClientRect().width / v.clientWidth
return z > 1.1 && Boolean(chip) && !chip.hidden && Math.abs(ratio - z) < 0.02
}))
await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2)
await sleep(220)
check('双击复位回 100%', await page.evaluate(() => {
const p = document.querySelector('.vz-preview')
return Number(p.style.getPropertyValue('--vz-zoom') || 1) === 1
}))
// 回归:平滑滚轮(小数 deltaY)在真站也必须缩放。旧逻辑靠整数步长识别鼠标,会把这类滚轮当平移。
await page.evaluate(() => {
const p = document.querySelector('.vz-preview')
const r = p.getBoundingClientRect()
p.dispatchEvent(new WheelEvent('wheel', {
deltaY: -12.5, deltaMode: 0, bubbles: true, cancelable: true,
clientX: r.left + r.width / 2, clientY: r.top + r.height / 2,
}))
})
await sleep(160)
check('真站:小数步长滚轮照样放大', await page.evaluate(() => {
const p = document.querySelector('.vz-preview')
return Number(p.style.getPropertyValue('--vz-zoom') || 1) > 1.001
}))
await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2)
await sleep(160)
// ---------- 5.6) 复制到剪贴板(真写,读回校验口味) ----------
await page.locator('[data-act="copy"]').click()
await sleep(400)
const clip = await page.evaluate(async () => {
try {
const items = await navigator.clipboard.read()
const types = items[0] ? items[0].types : []
let svg = ''
if (types.indexOf('image/svg+xml') >= 0) svg = await (await items[0].getType('image/svg+xml')).text()
return { types, svg, status: (document.querySelector('[data-status-text]') || {}).textContent || '' }
} catch (e) { return { error: String(e && e.message) } }
})
if (clip.error) {
check('复制 SVG 写入剪贴板', false, clip.error)
} else {
check('复制 SVG:剪贴板含 image/svg+xml(Figma 按矢量粘贴)',
clip.types.indexOf('image/svg+xml') >= 0 && clip.svg.indexOf('<svg') === 0 && clip.svg.indexOf('<path') > 0,
clip.types.join(',') + ' / ' + clip.svg.length + 'B')
check('复制后给了反馈', /已复制/.test(clip.status), clip.status)
// 拆分是这个版本的核心诉求:粘到 Figma 必须是多个可单独选中的图层,而不是一个整体
const pathCount = (clip.svg.match(/<path/g) || []).length
check('剪贴板里是多个独立 path(Figma 可单独选中,不是一个整体)', pathCount >= 5 && !/<g\b/.test(clip.svg), 'path 元素=' + pathCount)
}
// ---------- 6) 保存为节点(真实画布桥) ----------
await page.locator('[data-act="save"]').click()
const saved = await poll(async () => (await page.locator('.iwb-node').count()) >= 2, 25000)
check('保存为节点:画布新增一个图片节点', Boolean(saved), 'nodes=' + await page.locator('.iwb-node').count())
check('模态已关闭', (await page.locator('.vz-root').count()) === 0)
const fatal = consoleErrors.filter((e) => /Content Security Policy|Refused to|SRI|integrity/i.test(e))
check('无 CSP / SRI 报错', fatal.length === 0, fatal.slice(0, 2).join(' | '))
if (consoleErrors.length) {
console.log('')
console.log('控制台错误(' + consoleErrors.length + ' 条,前 5 条):')
for (const e of consoleErrors.slice(0, 5)) console.log(' ' + String(e).slice(0, 180))
}
console.log('')
console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')
await browser.close()
process.exit(failed ? 1 : 0)
+574
View File
@@ -0,0 +1,574 @@
// 位图转矢量(potrace 单色/灰度):本地端到端(开发用,不进 CI)。
//
// 直接把构建产物注入合成宿主,在真实 Chromium 里验证:
// 注册 / 模态 / 单色描摹 / 灰度分层(层数联动)/ 参数联动 / 反相 / 去小点 / 颜色 /
// 下载 SVG / 保存为 PNG 节点 / 空格对比 / Esc 关闭 / 参数记忆。
//
// 页面刻意带上**与线上同款的 CSP**(`script-src 'self'`,没有 wasm-unsafe-eval):
// potrace 是纯 JS,这条断言顺带证明「本版不再需要放宽 CSP」。
//
// 运行:node image-vectorize/tools/harness.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
const WANT_VERSION = JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8')).version
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT')
process.exit(2)
}
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const waitText = async (page, sel, timeout = 8000) => {
const end = Date.now() + timeout
for (;;) {
const t = await page.locator(sel).textContent().catch(() => null)
if (t && t !== '–') return t
if (Date.now() > end) return false
await sleep(100)
}
}
// 统计里的「元素」可能带后缀「(N 孤岛合并)」,这里只取前面的数字
const pathsNow = async (page) => {
const text = await page.locator('[data-stat="elements"]').textContent().catch(() => '')
const m = /^\s*(\d+)/.exec(text || '')
return m ? m[1] : ''
}
const levelsNow = (page) => page.locator('[data-stat="levels"]').textContent()
const svgNow = (page) => page.evaluate(() => {
const img = document.querySelector('[data-stage="vector"]')
if (!img || !img.src) return ''
return window.__lastSvg || ''
})
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
const errors = []
page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()) })
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message))
page.on('dialog', (d) => { errors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
// 与线上 _headers 的 /* 组保持一致(**故意不带 wasm-unsafe-eval**)
const CSP = "default-src 'self'; script-src 'self'; style-src 'unsafe-inline'; img-src data: blob:; connect-src https: http:"
await page.setContent('<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="' + CSP + '"><style>body{margin:0}</style></head><body><div id="host"></div></body></html>')
// 测试图:白底 + 红圆 + 蓝圆角矩形 + 黑色中文 + 绿色曲线(实心/圆角/文字/描边四类形态),
// 外加几个 1–2px 的孤立噪点(用来验证「去小点」真的吃掉它们)
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 480; c.height = 480
const g = c.getContext('2d')
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 480, 480)
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(140, 140, 88, 0, Math.PI * 2); g.fill()
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(252, 190, 176, 120, 16); g.fill()
g.fillStyle = '#111111'; g.font = 'bold 54px "PingFang SC", sans-serif'; g.fillText('菜单', 146, 372)
g.strokeStyle = '#2e9e6b'; g.lineWidth = 5
g.beginPath(); g.moveTo(70, 428); g.bezierCurveTo(176, 396, 306, 468, 412, 420); g.stroke()
for (const [x, y] of [[40, 40], [60, 44], [44, 62], [452, 60]]) g.fillRect(x, y, 2, 2)
return c.toDataURL('image/png')
})
await page.evaluate(() => {
window.IWBPluginHost = { register(manifest, factory) { window.__manifest = manifest; window.__factory = factory } }
window.__actions = {}
window.__commands = {}
window.__settings = {}
window.__writes = []
// 抓每次产出的 SVG 原文:断言要能看内容(反相/颜色/层数),不能只数路径
window.__svgSeq = 0
window.__lastSvg = ''
const origCreate = URL.createObjectURL.bind(URL)
URL.createObjectURL = function (blob) {
const url = origCreate(blob)
if (blob && typeof blob.text === 'function' && String(blob.type || '').indexOf('image/svg') === 0) {
blob.text().then((t) => { window.__lastSvg = t; window.__svgSeq++ })
}
return url
}
})
// 产物用 CDP 直接执行注入:本页带 CSP(script-src 无 unsafe-inline),addScriptTag 会被拦。
await page.evaluate(readFileSync(PLUGIN_ENTRY, 'utf8'))
const boot = await page.evaluate((png) => {
const ctx = {
id: 'image-vectorize', manifest: window.__manifest, apiVersion: 1,
log() {},
settings: {
get(k) { return window.__settings[k] },
set(k, v) { window.__settings[k] = v },
all() { return { ...window.__settings } },
},
storage: { get() {}, set() {}, remove() {}, keys() { return [] } },
events: { on() { return () => {} }, emit() { return true } },
canvas: {
getNodeImage() { return { dataUrl: png } },
getSelectedNode() { return { id: 'r1', type: 'ref', name: 'src.png' } },
setNodeImage() { window.__writes.push({ kind: 'replace' }); return true },
createImageNode(o) { window.__writes.push({ kind: 'newNode', name: o.name, head: String(o.dataUrl).slice(0, 22), len: String(o.dataUrl).length }); return { id: 'r2' } },
},
nodeActions: { register(r) { window.__actions[r.id] = r } },
commands: { register(r) { window.__commands[r.id] = r } },
}
window.__plugin = window.__factory(ctx)
return {
version: window.__manifest.version,
capabilities: window.__manifest.capabilities,
actions: Object.keys(window.__actions),
commands: Object.keys(window.__commands),
settings: Object.keys(window.__manifest.settings || {}),
icons: Object.keys(window.__actions).map((id) => String(window.__actions[id].icon || ''))
.concat(Object.keys(window.__commands).map((id) => String(window.__commands[id].icon || ''))),
}
}, PNG)
check('产物可执行(IIFE 打包 + 注册成功)', boot.version === WANT_VERSION, 'version=' + boot.version)
check('注册了节点动作与命令', boot.actions.includes('vectorize-node') && boot.commands.includes('vectorize-selected'), boot.actions.join(','))
// 图标不能与别的插件撞车:'vector-square' 是 white-bg-800 的,两个插件同屏时认不出谁是谁(用户实测反馈过)
check('节点动作图标是钢笔笔头(不与 white-bg-800 的 vector-square 重复)', boot.icons.indexOf('pen-tool') >= 0 && boot.icons.indexOf('vector-square') < 0, boot.icons.join(','))
check('manifest 声明了参数记忆项', ['mode', 'levels', 'turdSize', 'alphaMax', 'optTolerance', 'invert', 'color', 'outScale', 'advOpen', 'splitIslands'].every((k) => boot.settings.includes(k)), boot.settings.length + ' 项')
check('capabilities 含 canvasWrite(要写回节点)', boot.capabilities.includes('canvasWrite'), boot.capabilities.join(','))
// ---------- 打开模态 ----------
await page.evaluate(() => { window.__actions['vectorize-node'].run({ id: 'r1', type: 'ref', name: 'src.png' }) })
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 15000 })
check('模态打开:预览区 + 参数面板 + 四个动作按钮齐全', await page.evaluate(() =>
Boolean(document.querySelector('.vz-preview') && document.querySelector('.vz-panel') &&
document.querySelector('[data-act="save"]') && document.querySelector('[data-act="svg"]') &&
document.querySelector('[data-act="copy"]') && document.querySelector('[data-act="cancel"]'))))
// 用户 2026-11-09:顶栏「取消」与「保存为节点」互换(主操作在左、取消在最右),
// 且不再给主操作上绿色 —— 四颗按钮用同一套描边配色。
check('顶栏顺序:保存为节点 → 复制 → 下载 → 取消,且四颗同色', await page.evaluate(() => {
const btns = [...document.querySelectorAll('.vz-header .vz-btn')]
if (btns.map((b) => b.dataset.act).join(',') !== 'save,copy,svg,cancel') return false
const colors = new Set(btns.map((b) => getComputedStyle(b).backgroundColor + '|' + getComputedStyle(b).color))
return colors.size === 1
}))
// 高级参数默认展开:用户 2026-11-05 明确要求「不用隐藏」(低频项也一眼能看到)
check('高级参数默认展开', await page.evaluate(() => {
const box = document.querySelector('[data-adv]')
const toggle = document.querySelector('[data-act="adv"]')
return Boolean(box && !box.hidden && toggle && toggle.getAttribute('aria-expanded') === 'true')
}))
check('精度档默认「精细」(optTolerance 0.05)', await page.evaluate(() => {
const active = document.querySelector('[data-seg-group="precision"] button.active')
return Boolean(active && active.dataset.value === 'fine')
}))
const p0 = await waitText(page, '[data-stat="elements"]')
check('纯 JS 引擎在宿主 CSP 下跑通(无需 wasm-unsafe-eval)', Boolean(p0), 'paths=' + p0)
check('默认预设「文字 / 线稿」= 单色', await page.evaluate(() => {
const row = document.querySelector('[data-seg-group="mode"] button.active')
return Boolean(row && row.dataset.value === 'mono')
}))
// ---------- 预览与棋盘 ----------
check('预览是矢量(blob: SVG 且不是原图)', await page.evaluate(() => {
const v = document.querySelector('[data-stage="vector"]')
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
}))
// v0.3.1 起预览区改纯白底(用户要求「直接用白色,不用透明背景展示」),
// 同时断言没有残留棋盘(background-image 必须是 none),并顺带确认导出 SVG 仍透明
check('预览区白底、无棋盘格', await page.evaluate(() => {
const cs = getComputedStyle(document.querySelector('.vz-preview'))
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(cs.backgroundColor)
if (!m) return false
const lum = (Number(m[1]) + Number(m[2]) + Number(m[3])) / 3
return lum > 240 && cs.backgroundImage === 'none'
}))
// ---------- 预览视图:缩放 / 平移(2026-11-09 用户需求) ----------
const viewState = () => page.evaluate(() => {
const p = document.querySelector('[data-preview]')
return {
zoom: Number(p.style.getPropertyValue('--vz-zoom') || 1),
panX: parseFloat(p.style.getPropertyValue('--vz-pan-x') || '0'),
panY: parseFloat(p.style.getPropertyValue('--vz-pan-y') || '0'),
chip: !document.querySelector('[data-zoom-chip]').hidden,
label: document.querySelector('[data-zoom-val]').textContent,
}
})
const fit = await viewState()
check('默认等比铺满(100%),倍率胶囊不出现', fit.zoom === 1 && fit.panX === 0 && fit.panY === 0 && !fit.chip)
const pv = await page.locator('[data-preview]').boundingBox()
const cx = pv.x + pv.width / 2
const cy = pv.y + pv.height / 2
// 鼠标刻意偏离中心,用来验证「以光标为锚点」而不是「以中心缩放」
await page.mouse.move(cx + 60, cy - 40)
await page.mouse.wheel(0, -300)
await sleep(140)
const zoomed = await viewState()
check('滚轮向上放大', zoomed.zoom > 1.1 && zoomed.chip, 'zoom=' + zoomed.zoom)
check('缩放锚在光标处(偏离中心缩放会带动平移)',
Math.abs(zoomed.panX) > 1 || Math.abs(zoomed.panY) > 1,
'pan=' + zoomed.panX.toFixed(1) + ',' + zoomed.panY.toFixed(1))
check('倍率胶囊显示当前百分比', /^\d+%$/.test(zoomed.label) && zoomed.label !== '100%', zoomed.label)
await page.mouse.move(cx, cy)
await page.mouse.down()
await page.mouse.move(cx + 50, cy + 30, { steps: 6 })
await page.mouse.up()
await sleep(140)
const panned = await viewState()
check('拖动平移(位移跟手,1:1 不缩放)',
Math.abs(panned.panX - zoomed.panX - 50) < 3 && Math.abs(panned.panY - zoomed.panY - 30) < 3,
'pan=' + panned.panX.toFixed(1) + ',' + panned.panY.toFixed(1))
// 开发用:VZ_SHOT=/tmp/vz-zoom.png 出一张「放大 + 平移」状态的截图
if (process.env.VZ_SHOT) await page.locator('.vz-modal').screenshot({ path: process.env.VZ_SHOT })
await page.mouse.dblclick(cx, cy)
await sleep(140)
const reset = await viewState()
check('双击复位回 100% 且胶囊消失',
reset.zoom === 1 && reset.panX === 0 && reset.panY === 0 && !reset.chip)
// 回归:滚轮必须无条件缩放。早先靠「deltaY 是 ±100 整数」识别鼠标滚轮,
// 平滑滚动/高精度滚轮给小数步长时会被判成触控板滑动 → 退化成平移,用户看到「滚轮不放大」。
const wheelBy = (deltaY, deltaX) => page.evaluate(([dy, dx]) => {
const p = document.querySelector('[data-preview]')
const r = p.getBoundingClientRect()
p.dispatchEvent(new WheelEvent('wheel', {
deltaY: dy, deltaX: dx, deltaMode: 0, bubbles: true, cancelable: true,
clientX: r.left + r.width / 2, clientY: r.top + r.height / 2,
}))
}, [deltaY, deltaX])
await wheelBy(-12.5, 0) // 小数步长 = 平滑滚轮 / 触控板
await sleep(90)
const smooth = await viewState()
check('滚轮给小数步长也缩放(不被误判成触控板滑动)', smooth.zoom > 1.001, 'zoom=' + smooth.zoom)
await wheelBy(0, -60) // 纯水平滚动(Shift+滚轮在 Chrome 里就是这种)
await sleep(90)
const horiz = await viewState()
check('水平滚动只平移、不改倍率', horiz.zoom === smooth.zoom && Math.abs(horiz.panX - smooth.panX) > 20,
'panX=' + horiz.panX.toFixed(1))
await page.mouse.dblclick(cx, cy)
await sleep(120)
await page.mouse.move(cx, cy)
await page.mouse.down()
await page.mouse.move(cx + 40, cy + 20, { steps: 5 })
await page.mouse.up()
await sleep(90)
const dragAt1x = await viewState()
check('100% 状态左键也能拖图(不要求先放大)',
dragAt1x.zoom === 1 && Math.abs(dragAt1x.panX - 40) < 3 && Math.abs(dragAt1x.panY - 20) < 3,
'pan=' + dragAt1x.panX.toFixed(1) + ',' + dragAt1x.panY.toFixed(1))
await page.mouse.dblclick(cx, cy)
await sleep(120)
const monoPaths = Number(await pathsNow(page))
const monoMs = Number((await page.locator('[data-stat="ms"]').textContent()).replace(/[^\d]/g, ''))
check('单色描摹产出元素(文字图形都在)', monoPaths >= 1 && monoPaths <= 80, 'elements=' + monoPaths)
check('描摹耗时 < 1.5s(480×480)', monoMs > 0 && monoMs < 1500, monoMs + 'ms')
check('单色模式没有 fill-opacity(真单色,不是灰度伪装)', await page.evaluate(() => !/fill-opacity/.test(window.__lastSvg || '')), '')
// ---------- 孤岛拆分(用户 2026-11-05 需求:元素不要是一个整体) ----------
// potrace 出厂把整图所有轮廓塞进一个 <path>,粘到 Figma 只是一个整体。
// 拆分后每个不连通的图形要成为**并列的 path 元素**,且不能包 <g>(包了 Figma 里就是组)。
const splitSvg = await page.evaluate(() => window.__lastSvg || '')
const splitStat = await page.evaluate(() => ({
paths: (String(window.__lastSvg || '').match(/<path/g) || []).length,
groups: (String(window.__lastSvg || '').match(/<g\b/g) || []).length,
text: (document.querySelector('[data-stat="elements"]') || {}).textContent || '',
}))
check('默认按孤岛拆分:多个独立 path 元素(不再是一个整体)', splitStat.paths >= 4, 'path 元素=' + splitStat.paths)
check('拆分后不包 <g>(Figma 顶层直接是可单独选中的图层)', splitStat.groups === 0, 'g=' + splitStat.groups)
check('统计显示拆分后的元素数', Number(splitStat.text) === splitStat.paths, splitStat.text + ' vs ' + splitStat.paths)
// 关掉勾选 ⇒ 合并回 1 个 path(同一份几何,只是打包方式不同)
await page.locator('[data-check="splitIslands"]').uncheck({ force: true })
await sleep(500)
const wholeSvg = await page.evaluate(() => window.__lastSvg || '')
const wholeStat = await page.evaluate(() => ({
paths: (String(window.__lastSvg || '').match(/<path/g) || []).length,
text: (document.querySelector('[data-stat="elements"]') || {}).textContent || '',
}))
check('取消勾选「按孤岛拆分」⇒ 合并为 1 个 path', wholeStat.paths === 1, 'path 元素=' + wholeStat.paths)
check('合并时统计明说「N 孤岛合并」(否则看着像描摹漏画了)', /孤岛合并/.test(wholeStat.text), wholeStat.text)
// 几何必须一模一样:拆分只改「怎么打包」,不该改「画什么」。
// 注意别比 d 的**字符长度** —— 拆分会把 `60.000` 重新格式化成 `60`,长度天然变短(实测 -3%),
// 那是格式差不是几何差。要逐个坐标比数值。
const numSeq = (svg) => {
const out = []
const re = /\bd="([^"]*)"/g
let m
while ((m = re.exec(String(svg)))) {
const tokens = m[1].match(/-?\d*\.?\d+(?:e[-+]\d+)?/g) || []
for (const t of tokens) out.push(Number(t))
}
return out
}
// 顺序会变(元素按面积降序输出,让大面积压在下层),所以比「集合」而不是「序列」
const seqSplit = numSeq(splitSvg).sort((a, b) => a - b)
const seqWhole = numSeq(wholeSvg).sort((a, b) => a - b)
check('拆分没有丢几何(坐标集合完全一致;顺序按面积重排是刻意的)',
seqSplit.length === seqWhole.length && seqSplit.every((v, i) => v === seqWhole[i]),
seqSplit.length + ' vs ' + seqWhole.length + ' 个坐标')
// 渲染也要一致:孔洞("O" 的内圈)如果被切碎会变成实心,这里能直接抓到
const diffRatio = await page.evaluate(async ({ a, b }) => {
const load = (s) => new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(s))) })
const W = 480, H = 480
const grab = (img) => { const c = document.createElement('canvas'); c.width = W; c.height = H; const g = c.getContext('2d', { willReadFrequently: true }); g.drawImage(img, 0, 0, W, H); return g.getImageData(0, 0, W, H) }
const da = grab(await load(a)), db = grab(await load(b))
let bad = 0
for (let i = 0; i < da.data.length; i += 4) {
const d = Math.abs(da.data[i] - db.data[i]) + Math.abs(da.data[i + 1] - db.data[i + 1]) + Math.abs(da.data[i + 2] - db.data[i + 2])
if (d > 8) bad++
}
return bad / (W * H)
}, { a: splitSvg, b: wholeSvg })
check('拆分与整体渲染一致(差异只在抗锯齿边缘,<0.5%)', diffRatio < 0.005, (diffRatio * 100).toFixed(3) + '%')
await page.locator('[data-check="splitIslands"]').check({ force: true })
await sleep(500)
check('重新勾选后恢复拆分', await page.evaluate(() => (String(window.__lastSvg || '').match(/<path/g) || []).length > 3))
// ---------- 灰度分层 ----------
await page.locator('[data-seg="mode"][data-value="gray"]').click()
await sleep(400)
const grayPaths = await waitText(page, '[data-stat="elements"]')
const grayLevels = await levelsNow(page)
check('切「灰度分层」:层数 = 3 且重新描摹', String(grayLevels) === '3' && Number(grayPaths) >= 3, 'paths=' + grayPaths + ' levels=' + grayLevels)
check('灰度层数行可见、单色颜色项禁用', await page.evaluate(() => {
const row = document.querySelector('[data-only="gray"]')
const color = document.querySelector('[data-color="color"]')
return Boolean(row && !row.hidden && color && color.disabled)
}))
await page.locator('[data-seg="levels"][data-value="5"]').click()
await sleep(500)
check('层数切到 5:层数统计跟着变(自定义阈值数组生效)', String(await levelsNow(page)) === '5', 'levels=' + await levelsNow(page))
await page.locator('[data-seg="levels"][data-value="3"]').click()
await sleep(400)
// ---------- 去小点 ----------
const beforeTurd = await pathsNow(page)
await page.locator('[data-param="turdSize"]').fill('24')
await sleep(450)
const afterTurd = await waitText(page, '[data-stat="elements"]')
check('去小点调大后重新描摹(噪点应被吃掉,路径不增)', Number(afterTurd) <= Number(beforeTurd), beforeTurd + ' → ' + afterTurd)
await page.locator('[data-param="turdSize"]').fill('3')
await sleep(400)
// ---------- 边缘(alphaMax) ----------
const beforeTone = await page.evaluate(() => window.__svgSeq)
await page.locator('[data-seg="alphaTone"][data-value="round"]').click()
await sleep(450)
check('边缘「圆润」触发重新描摹(换了一套几何)', (await page.evaluate(() => window.__svgSeq)) > beforeTone)
await page.locator('[data-seg="alphaTone"][data-value="normal"]').click()
await sleep(400)
// ---------- 精度(optTolerance) ----------
const beforeTol = await page.evaluate(() => ({ seq: window.__svgSeq, len: (window.__lastSvg || '').length }))
await page.locator('[data-seg="precision"][data-value="light"]').click()
await sleep(500)
const lightTol = await page.evaluate(() => ({ seq: window.__svgSeq, len: (window.__lastSvg || '').length }))
check('精度「轻量」重算几何且路径数据更少', lightTol.seq > beforeTol.seq && lightTol.len < beforeTol.len,
beforeTol.len + 'B → ' + lightTol.len + 'B')
await page.locator('[data-seg="precision"][data-value="fine"]').click()
await sleep(500)
const fineTol = await page.evaluate(() => (window.__lastSvg || '').length)
check('精度「精细」路径数据更多(拟合容差真的换了)', fineTol > lightTol.len, lightTol.len + 'B → ' + fineTol + 'B')
// ---------- 反相 ----------
const beforeInv = await page.evaluate(() => window.__svgSeq)
// 高级区默认已展开(上面断言过),这里直接点反相,不再先点开
await page.locator('[data-seg="invert"][data-value="1"]').click()
await sleep(450)
check('反相(负片)重新描摹', (await page.evaluate(() => window.__svgSeq)) > beforeInv)
await page.locator('[data-seg="invert"][data-value="0"]').click()
await sleep(400)
// ---------- 阈值手动 ----------
await page.locator('[data-seg="thrMode"][data-value="manual"]').click()
await sleep(150)
check('阈值切手动后滑杆出现', await page.evaluate(() => {
const row = document.querySelector('[data-thr-row]')
return Boolean(row && !row.hidden)
}))
await page.locator('[data-seg="thrMode"][data-value="auto"]').click()
await sleep(300)
// ---------- 颜色(单色) ----------
await page.locator('[data-seg="mode"][data-value="mono"]').click()
await sleep(400)
check('切回单色后颜色输入可用', await page.evaluate(() => {
const c = document.querySelector('[data-color="color"]')
return Boolean(c && !c.disabled)
}))
await page.evaluate(() => {
const c = document.querySelector('[data-color="color"]')
c.value = '#c0392b'
c.dispatchEvent(new Event('input', { bubbles: true }))
})
await sleep(400)
check('改单色填充色写进 SVG', await page.evaluate(() => /#c0392b/i.test(window.__lastSvg || '')), '')
// 开发用:VZ_SHOT_PANEL=/tmp/vz-panel.png 出一张面板截图(验证「填充 / 背景」这排没挤坏布局)
// ⚠️ 别和上面的 VZ_SHOT 共用同一个变量 —— 两处都写同一路径时,后一张会把前一张覆盖掉
if (process.env.VZ_SHOT_PANEL) await page.locator('.vz-modal').screenshot({ path: process.env.VZ_SHOT_PANEL })
// ---------- 背景色 / 带底(v0.3.1) ----------
const setBg = async (hex) => {
await page.evaluate((v) => {
const c = document.querySelector('[data-color="bg"]')
c.value = v
c.dispatchEvent(new Event('input', { bubbles: true }))
}, hex)
await sleep(320)
}
const hasBgRect = () => page.evaluate(() => /<rect[^>]*width="100%"[^>]*fill="#efefef"/i.test(window.__lastSvg || ''))
const seqBeforeBg = await page.evaluate(() => window.__svgSeq)
await setBg('#efefef')
check('改背景色:预览底色跟着变(不用重新描摹)', await page.evaluate(() => {
const bg = getComputedStyle(document.querySelector('.vz-preview')).backgroundColor
return /239,\s*239,\s*239/.test(bg)
}))
check('改背景色不触发重描摹(底色不参与轮廓计算)',
await page.evaluate(() => window.__svgSeq) === seqBeforeBg)
check('默认「带底」关:导出仍是透明底', !(await hasBgRect()))
const elementsBeforeBg = await page.evaluate(() => document.querySelector('[data-stat="elements"]').textContent)
await page.locator('[data-check="bgExport"]').check()
await sleep(450)
check('勾「带底」后 SVG 里铺了背景矩形', await hasBgRect())
check('带底不影响元素数(背景矩形不算一个元素)',
(await page.evaluate(() => document.querySelector('[data-stat="elements"]').textContent)) === elementsBeforeBg)
await page.locator('[data-check="bgExport"]').uncheck()
await sleep(450)
check('取消「带底」后回到透明导出', !(await hasBgRect()))
await setBg('#ffffff')
// ---------- 输出 ----------
// 复制到剪贴板:about:blank 是非安全上下文,没有真的 Clipboard API,
// 这里打桩只为验证「写的是哪些口味、内容是不是当前矢量」。
await page.evaluate(() => {
window.__clip = null
window.__clipText = ''
function FakeClipboardItem(items) { this.items = items }
FakeClipboardItem.supports = function () { return true }
Object.defineProperty(window, 'ClipboardItem', { configurable: true, writable: true, value: FakeClipboardItem })
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
write: async function (items) { window.__clip = items[0].items },
writeText: async function (text) { window.__clipText = text },
},
})
})
await page.locator('[data-act="copy"]').click()
await sleep(400)
const clip = await page.evaluate(async () => {
const box = window.__clip || {}
return {
types: Object.keys(box),
svg: box['image/svg+xml'] ? await box['image/svg+xml'].text() : '',
plain: box['text/plain'] ? await box['text/plain'].text() : '',
status: (document.querySelector('[data-status-text]') || {}).textContent || '',
}
})
check('「复制 SVG」写进剪贴板(image/svg+xml + text/plain 双口味)',
clip.types.indexOf('image/svg+xml') >= 0 && clip.types.indexOf('text/plain') >= 0 &&
clip.svg.indexOf('<svg') >= 0 && clip.svg.indexOf('<path') >= 0,
clip.types.join(','))
check('复制的内容就是当前矢量(纯文本口味与矢量口味一致)', clip.plain === clip.svg && clip.plain.length > 100, clip.plain.length + 'B')
check('复制后给用户反馈', /已复制/.test(clip.status), clip.status)
const dl = page.waitForEvent('download', { timeout: 8000 })
await page.locator('[data-act="svg"]').click()
const download = await dl
check('「下载 SVG」触发文件下载', /\.svg$/.test(download.suggestedFilename()), download.suggestedFilename())
await page.locator('[data-act="save"]').click()
await sleep(900)
check('「保存为节点」写出 PNG 图片节点', await page.evaluate(() =>
window.__writes.some((w) => w.kind === 'newNode' && /^data:image\/png;base64,/.test(w.head))),
JSON.stringify(await page.evaluate(() => window.__writes.slice(-1))))
check('保存后模态自动关闭', (await page.locator('.vz-root').count()) === 0)
// ---------- 参数记忆 ----------
const mem = await page.evaluate(() => window.__settings)
check('参数记忆写回宿主 settings', mem && mem.mode === 'mono' && Number(mem.turdSize) === 3 && String(mem.color).toLowerCase() === '#c0392b', JSON.stringify(mem))
check('背景色 / 带底 也进记忆', String(mem.bg).toLowerCase() === '#ffffff' && mem.bgExport === false,
'bg=' + mem.bg + ' bgExport=' + mem.bgExport)
await page.evaluate(() => { window.__actions['vectorize-node'].run({ id: 'r1', type: 'ref', name: 'src.png' }) })
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 15000 })
check('重新打开沿用上次参数(mode=mono、颜色 #c0392b)', await page.evaluate(() => {
const active = document.querySelector('[data-seg-group="mode"] button.active')
const color = document.querySelector('[data-color="color"]')
return Boolean(active && active.dataset.value === 'mono' && color && color.value.toLowerCase() === '#c0392b')
}))
// ---------- 空格对比 / Esc ----------
// 先缩放到非 1x:验证「按住空格切原图时视图不跳」—— 两张 img 共用同一套变量才做得到。
// 注意不能拿 vector 的 computed transform 跟 original 比:display:none 的元素 compute 出来是 none。
const pv2 = await page.locator('[data-preview]').boundingBox()
await page.mouse.move(pv2.x + pv2.width / 2, pv2.y + pv2.height / 2)
await page.mouse.wheel(0, -300)
await sleep(150)
const viewBefore = await page.evaluate(() =>
getComputedStyle(document.querySelector('[data-stage="vector"]')).transform)
await page.evaluate(() => document.body.focus())
await page.keyboard.down('Space')
await sleep(150)
check('按住空格对比原图', await page.evaluate(() => {
const o = document.querySelector('[data-stage="original"]')
return Boolean(o && !o.hidden)
}))
const spaceCmp = await page.evaluate(() => {
const p = document.querySelector('[data-preview]')
return {
z: Number(p.style.getPropertyValue('--vz-zoom') || 1),
t: getComputedStyle(document.querySelector('[data-stage="original"]')).transform,
}
})
check('缩放状态下切原图,视图完全不跳(两图共用变量)',
spaceCmp.z > 1 && spaceCmp.t === viewBefore,
'zoom=' + spaceCmp.z.toFixed(2) + ' ' + spaceCmp.t + ' vs ' + viewBefore)
await page.keyboard.up('Space')
await sleep(120)
check('松开空格回到矢量', await page.evaluate(() => {
const o = document.querySelector('[data-stage="original"]')
const v = document.querySelector('[data-stage="vector"]')
return Boolean(o && o.hidden && v && !v.hidden)
}))
await page.keyboard.press('Escape')
await sleep(200)
check('Esc 关闭模态', (await page.locator('.vz-root').count()) === 0)
const fatal = errors.filter((e) => /Content Security Policy|Refused to|WebAssembly|is not defined|TypeError/i.test(e))
check('无 CSP / 运行时错误', fatal.length === 0, fatal.slice(0, 2).join(' | '))
if (errors.length) {
console.log('')
console.log('控制台错误(' + errors.length + ' 条,前 5 条):')
for (const e of errors.slice(0, 5)) console.log(' ' + String(e).slice(0, 180))
}
console.log('')
console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')
await browser.close()
process.exit(failed ? 1 : 0)
+142
View File
@@ -0,0 +1,142 @@
// 单色/灰度描摹 CLI(开发用,不进 CI):把真实素材丢进去,直接看参数效果。
//
// node image-vectorize/tools/trace-cli.mjs <图片> [--mode mono|gray] [--levels 3]
// [--turd 3] [--alpha 1] [--tol 0.1] [--invert] [--color #1a1a1a] [--threshold -1]
// [--no-split] [--out 目录]
//
// --no-split:不按孤岛拆分(所有轮廓塞在一个 path 里,粘到 Figma 是整体)。默认拆分。
//
// 产物:<out>/<name>-<mode><levels>.svg + 一张对比图 <out>/<name>-cmp.png(原图 / 结果 / 局部放大)。
// 为什么走浏览器:PNG/JPEG 解码和 ImageData 语义都与线上一致,Node 里没有等价的零依赖解码器。
import { createRequire } from 'node:module'
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { bundleEngine } from './bundle-engine.mjs'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
let chromium = null
for (const base of [HOST_REPO, REPO, process.cwd()]) {
try {
chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium
break
} catch {
/* 试下一个 */
}
}
if (!chromium) {
console.error('✗ 找不到 playwright')
process.exit(2)
}
const argv = process.argv.slice(2)
const files = []
const opt = { mode: 'gray', levels: 3, turd: 3, alpha: 1, tol: 0.1, invert: false, color: '#1a1a1a', threshold: -1, split: true, out: '/tmp/vz-cli' }
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
if (a === '--mode') opt.mode = argv[++i]
else if (a === '--levels') opt.levels = Number(argv[++i])
else if (a === '--turd') opt.turd = Number(argv[++i])
else if (a === '--alpha') opt.alpha = Number(argv[++i])
else if (a === '--tol') opt.tol = Number(argv[++i])
else if (a === '--invert') opt.invert = true
else if (a === '--color') opt.color = argv[++i]
else if (a === '--threshold') opt.threshold = Number(argv[++i])
else if (a === '--no-split') opt.split = false
else if (a === '--split') opt.split = true
else if (a === '--out') opt.out = argv[++i]
else if (a.startsWith('--')) throw new Error('未知参数 ' + a)
else files.push(a)
}
if (!files.length) {
console.error('用法:node image-vectorize/tools/trace-cli.mjs <图片...> [--mode mono|gray] [--levels 3] ...')
process.exit(2)
}
fs.mkdirSync(opt.out, { recursive: true })
const bundle = bundleEngine()
const bundleCode = fs.readFileSync(bundle, 'utf8')
const browser = await chromium.launch()
const page = await browser.newPage()
await page.setContent('<canvas id="c"></canvas>')
await page.addScriptTag({ content: bundleCode })
const params = {
mode: opt.mode,
levels: opt.levels,
turdSize: opt.turd,
alphaMax: opt.alpha,
optTolerance: opt.tol,
invert: opt.invert,
color: opt.color,
threshold: opt.threshold,
outScale: 1,
splitIslands: opt.split,
}
for (const file of files) {
const b64 = fs.readFileSync(file).toString('base64')
const mime = /\.jpe?g$/i.test(file) ? 'image/jpeg' : 'image/png'
const res = await page.evaluate(
async ({ dataUrl, params }) => {
const img = new Image()
img.src = dataUrl
await img.decode()
const c = document.createElement('canvas')
c.width = img.naturalWidth
c.height = img.naturalHeight
const g = c.getContext('2d', { willReadFrequently: true })
g.drawImage(img, 0, 0)
const imageData = g.getImageData(0, 0, c.width, c.height)
const out = window.VZEngine.traceImageData(imageData, params)
return { svg: out.svg, ms: out.ms, paths: out.paths, elements: out.elements, islands: out.islands, levels: out.levels, w: c.width, h: c.height }
},
{ dataUrl: `data:${mime};base64,${b64}`, params }
)
const base = path.basename(file).replace(/\.[^.]+$/, '')
const tag = (opt.mode === 'mono' ? 'mono' : 'gray' + res.levels) + '-t' + opt.tol + (opt.split ? '-split' : '-whole')
const svgPath = path.join(opt.out, `${base}-${tag}.svg`)
fs.writeFileSync(svgPath, res.svg)
console.log(
`${base} ${tag.padEnd(14)} ${String(res.elements).padStart(4)} 元素 / ${String(res.islands).padStart(4)} 孤岛 ${String(res.ms).padStart(4)}ms ` +
`${(res.svg.length / 1024).toFixed(0)}KB ${res.w}×${res.h} → ${svgPath}`
)
// 对比图:原图 | 描摹结果
const cmp = await page.evaluate(
async ({ orig, svg, w, h }) => {
const load = (src) => new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = src })
const a = await load(orig)
const b = await load('data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg))))
const cw = 520
const ch = Math.round((h / w) * cw)
const cv = document.createElement('canvas')
cv.width = cw * 2 + 16
cv.height = ch + 24
const g = cv.getContext('2d')
g.fillStyle = '#fff'
g.fillRect(0, 0, cv.width, cv.height)
g.drawImage(a, 0, 20, cw, ch)
g.drawImage(b, cw + 16, 20, cw, ch)
g.fillStyle = '#333'
g.font = '12px system-ui'
g.fillText('原图', 4, 14)
g.fillText('描摹结果', cw + 20, 14)
return cv.toDataURL('image/png')
},
{
orig: `data:${mime};base64,${b64}`,
svg: res.svg.replace(/fill-opacity="0"/g, 'fill-opacity="0.001"'),
w: res.w,
h: res.h,
}
)
const cmpPath = path.join(opt.out, `${base}-cmp.png`)
fs.writeFileSync(cmpPath, Buffer.from(cmp.split(',')[1], 'base64'))
console.log(' 对比图 → ' + cmpPath)
}
await browser.close()
+481
View File
@@ -0,0 +1,481 @@
{
"name": "@iwb-plugin/workspace",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@iwb-plugin/workspace",
"version": "1.0.0",
"devDependencies": {
"esbuild": "^0.24.2"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.24.2.tgz",
"integrity": "sha512-thpVCb/rhxE/BnMLQ7GReQLLN8q9qbHmI55F4489/ByVg2aQaQ6kbcLb6FHkocZzQhxc4gx0sCk0tJkKBFzDhA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.24.2.tgz",
"integrity": "sha512-tmwl4hJkCfNHwFB3nBa8z1Uy3ypZpxqxfTQOcHX+xRByyYgunVbZ9MzUUfb0RxaHIMnbHagwAxuTL+tnNM+1/Q==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.24.2.tgz",
"integrity": "sha512-cNLgeqCqV8WxfcTIOeL4OAtSmL8JjcN6m09XIgro1Wi7cF4t/THaWEa7eL5CMoMBdjoHOTh/vwTO/o2TRXIyzg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.24.2.tgz",
"integrity": "sha512-B6Q0YQDqMx9D7rvIcsXfmJfvUYLoP722bgfBlO5cGvNVb5V/+Y7nhBE3mHV9OpxBf4eAS2S68KZztiPaWq4XYw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.24.2.tgz",
"integrity": "sha512-kj3AnYWc+CekmZnS5IPu9D+HWtUI49hbnyqk0FLEJDbzCIQt7hg7ucF1SQAilhtYpIujfaHr6O0UHlzzSPdOeA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.24.2.tgz",
"integrity": "sha512-WeSrmwwHaPkNR5H3yYfowhZcbriGqooyu3zI/3GGpF8AyUdsrrP0X6KumITGA9WOyiJavnGZUwPGvxvwfWPHIA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.24.2.tgz",
"integrity": "sha512-UN8HXjtJ0k/Mj6a9+5u6+2eZ2ERD7Edt1Q9IZiB5UZAIdPnVKDoG7mdTVGhHJIeEml60JteamR3qhsr1r8gXvg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.24.2.tgz",
"integrity": "sha512-TvW7wE/89PYW+IevEJXZ5sF6gJRDY/14hyIGFXdIucxCsbRmLUcjseQu1SyTko+2idmCw94TgyaEZi9HUSOe3Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.24.2.tgz",
"integrity": "sha512-n0WRM/gWIdU29J57hJyUdIsk0WarGd6To0s+Y+LwvlC55wt+GT/OgkwoXCXvIue1i1sSNWblHEig00GBWiJgfA==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.24.2.tgz",
"integrity": "sha512-7HnAD6074BW43YvvUmE/35Id9/NB7BeX5EoNkK9obndmZBUk8xmJJeU7DwmUeN7tkysslb2eSl6CTrYz6oEMQg==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.24.2.tgz",
"integrity": "sha512-sfv0tGPQhcZOgTKO3oBE9xpHuUqguHvSo4jl+wjnKwFpapx+vUDcawbwPNuBIAYdRAvIDBfZVvXprIj3HA+Ugw==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.24.2.tgz",
"integrity": "sha512-CN9AZr8kEndGooS35ntToZLTQLHEjtVB5n7dl8ZcTZMonJ7CCfStrYhrzF97eAecqVbVJ7APOEe18RPI4KLhwQ==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.24.2.tgz",
"integrity": "sha512-iMkk7qr/wl3exJATwkISxI7kTcmHKE+BlymIAbHO8xanq/TjHaaVThFF6ipWzPHryoFsesNQJPE/3wFJw4+huw==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.24.2.tgz",
"integrity": "sha512-shsVrgCZ57Vr2L8mm39kO5PPIb+843FStGt7sGGoqiiWYconSxwTiuswC1VJZLCjNiMLAMh34jg4VSEQb+iEbw==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.24.2.tgz",
"integrity": "sha512-4eSFWnU9Hhd68fW16GD0TINewo1L6dRrB+oLNNbYyMUAeOD2yCK5KXGK1GH4qD/kT+bTEXjsyTCiJGHPZ3eM9Q==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.24.2.tgz",
"integrity": "sha512-S0Bh0A53b0YHL2XEXC20bHLuGMOhFDO6GN4b3YjRLK//Ep3ql3erpNcPlEFed93hsQAjAQDNsvcK+hV90FubSw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.24.2.tgz",
"integrity": "sha512-8Qi4nQcCTbLnK9WoMjdC9NiTG6/E38RNICU6sUNqK0QFxCYgoARqVqxdFmWkdonVsvGqWhmm7MO0jyTqLqwj0Q==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.24.2.tgz",
"integrity": "sha512-wuLK/VztRRpMt9zyHSazyCVdCXlpHkKm34WUyinD2lzK07FAHTq0KQvZZlXikNWkDGoT6x3TD51jKQ7gMVpopw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.24.2.tgz",
"integrity": "sha512-VefFaQUc4FMmJuAxmIHgUmfNiLXY438XrL4GDNV1Y1H/RW3qow68xTwjZKfj/+Plp9NANmzbH5R40Meudu8mmw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.24.2.tgz",
"integrity": "sha512-YQbi46SBct6iKnszhSvdluqDmxCJA+Pu280Av9WICNwQmMxV7nLRHZfjQzwbPs3jeWnuAhE9Jy0NrnJ12Oz+0A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.24.2.tgz",
"integrity": "sha512-+iDS6zpNM6EnJyWv0bMGLWSWeXGN/HTaF/LXHXHwejGsVi+ooqDfMCCTerNFxEkM3wYVcExkeGXNqshc9iMaOA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.24.2.tgz",
"integrity": "sha512-hTdsW27jcktEvpwNHJU4ZwWFGkz2zRJUz8pvddmXPtXDzVKTTINmlmga3ZzwcuMpUvLw7JkLy9QLKyGpD2Yxig==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.24.2.tgz",
"integrity": "sha512-LihEQ2BBKVFLOC9ZItT9iFprsE9tqjDjnbulhHoFxYQtQfai7qfluVODIYxt1PgdoyQkz23+01rzwNwYfutxUQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.24.2.tgz",
"integrity": "sha512-q+iGUwfs8tncmFC9pcnD5IvRHAzmbwQ3GPS5/ceCyHdjXubwQWI12MKWSNSMYLJMq23/IUCvJMS76PDqXe1fxA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.24.2.tgz",
"integrity": "sha512-7VTgWzgMGvup6aSqDPLiW5zHaxYJGTO4OokMjIlrCtf+VpEL+cXKtCvg723iguPYI5oaUNdS+/V7OU2gvXVWEg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/esbuild": {
"version": "0.24.2",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz",
"integrity": "sha512-+9egpBW8I3CD5XPe0n6BfT5fxLzxrlDzqydF3aviG+9ni1lDC/OvMHcxqEFV0+LANZG5R1bFMWfUrjVsdwxJvA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.24.2",
"@esbuild/android-arm": "0.24.2",
"@esbuild/android-arm64": "0.24.2",
"@esbuild/android-x64": "0.24.2",
"@esbuild/darwin-arm64": "0.24.2",
"@esbuild/darwin-x64": "0.24.2",
"@esbuild/freebsd-arm64": "0.24.2",
"@esbuild/freebsd-x64": "0.24.2",
"@esbuild/linux-arm": "0.24.2",
"@esbuild/linux-arm64": "0.24.2",
"@esbuild/linux-ia32": "0.24.2",
"@esbuild/linux-loong64": "0.24.2",
"@esbuild/linux-mips64el": "0.24.2",
"@esbuild/linux-ppc64": "0.24.2",
"@esbuild/linux-riscv64": "0.24.2",
"@esbuild/linux-s390x": "0.24.2",
"@esbuild/linux-x64": "0.24.2",
"@esbuild/netbsd-arm64": "0.24.2",
"@esbuild/netbsd-x64": "0.24.2",
"@esbuild/openbsd-arm64": "0.24.2",
"@esbuild/openbsd-x64": "0.24.2",
"@esbuild/sunos-x64": "0.24.2",
"@esbuild/win32-arm64": "0.24.2",
"@esbuild/win32-ia32": "0.24.2",
"@esbuild/win32-x64": "0.24.2"
}
}
}
}
+10 -1
View File
@@ -4,6 +4,15 @@
"version": "1.0.0",
"description": "IWB 插件仓:只写插件,不复制宿主契约",
"scripts": {
"validate": "node scripts/validate.mjs"
"validate": "node scripts/validate.mjs",
"build": "node scripts/build-plugin.mjs",
"test": "npm run validate && npm run test:album && npm run test:promptlib",
"test:album": "node album/tools/harness.mjs",
"test:album:e2e": "node album/tools/viewer-e2e.mjs",
"test:promptlib": "node promptlib/tools/harness.mjs && node promptlib/tools/vars-editor-test.mjs",
"test:promptlib:visual": "node promptlib/tools/vars-panel-visual-check.mjs"
},
"devDependencies": {
"esbuild": "^0.24.2"
}
}
+9
View File
@@ -0,0 +1,9 @@
# promptlib 样式基线(重要)
- 正确基线:**v1.8.8**(commit `178b36c`)
- 当前 v1.8.17 的样式与 1.8.8 视觉一致,仅颜色做了 `var(--plp-cN, #原色)` 兜底包装
- 禁止批量改写颜色 token / 重写 CSS 声明(曾导致文字不可见、灰块、伪类失效)
- 插入变量:禁止在 blur 记录选区;用 `execCommand("insertText")` 在光标处插入
- 改样式后必须截图核对再发市场
详细说明见桌面仓 `docs/standards/promptlib-style-baseline.md`。
+47
View File
@@ -0,0 +1,47 @@
# promptlib Token 迁移映射表(第一批:颜色)
> 依据:`image-workbench-desktop/docs/standards/design-tokens.md` 与 `plugin-theme.md`。
> 原则:**视觉目标仍是 1.8.8 基线**;先迁颜色(语义明确),尺寸后续单独批次 + 截图 diff。
## 1. 颜色映射(已落地 1.8.22)
| 原值 | Token | 用途 |
| --- | --- | --- |
| `#fff` / `#ffffff`(background) | `--iwb-plugin-card` | 卡片/弹窗内白底 |
| `#fbfcfd` / `#fcfcfd` | `--iwb-field` | 输入框/编辑区底 |
| `#fafafb` / `#fafbfc` | `--iwb-plugin-surface` | 面板根 |
| `#f5f6f7` `#f3f4f7` `#f2f4f7` `#eef0f4` `#f4f5f7` `#f4f6f9` `#f1f3f5` | `--iwb-plugin-inset` | 内嵌/分组底 |
| `#eef0f3` `#eef1f4` `#e9ecf1` `#e7e9ee` `#d7dbe2` | `--iwb-plugin-hover` | 悬停/次级块 |
| `#d5d9e0` `#e3e5e9` `#e6e8ec` `#eceef2` `#e2e6ec` `#e8eaee` `#eef0f2` `#dfe3e9` `#f1f3f5` `#f3f5f8` `#eef0f3` | `--iwb-plugin-border` | 常规描边/分割线 |
| `#b9bfca` `#c2c7cf` `#9aa3ad` | `--iwb-border2` | 强调描边 |
| `#1d2129` `#1c2333` `#2f3540` `#3f4450` `#3a4048` `#33383f` | `--iwb-text` | 主文字 |
| `#5b6472` `#4d5668` `#8b929c` `#8a919c` | `--iwb-text2` | 次要文字 |
| `#9aa1ac` `#aab0ba` `#b3b9c2` `#c2c7cf` | `--iwb-text-dim` | 占位/弱说明 |
| `#5a3fd0` `#5a4bd0` `#7c4dff` `#6b4dff` `#8b7ff0` | `--iwb-plp-accent` | 插件强调色(高饱和,允许自有) |
| `#f1ecff` `#f4f0ff` | `--iwb-plp-accent-soft` | 强调色浅底 |
| `#cfc3ff` `#d8cbff` `#d9d3ff` | `--iwb-plp-accent-border` | 强调色描边 |
| `#d97706` | `--iwb-warn` | 警告 |
| `#c0392b` | `--iwb-err` | 错误/删除 |
白色文字(压在封面/渐变上)保留 `#fff`,属内容色。
## 2. 尺寸迁移(已完成 1.8.23)
迁移结果:promptlib 散值清零(字号/圆角/间距全部落入闭集),棘轮基线已下调;视觉对比无换行/溢出。
| 类别 | 目标闭集 | 归并规则 |
| --- | --- | --- |
| 字号 | 11/12/13/14/15/17/20/24 | 10→11、10.5→11、11.5→12、12.5→13、13.5→14、16→15、18→17 |
| 圆角 | 6/8/10/12/14/999 | 2/3/4→6、7/9→8、11→10、16→14 |
| 间距 | 0/2/4/6/8/10/12/16/20/24/32/40/48/64 | 1→2、3→4、5→6、7→6、9→8、14→12、18→16 |
尺寸批次要求:亮/暗两套截图 diff + 逐项确认后再发布。
## 3. 复查命令
```bash
node scripts/token-audit.js --plugins
node tests/plugin-theme-contract-test.js
node tests/plugin-scale-contract-test.js
npm run test:visual
```
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/promptlib",
"private": true,
"version": "1.13.1",
"description": "提示词库:右栏提示词列表(搜索/分组/收藏/新建编辑/插入画布/复制/删除),数据由宿主 promptlib 能力提供",
"ibwPlugin": {
"id": "promptlib",
"entry": "src/index.js",
"apiVersion": 1
}
}
File diff suppressed because it is too large. Load diff
+598
View File
@@ -0,0 +1,598 @@
.iwb-promptlib, .iwb-plp-dialog, .iwb-plp-mask, .iwb-plp-dragghost, .iwb-plp-placebox{--iwb-plp-accent:#6b4dff;--iwb-plp-accent-soft:#f1ecff;--iwb-plp-accent-border:#d9d3ff}
/* promptlib(提示词库)自带样式
作用域全部带 .iwb-plp-*,不影响宿主与其他插件;样式随插件发布,不必等客户端发版。 */
/* 分组胶囊「适应面板宽度」自动换行。
宿主的 .iwb-lib-chips 是 flex-wrap: nowrap(配 .iwb-lib-chips-scroll 做单行横向滚动 + 右侧渐隐),
分组多时靠后的分类看不见也点不到。双类选择器提高优先级(不依赖样式注入顺序)。 */
.iwb-lib-chips.iwb-plp-chips {
flex-wrap: wrap;
row-gap: 6px;
}
/* + / ⚙ 是动作按钮,不是分组名:不参与压缩,并与最后一个分组稍作分隔 */
.iwb-plp-chips .iwb-plp-add {
flex: 0 0 auto;
margin-left: 2px;
}
/* v1.0.2(2026-11-21):卡片化 —— 白卡 + 悬停 + 文本三行截断。
颜色一律走宿主 --iwb-plugin-* / --iwb-* token,不在插件里写死。 */
.iwb-promptlib .iwb-pname { font-weight: 600; }
.iwb-promptlib .iwb-ptext {
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3;
overflow: hidden; color: var(--iwb-text2, #4d5668);
}
.iwb-promptlib .iwb-lib-cards { gap: 8px; }
/* v1.1.0(2026-11-21):封面网格 + 长文详情 + 宽编辑弹窗。
颜色全部走宿主 token,不写死。 */
.iwb-plp-card {
position: relative; border-radius: 10px; overflow: hidden; cursor: pointer;
aspect-ratio: 1 / 1; border: 1px solid var(--iwb-border, #d5d9e0);
transition: border-color .12s ease, transform .12s ease;
}
.iwb-plp-card:hover { border-color: var(--iwb-border2, #b9bfca); }
.iwb-plp-cover { width: 100%; height: 100%; object-fit: cover; display: block; }
.iwb-plp-t {
position: absolute; left: 0; right: 0; bottom: 0; padding: 16px 6px 6px;
background: linear-gradient(to bottom, rgba(0,0,0,0), rgba(0,0,0,.66));
color: var(--plp-c1, #fff); font-size: 11px; line-height: 1.35; max-height: 48%;
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden;
text-shadow: 0 1px 2px rgba(0,0,0,.35);
}
/* 详情:长文阅读 */
.iwb-plp-dhead { display: flex; align-items: center; gap: 6px; padding: 2px 0 8px; position: sticky; top: 0; z-index: 2; background: var(--iwb-plugin-surface, #fafafb); }
.iwb-plp-dtop { align-items: flex-start; gap: 10px; margin-bottom: 8px; }
.iwb-plp-dthumb { flex: 0 0 84px; width: 84px; height: 84px; border-radius: 8px; overflow: hidden; border: 1px solid var(--iwb-border, #d5d9e0); }
.iwb-plp-dmeta { min-width: 0; display: flex; flex-direction: column; gap: 4px; }
.iwb-plp-dtitle { font-size: 13px; font-weight: 600; color: var(--iwb-text, #1c2333); line-height: 1.45; }
.iwb-plp-dtext {
font-size: 12px; line-height: 1.75; color: var(--iwb-text2, #4d5668);
white-space: pre-wrap; word-break: break-word; padding: 4px 0 12px;
}
.iwb-plp-dfoot { display: flex; align-items: center; gap: 6px; padding: 8px 0 2px; position: sticky; bottom: 0; background: var(--iwb-plugin-surface, #fafafb); }
/* 编辑弹窗:760 宽 + 大文本框 */
.iwb-promptlib-editor { width: 760px; max-width: 94vw; }
.iwb-promptlib-editor .iwb-modal-body { max-height: 78vh; }
.iwb-promptlib-text { min-height: 360px; height: 44vh; font-size: 13px; line-height: 1.9; resize: vertical; }
.iwb-plp-editor-cover { display: flex; gap: 12px; align-items: flex-start; margin-bottom: 10px; }
.iwb-plp-editor-thumb { flex: 0 0 96px; width: 96px; height: 128px; border-radius: 8px; overflow: hidden; border: 1px solid var(--iwb-border, #d5d9e0); }
.iwb-plp-editor-coverops { display: flex; flex-direction: column; gap: 8px; }
/* v1.2.0:可拖动 / 可缩放的详情与编辑弹窗(同宽 880×640,最小 640×420) */
.iwb-plp-mask { background: transparent; display: block; }
.iwb-plp-dialog { display: flex; flex-direction: column; overflow: hidden; border-radius: 14px;
box-shadow: 0 24px 60px rgba(0,0,0,.28); }
.iwb-plp-dhead { display: flex; align-items: center; gap: 6px; padding: 10px 12px;
border-bottom: 1px solid var(--iwb-border, #d5d9e0); cursor: move; user-select: none; }
.iwb-plp-grip { display: grid; grid-template-columns: repeat(3, 3px); gap: 2px; margin-right: 6px; }
.iwb-plp-grip i { width: 3px; height: 3px; border-radius: 50%; background: var(--iwb-border2, #b9bfca); display: block; }
.iwb-plp-dbody { flex: 1 1 auto; min-height: 0; display: flex; gap: 12px; padding: 12px; }
.iwb-plp-dcov { flex: 0 0 210px; width: 210px; height: 280px; border-radius: 10px; overflow: hidden;
border: 1px solid var(--iwb-border, #d5d9e0); background: var(--iwb-plugin-inset, #f5f6f7); }
.iwb-plp-dright { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 8px; }
.iwb-plp-dtext { flex: 1 1 auto; min-height: 0; overflow: auto; white-space: pre-wrap; word-break: break-word;
font-size: 12px; line-height: 1.9; color: var(--iwb-text2, #4d5668); }
.iwb-plp-dfooter { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 10px 12px;
border-top: 1px solid var(--iwb-border, #d5d9e0); }
.iwb-plp-resize { position: absolute; right: 0; bottom: 0; width: 18px; height: 18px; cursor: nwse-resize;
background: linear-gradient(135deg, transparent 0 45%, var(--iwb-border2, #b9bfca) 45% 50%, transparent 50% 62%, var(--iwb-border2, #b9bfca) 62% 67%, transparent 67%); }
/* 编辑:左栏固定 240,右栏大文本框 */
.iwb-plp-eleft { flex: 0 0 240px; width: 240px; display: flex; flex-direction: column; gap: 8px; min-height: 0; }
.iwb-plp-ecov { width: 240px; height: 300px; border-radius: 10px; overflow: hidden;
border: 1px solid var(--iwb-border, #d5d9e0); background: var(--iwb-plugin-inset, #f5f6f7); }
.iwb-plp-lrow { display: flex; flex-direction: column; gap: 4px; font-size: 11px; color: var(--iwb-text2, #4d5668); }
.iwb-plp-etext { flex: 1 1 auto; min-height: 0; height: auto; resize: none; font-size: 12px; line-height: 1.9; }
/* 输入框边框柔化(用户反馈现在的边框太深) */
.iwb-plp-dialog .iwb-input { border-color: color-mix(in srgb, var(--iwb-border, #d5d9e0) 72%, transparent); }
.iwb-plp-dialog .iwb-input:focus { border-color: var(--iwb-brand, #6b7280); box-shadow: 0 0 0 2px color-mix(in srgb, var(--iwb-brand, #6b7280) 14%, transparent); }
/* v1.2.1:去掉弹窗里多余的线框(用户反馈“线框太多、太明显”) */
.iwb-plp-dialog .iwb-plp-dcov,
.iwb-plp-dialog .iwb-plp-ecov { border-color: transparent; }
.iwb-plp-dialog .iwb-plp-dhead { border-bottom-color: color-mix(in srgb, var(--iwb-border, #d5d9e0) 45%, transparent); }
.iwb-plp-dialog .iwb-plp-dfooter { border-top-color: color-mix(in srgb, var(--iwb-border, #d5d9e0) 45%, transparent); }
/* 输入框:默认无边框,用浅底区分;聚焦才出现细描边 */
.iwb-plp-dialog .iwb-input {
border-color: transparent;
background: var(--iwb-plugin-inset, #f5f6f7);
box-shadow: none;
}
.iwb-plp-dialog .iwb-input:hover { background: var(--iwb-plugin-hover, #eef1f4); }
.iwb-plp-dialog .iwb-input:focus {
background: var(--iwb-panel, #fff);
border-color: color-mix(in srgb, var(--iwb-brand, #6b7280) 55%, transparent);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--iwb-brand, #6b7280) 12%, transparent);
}
/* 正文编辑区:无边框、无底色,像一张纸 */
.iwb-plp-dialog .iwb-plp-etext { border-color: transparent; background: transparent; box-shadow: none; }
.iwb-plp-dialog .iwb-plp-etext:focus { border-color: transparent; box-shadow: none; background: transparent; }
/* 左侧封面区的两个按钮:去掉按钮描边,弱化成文字按钮 */
.iwb-plp-dialog .iwb-plp-eleft .iwb-btn { border-color: transparent; background: var(--iwb-plugin-inset, #f5f6f7); }
.iwb-plp-dialog .iwb-plp-eleft .iwb-btn:hover { background: var(--iwb-plugin-hover, #eef1f4); }
/* v1.3.3:封面比例不定 —— 详情/编辑里完整显示(contain,不裁切);列表保持方形裁切(网格整齐) */
.iwb-plp-dialog .iwb-plp-dcov img,
.iwb-plp-dialog .iwb-plp-ecov img { object-fit: contain; background: var(--iwb-plugin-inset, #f5f6f7); }
.iwb-plp-dialog .iwb-plp-dcov,
.iwb-plp-dialog .iwb-plp-ecov { background: var(--iwb-plugin-inset, #f5f6f7); }
.iwb-plp-card .iwb-plp-cover { object-fit: cover; object-position: center; }
/* v1.3.4:瀑布流(列式)+ 卡片定宽不随面板拉伸;面板底色统一走 --iwb-plugin-surface */
.iwb-promptlib .iwb-plp-card {
display: inline-block; width: 100%; margin: 0 0 8px;
break-inside: avoid; -webkit-column-break-inside: avoid;
aspect-ratio: auto; /* 高度交给图片原始比例 */
}
.iwb-promptlib .iwb-plp-cover { width: 100%; height: auto; object-fit: contain; }
/* 统一插件灰:面板底(宿主会给 --iwb-plugin-surface,这里只留兜底) */
.iwb-promptlib { background: transparent; }
/* v1.3.5:无封面的提示词也给一个方形占位(否则瀑布流里会塌成一条线) */
.iwb-promptlib .iwb-plp-card.no-cover { aspect-ratio: 1 / 1; }
.iwb-promptlib .iwb-plp-card.no-cover .iwb-plp-t { max-height: 60%; }
/* v1.4.7:恢复瀑布流列规则(1.4.0 清理 CSS 时把这组规则一起删掉了,列表退化成单列、卡片被拉满宽) */
.iwb-promptlib .iwb-lib-cards { display: block; column-width: 122px; column-gap: 8px; grid-template-columns: none; }
.iwb-promptlib .iwb-plp-card { display: inline-block; width: 100%; margin: 0 0 8px; break-inside: avoid; -webkit-column-break-inside: avoid; aspect-ratio: auto; }
.iwb-promptlib .iwb-plp-cover { width: 100%; height: auto; object-fit: contain; }
.iwb-promptlib .iwb-plp-card.no-cover { aspect-ratio: 1 / 1; }
/* v1.5.0:模板节点 + 变量标记 */
.iwb-plp-vdot{position:absolute;right:8px;top:8px;width:7px;height:7px;border-radius:50%;background:var(--iwb-plp-accent, #7c4dff);box-shadow:0 0 0 2px var(--iwb-plp-dot-ring, rgba(255,255,255,.75))}
.iwb-plp-node{display:flex;flex-direction:column;gap:6px;padding:8px 10px;font-size:12px;color:var(--iwb-text,#1c2333)}
.iwb-plp-nhead{display:flex;align-items:center;gap:8px}
.iwb-plp-nthumb{width:44px;height:44px;border-radius:8px;object-fit:cover;flex:0 0 auto}
.iwb-plp-ntitle{font-weight:600;font-size: 13px;line-height:1.3;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
.iwb-plp-nvars{display:flex;flex-direction:column;gap:4px}
/* v1.12.1:标签列定宽(此前是 flex:0 0 auto,宽度跟着名称长短变 ⇒ 每个变量输入框左边缘错位)。
v1.13.0:用户要求按 4 字定宽 ⇒ 56px(12px 字号 × 4 + 8px 余量)。超过 4 字的名称省略号截断,完整名称在 title 里。 */
.iwb-plp-nrow{display:flex;align-items:flex-start;gap:6px;min-height:26px}
.iwb-plp-nk{flex:0 0 56px;width:56px;max-width:56px;padding-top:4px;color:var(--iwb-text2,#5b6472);font-size: 12px;line-height:1.35;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.iwb-plp-nin{flex:1 1 auto;min-width:0;height:auto;min-height:24px;padding:2px 8px;line-height:1.5;font-size: 12px;resize:none;overflow-y:hidden}
.iwb-plp-nref{display:flex;align-items:center;gap:6px;font-size: 12px;color:var(--iwb-text2,#5b6472);border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px}
.iwb-plp-nref em{font-style:normal;color:var(--iwb-text2,#8b929c)}
.iwb-plp-nprev{margin-top:2px;border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px;color:var(--iwb-text2,#5b6472);font-size: 12px;line-height:1.6;max-height:88px;overflow:hidden}
/* v1.5.0:变量编辑器 / 详情变量 */
.iwb-plp-emid{flex:1;min-width:0;display:flex;flex-direction:column;gap:8px}
.iwb-plp-vars{border:1px solid var(--iwb-border,#e3e5e9);border-radius:10px;padding:8px 10px;display:flex;flex-direction:column;gap:6px;background:var(--iwb-plugin-surface,#fff)}
.iwb-plp-vhead{display:flex;align-items:center;gap:8px;font-size: 12px;color:var(--iwb-text2,#5b6472)}
.iwb-plp-vchips{display:flex;flex-wrap:wrap;gap:6px}
.iwb-plp-vchip{display:inline-flex;align-items:center;gap:4px;padding: 2px 6px;border-radius:6px;background:color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 10%, transparent);color:var(--iwb-plp-accent, #5a4bd0);font-size: 12px}
.iwb-plp-vx{font-style:normal;cursor:pointer;color:var(--iwb-plp-accent, #8b7ff0);font-weight:700}
.iwb-plp-vrows{display:flex;flex-direction:column;gap: 6px}
.iwb-plp-vrow{display:flex;align-items:center;gap:8px}
.iwb-plp-vk{width:92px;flex:0 0 92px;font-size: 12px;color:var(--iwb-text2,#5b6472);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.iwb-plp-vin{flex:1;height:26px;font-size: 12px}
.iwb-plp-vprev{margin-top:2px;border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px;font-size: 12px;line-height:1.6;color:var(--iwb-text2,#5b6472);max-height:72px;overflow:auto;white-space:pre-wrap}
.iwb-plp-dvars{display:flex;flex-direction:column;gap: 6px;border:1px solid var(--iwb-border,#e3e5e9);border-radius:10px;padding:8px 10px}
/* v1.5.6:模板节点参照风格节点 —— 封面 + 名称 + 变量,正文不再铺开 */
.iwb-plp-nthumb{width:56px;height:56px;border-radius:8px;object-fit:cover;flex:0 0 auto}
.iwb-plp-ntitlebox{min-width:0;display:flex;flex-direction:column;gap:2px}
.iwb-plp-ntitle{font-weight:600;font-size: 13px;line-height:1.3;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
.iwb-plp-nmeta{font-size: 11px;color:var(--iwb-text2,#8b929c)}
.iwb-plp-nempty{font-size:11px;color:var(--iwb-text2,#8b929c);padding:2px 0}
.iwb-plp-nwarn{font-size:11px;line-height:1.5;color:var(--iwb-warn,#d97706)}
/* v1.5.10:设置页 */
.iwb-plp-settings{display:flex;flex-direction:column;gap: 16px}
/* 2026-11-24:插件设置页跟随宿主的设置分组 token(不再自画卡片,避免卡片套卡片) */
.iwb-plp-ssec{border:0;border-top:1px solid var(--iwb-set-divider,var(--iwb-border,#e3e5e9));border-radius:0;padding:var(--iwb-space-12) 0 0;display:flex;flex-direction:column;gap:var(--iwb-space-8)}
.iwb-plp-ssec:first-child{border-top:0;padding-top:0}
.iwb-plp-stitle{font-weight:600;font-size:var(--iwb-font-md,13px);color:var(--iwb-text,#2a2f36)}
.iwb-plp-sgroups{display:flex;flex-direction:column;border:1px solid var(--iwb-set-input-border,var(--iwb-border,#eef0f2));border-radius:var(--iwb-radius-card,10px);overflow:hidden}
.iwb-plp-sgrow{display:flex;align-items:center;gap:8px;padding: 6px 10px;border-top:1px solid var(--iwb-border,#f1f3f5)}
.iwb-plp-sgrow:first-child{border-top:0}
.iwb-plp-sgrip{width:12px;height:12px;background:radial-gradient(var(--iwb-text2,#c2c7cf) 1px,transparent 1px);background-size:4px 4px;border-radius: 6px;flex:0 0 auto}
.iwb-plp-sgname{width:170px;height:26px;font-size:12px}
.iwb-plp-sgcount{font-size: 12px;color:var(--iwb-text2,#8b929c);width:56px}
.iwb-plp-sadd{display:flex;gap:8px;align-items:center}
.iwb-plp-sbtns{display:flex;gap:8px;align-items:center}
.iwb-plp-sopt{display:flex;gap:8px;align-items:center;font-size:12px;color:var(--iwb-text2,#4d5668)}
.iwb-plp-settings{max-height:calc(100vh - 230px);overflow:auto;padding-right:4px}
/* v1.6.2:正文上方工具行 */
.iwb-plp-etool{display:flex;align-items:center;gap:8px}
/* v1.13.0:中列变窄时按钮文字会被挤成「+ 插入变 / 量」,按钮不参与收缩,让右边的灰字提示去换行 */
.iwb-plp-insvar{flex:0 0 auto;white-space:nowrap}
.iwb-plp-insvar{border:1px solid var(--iwb-plp-accent,#d9d3ff);background:color-mix(in srgb,var(--iwb-plp-accent,#7c4dff) 8%,transparent);color:var(--iwb-plp-accent,#5a4bd0);font-weight:600}
/* v1.6.5:宿主基础样式的插件作用域副本 —— 宿主改全局样式不再影响插件 */
.iwb-promptlib .iwb-grow {
flex: 1;
}
.iwb-promptlib .iwb-row {
display: flex; gap: 6px; align-items: center;
}
.iwb-promptlib .iwb-hint {
font-size: 11px; color: var(--iwb-text2); margin-top: 4px;
}
.iwb-promptlib .iwb-toolbar-title {
font-weight: 700; font-size: 13px; margin-right: 2px;
}
.iwb-plp-mask {
position: fixed; inset: 0; background: rgba(0,0,0,0.45); z-index: 300; display: flex; align-items: center; justify-content: center;
}
.iwb-plp-dialog {
width: 680px; max-width: calc(100vw - 60px); max-height: 82vh; background: var(--iwb-panel); border: 1px solid var(--iwb-border2); border-radius: 14px; display: flex; flex-direction: column; overflow: hidden;
}
.iwb-plp-dialog-head {
display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid var(--iwb-border);
}
.iwb-plp-dialog-body {
padding: 12px 16px; overflow: auto; display: flex; flex-direction: column; gap: 10px; max-height: 62vh;
}
.iwb-promptlib .iwb-lib-body {
flex: 1; overflow: hidden; padding: 12px 12px; display: flex; flex-direction: column; gap: 8px;
}
.iwb-promptlib .iwb-lib-fixed {
flex: 0 0 auto; display: flex; flex-direction: column; gap: 8px;
}
.iwb-promptlib .iwb-lib-scroll {
flex: 1 1 auto; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding-right: 2px;
}
.iwb-promptlib .iwb-lib-chips-scroll::-webkit-scrollbar {
display: none;
}
.iwb-promptlib .iwb-lib-chips-scroll > .iwb-chip:last-child {
margin-right: 16px;
}
.iwb-promptlib .iwb-lib-searchscope-back {
display: inline-flex; align-items: center; justify-content: center; width: 15px; height: 15px; padding: 0; border: none; border-radius: 999px; background: transparent; color: var(--iwb-text2); font-size: 13px; line-height: 1; cursor: pointer;
}
.iwb-promptlib .iwb-lib-searchscope-back:hover {
background: color-mix(in srgb, var(--iwb-text) 12%, transparent); color: var(--iwb-text);
}
.iwb-promptlib .iwb-chip {
flex: 0 0 auto; display: inline-flex; align-items: center; gap: 4px; background: var(--iwb-layer); border: 1px solid var(--iwb-border); border-radius: 999px; padding: 4px 10px; font-size: 12px; color: var(--iwb-text2); cursor: pointer; white-space: nowrap; transition: all 0.15s;
}
.iwb-promptlib .iwb-chip:hover {
color: var(--iwb-text); border-color: var(--iwb-border2);
}
.iwb-promptlib .iwb-chip-active {
background: var(--iwb-panel); border-color: var(--iwb-border2); color: var(--iwb-text); font-weight: 600;
}
.iwb-promptlib .iwb-chip-active:hover {
color: var(--iwb-text);
}
.iwb-promptlib .iwb-chip-count {
font-size: 11px; opacity: 0.8;
}
.iwb-promptlib .iwb-chip-add {
font-weight: 700;
}
.iwb-promptlib .iwb-pcard .iwb-btn:hover {
opacity: 1; color: var(--iwb-text); background: transparent;
}
.iwb-promptlib .iwb-pcard .iwb-btn-starred {
color: var(--iwb-text); opacity: 1;
}
.iwb-promptlib .iwb-pcard {
border: 1px solid var(--iwb-border); border-radius: 8px; padding: 8px 10px; background: var(--iwb-panel);
}
.iwb-promptlib .iwb-tag {
display: inline-block; background: color-mix(in srgb, var(--iwb-text) 7%, transparent); color: var(--iwb-text2); border-radius: 6px; font-size: 11px; padding: 2px 6px; margin: 4px 4px 0 0;
}
.iwb-plp-dialog-sm {
width: 460px;
}
.iwb-promptlib .iwb-pcard {
cursor: grab;
}
.iwb-promptlib .iwb-pcard:active {
cursor: grabbing;
}
.iwb-promptlib .iwb-btn-primary .iwb-ic {
width: 15px; height: 15px;
}
.iwb-promptlib .iwb-btn:hover {
border-color: var(--iwb-brand); color: var(--iwb-brand);
}
.iwb-promptlib .iwb-btn:active {
transform: translateY(1px);
}
.iwb-promptlib .iwb-btn:focus-visible {
outline: 2px solid color-mix(in srgb, var(--iwb-brand) 60%, transparent); outline-offset: 1px;
}
.iwb-promptlib .iwb-btn:disabled {
opacity: 0.45; cursor: not-allowed; transform: none;
}
.iwb-promptlib .iwb-btn-primary {
background: var(--iwb-brand); border-color: var(--iwb-brand); color: var(--iwb-on-brand);
}
.iwb-promptlib .iwb-btn-primary:hover {
background: color-mix(in srgb, var(--iwb-brand) 85%, var(--iwb-text)); border-color: var(--iwb-brand); color: var(--iwb-on-brand);
}
.iwb-promptlib .iwb-btn-sm {
padding: 4px 6px; font-size: 11px;
}
.iwb-promptlib .iwb-btn-danger {
color: var(--iwb-err);
}
.iwb-promptlib .iwb-btn-danger:hover {
border-color: var(--iwb-err); color: var(--iwb-err);
}
.iwb-promptlib .iwb-ctxmenu {
position: fixed; min-width: 196px; max-width: 240px; max-height: calc(100vh - 24px); overflow-y: auto; padding: 6px; background: var(--iwb-layer); border: 1px solid var(--iwb-border); border-radius: 12px; box-shadow: 0 12px 32px rgba(0,0,0,0.28), 0 2px 8px rgba(0,0,0,0.16); z-index: 91; display: flex; flex-direction: column; gap: 2px;
}
.iwb-promptlib .iwb-ctx-title {
font-size: 11px; font-weight: 700; color: var(--iwb-text2); letter-spacing: 1px; padding: 6px 10px 2px; text-transform: uppercase;
}
.iwb-promptlib .iwb-ctx-item {
display: flex; align-items: center; gap: 8px; width: 100%; padding: 6px 10px; border: none; border-radius: 8px; background: transparent; color: var(--iwb-text); font-size: 13px; cursor: pointer; text-align: left;
}
.iwb-promptlib .iwb-ctx-item .iwb-ic {
width: 14px; height: 14px; flex: 0 0 auto; color: var(--iwb-text2);
}
.iwb-promptlib .iwb-ctx-item:hover:not(:disabled) {
background: color-mix(in srgb, var(--iwb-brand) 12%, transparent); color: var(--iwb-text);
}
.iwb-promptlib .iwb-ctx-item:hover:not(:disabled) .iwb-ic {
color: var(--iwb-brand);
}
.iwb-promptlib .iwb-ctx-item:disabled {
opacity: 0.38; cursor: default;
}
.iwb-promptlib .iwb-ctx-item.iwb-ctx-danger {
color: var(--iwb-err);
}
.iwb-promptlib .iwb-ctx-item.iwb-ctx-danger .iwb-ic {
color: var(--iwb-err);
}
.iwb-promptlib .iwb-ctx-item.iwb-ctx-danger:hover:not(:disabled) {
background: color-mix(in srgb, var(--iwb-err) 10%, transparent); color: var(--iwb-err);
}
.iwb-promptlib .iwb-ctx-sep {
height: 1px; margin: 4px 6px; background: var(--iwb-border); flex: 0 0 auto;
}
.iwb-promptlib .iwb-drawer-spacer {
flex: 1 1 auto;
}
/* v1.10.1:详情底部分享组(文本/文件分享)与插入组之间的竖向分割线 */
.iwb-plp-dialog .iwb-plp-foot-vsep {
display: inline-block; width: 1px; height: 18px; flex: 0 0 auto;
align-self: center; margin: 0 12px; background: var(--iwb-border);
}
.iwb-plp-dialog .iwb-section-sub {
margin-top: 2px;
}
.iwb-plp-mask.iwb-mask-ghost .iwb-settings-modal {
box-shadow: 0 24px 60px rgba(0,0,0,.32);
}
/* v1.6.7:卡片长按可拖的视觉反馈 */
.iwb-plp-card{cursor:grab}
.iwb-plp-card.is-armed{border-color:var(--iwb-plp-accent,#7c4dff);box-shadow:0 0 0 2px color-mix(in srgb,var(--iwb-plp-accent,#7c4dff) 20%,transparent)}
.iwb-plp-card.is-dragging{opacity:.55;transform:scale(.98);cursor:grabbing}
/* v1.6.8:卡片悬停放大 + 按下/拖拽反馈 */
.iwb-plp-card{transition:transform .14s ease, box-shadow .14s ease, border-color .14s ease, opacity .14s ease}
.iwb-plp-card:hover{transform:scale(1.03);box-shadow:0 8px 22px rgba(0,0,0,.14);z-index:2}
.iwb-plp-card.is-pressed{border-color:var(--iwb-plp-accent,#7c4dff);box-shadow:0 0 0 2px color-mix(in srgb,var(--iwb-plp-accent,#7c4dff) 22%,transparent)}
.iwb-plp-card.is-dragging{opacity:.55;transform:scale(.98)}
/* v1.6.9:拖拽虚拟卡片(跟手预览) */
.iwb-plp-dragghost{width:168px;display:flex;align-items:center;gap:8px;padding:8px 10px;background:var(--iwb-panel,#fff);border:2px solid var(--iwb-plp-accent,#7c4dff);border-radius: 10px;box-shadow:0 12px 28px rgba(0,0,0,.22);font-size:12px;pointer-events:none;z-index: var(--iwb-z-anchor, 3200)}
.iwb-plp-ghostcov{width:38px;height:38px;border-radius:8px;object-fit:cover;flex:0 0 auto;background:var(--iwb-plugin-inset,#eef0f2)}
.iwb-plp-ghosttxt{min-width:0;display:flex;flex-direction:column;gap:2px}
.iwb-plp-ghostname{font-weight:600;color:var(--iwb-text,#1c2333);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.iwb-plp-ghosthint{font-size: 11px;color:var(--iwb-plp-accent,#5a4bd0)}
/* v1.6.10:悬停放大改为「内层背景层缩放」——卡片命中区域不变,渐变卡不再闪烁 */
.iwb-plp-bg{position:absolute;inset:0;overflow:hidden;border-radius:inherit;transition:transform .16s ease;will-change:transform;backface-visibility:hidden}
.iwb-plp-card:hover .iwb-plp-bg{transform:scale(1.045)}
.iwb-plp-card:hover{border-color:var(--iwb-border2,#b9bfca);box-shadow:0 8px 22px rgba(0,0,0,.14)}
/* 取消卡片本体的缩放/层级切换(闪烁与边缘点击丢失的来源) */
.iwb-plp-card{transform:none}
.iwb-plp-card:hover{transform:none;z-index:auto}
.iwb-plp-card.is-dragging{opacity:.55}
.iwb-plp-bg,.iwb-plp-cover{pointer-events:none}
/* v1.6.11:封面卡瀑布流高度由图片决定 —— 背景层必须是普通流,不能绝对定位(否则卡塌成一条线) */
.iwb-plp-bg{position:relative;inset:auto;width:100%}
.iwb-plp-card.no-cover .iwb-plp-bg{position:absolute;inset:0}
.iwb-plp-bg .iwb-plp-cover{width:100%;height:auto;object-fit:contain;display:block}
/* v1.6.13:未选中时变量输入框不拦截指针 —— 单击节点=选中/可拖动;选中后再点输入框编辑 */
.iwb-plp-node:not(.is-selected) input{pointer-events:none}
.iwb-plp-card{user-select:none}
body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webkit-user-select:none!important}
.iwb-plp-placeghost{border-style:dashed!important;pointer-events:none}
.iwb-plp-placehint{font-size: 11px;color:var(--iwb-plp-accent,#5a4bd0);margin-top:2px}
.iwb-plp-placebox{position:fixed;left:-9999px;top:0;z-index: var(--iwb-z-anchor, 3200);pointer-events:none;border:2px dashed var(--iwb-plp-accent,#6b4dff);border-radius:12px;background:color-mix(in srgb,var(--iwb-plp-accent,#6b4dff) 9%,transparent);display:flex;align-items:center;justify-content:center;box-shadow:0 10px 26px rgba(30,20,80,.10)}
.iwb-plp-placebox-t{font-size:12px;color:var(--iwb-plp-accent,#5a3fd0);background:rgba(255,255,255,.82);border-radius:999px;padding: 4px 10px}
/* v1.6.23:放置指示改为灰色小方框 */
.iwb-plp-placebox{border: 2px dashed var(--iwb-border2, #9aa3ad);border-radius:10px;background:rgba(122,130,142,.10);box-shadow:none}
.iwb-plp-placebox-t{font-size:11px;color: var(--plp-c3, #6b7280);background:rgba(255,255,255,.75);padding:2px 8px}
/* v1.7.0:编辑面板三栏 + 可拖宽;详情封面放大、变量高亮 */
.iwb-plp-eleft{flex:0 0 236px;width:236px}
.iwb-plp-emid{flex:1 1 auto;min-width:220px;display:flex;flex-direction:column;min-height:0}
.iwb-plp-emid .iwb-plp-etext{flex:1 1 auto;min-height:0;resize:none}
.iwb-plp-esplit{flex:0 0 10px;cursor:col-resize;display:flex;align-items:center;justify-content:center;border-radius:6px;background:var(--iwb-plugin-inset,#f3f4f7)}
.iwb-plp-esplit:hover{background:var(--iwb-plugin-hover,#e9ecf1)}
.iwb-plp-eright{flex:0 0 auto;width:300px;min-width:190px;max-width:460px;display:flex;flex-direction:column;min-height:0;background:var(--iwb-plugin-surface,#fafbfc);border:1px solid var(--iwb-border,#e6e8ec);border-radius:10px;padding:8px}
.iwb-plp-vars{flex:1 1 auto;min-height:0;display:flex;flex-direction:column}
.iwb-plp-vrows{flex:1 1 auto;min-height:0;overflow:auto}
.iwb-plp-vitem{padding:4px 0}
.iwb-plp-vrow2{display:flex;align-items:center;gap:6px}
.iwb-plp-vname{flex:1 1 auto;min-width:0;height:32px}
.iwb-plp-vdesc{width:100%;height:28px;margin-top: 6px;border-style:dashed;background: var(--iwb-field, #fbfcfd);font-size: 12px;color: var(--plp-c3, #6b7280)}
/* v1.12.0:变量编辑器折叠两态(收起一行名称+摘要,展开四字段)与内容多行框 */
.iwb-plp-vrow2{cursor:pointer}
.iwb-plp-vcaret{flex:0 0 12px;width:12px;text-align:center;font-size:11px;line-height:32px;color:var(--iwb-text2,#8b929c)}
.iwb-plp-vlabelx{flex:1 1 auto;min-width:0;font-size:13px;line-height:32px;color:var(--iwb-text,#2a2f36);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.iwb-plp-vlabelx.is-empty{color:var(--iwb-text2,#8b929c)}
.iwb-plp-vsum{flex:0 0 auto;font-size:11px;line-height:32px;white-space:nowrap;color:var(--iwb-text2,#8b929c)}
.iwb-plp-vfield{display:flex;align-items:flex-start;gap:8px;margin-top:6px}
.iwb-plp-vflabel{flex:0 0 40px;padding-top:8px;font-size:12px;color:var(--iwb-text2,#8b929c)}
.iwb-plp-vbody{flex:1 1 auto;min-width:0}
.iwb-plp-vbody .iwb-input{width:100%}
.iwb-plp-vbody .iwb-plp-vdesc{margin-top:0}
.iwb-plp-vdef{height:auto;min-height:66px;padding:4px 10px;line-height:1.65;font-size:12px;resize:none;overflow-y:hidden}
.iwb-plp-dcov{flex:0 0 auto;width:180px;height:180px;border-radius:12px;overflow:hidden}
.iwb-plp-dvar{background: var(--iwb-plp-accent-soft, #f1ecff);color: var(--iwb-plp-accent, #5a3fd0);border-radius: 6px;padding:0 4px;font-weight:500}
/* v1.7.1:编辑面板视觉精修——输入框比底色更亮、去多余边框、细分隔线 */
.iwb-plp-dialog .iwb-plp-dbody{gap:10px;padding:12px;background: var(--iwb-plugin-inset, #f4f5f7)}
.iwb-plp-dialog .iwb-plp-eleft{flex:0 0 236px;width:236px;background: var(--iwb-plugin-card, #fff);border: 1px solid var(--iwb-plugin-border, #e6e8ec);border-radius:12px;padding:12px}
.iwb-plp-dialog .iwb-plp-emid{background: var(--iwb-plugin-card, #fff);border: 1px solid var(--iwb-plugin-border, #e6e8ec);border-radius:12px;padding:10px 12px 12px}
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-etext{border: 1px solid var(--iwb-plugin-border, #eef0f3);background: var(--iwb-field, #fbfcfd);border-radius: 8px;padding:10px 12px}
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-etext:focus{background: var(--iwb-plugin-card, #fff);border-color: var(--iwb-plp-accent-border, #cfc3ff);box-shadow:0 0 0 3px rgba(107,77,255,.08)}
.iwb-plp-dialog .iwb-plp-esplit{flex:0 0 6px;background:transparent;border-radius: 6px}
.iwb-plp-dialog .iwb-plp-esplit:hover{background: var(--iwb-plugin-hover, #e7e9ee)}
.iwb-plp-dialog .iwb-plp-esplit::before{content:'';display:block;width:2px;height:30px;border-radius: 6px;background: var(--iwb-plugin-hover, #d7dbe2)}
.iwb-plp-dialog .iwb-plp-eright{background:transparent;border:0;padding:2px 0 0}
.iwb-plp-dialog .iwb-plp-vitem{padding:2px 0}
.iwb-plp-dialog .iwb-plp-vrow2{gap:6px}
.iwb-plp-dialog .iwb-plp-vname{background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eceef2);border-radius:8px;height:32px;padding:0 10px;font-size: 13px;color: var(--iwb-text, #33383f)}
.iwb-plp-dialog .iwb-plp-vname:focus{background: var(--iwb-plugin-card, #fff);border-color: var(--iwb-plp-accent-border, #cfc3ff);box-shadow:0 0 0 3px rgba(107,77,255,.08)}
.iwb-plp-dialog .iwb-plp-vdesc{background: var(--iwb-field, #fbfcfd);border: 1px dashed var(--iwb-plugin-border, #e2e6ec);border-radius: 8px;height:28px;margin-top:4px}
.iwb-plp-dialog .iwb-plp-lrow span{color: var(--iwb-text2, #8a919c);font-size: 12px}
.iwb-plp-dialog .iwb-plp-lrow .iwb-input{background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eceef2);border-radius:8px;height:32px}
.iwb-plp-dialog .iwb-plp-lrow .iwb-input:focus{background: var(--iwb-plugin-card, #fff);border-color: var(--iwb-plp-accent-border, #cfc3ff)}
/* v1.7.2:正文变量高亮(黑粗)+ 说明灰按钮 + 说明背景回归面板底 */
.iwb-plp-ewrap{position:relative;flex:1 1 auto;min-height:0;display:flex;border-radius: 8px;background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eef0f3)}
.iwb-plp-ewrap:focus-within{background: var(--iwb-plugin-card, #fff);border-color: var(--iwb-plp-accent-border, #cfc3ff);box-shadow:0 0 0 3px rgba(107,77,255,.08)}
.iwb-plp-ewrap .iwb-plp-etext{flex:1 1 auto;min-height:0;border:0;background:transparent;box-shadow:none;color:transparent;caret-color:var(--plp-c22, #1d2129);position:relative;z-index:1;resize:none}
.iwb-plp-ewrap .iwb-plp-etext:focus{background:transparent;border:0;box-shadow:none}
.iwb-plp-hl{position:absolute;inset:0;padding:10px 12px;overflow:hidden;white-space:pre-wrap;word-wrap:break-word;font-size:13px;line-height:1.9;color: var(--iwb-text2, #5b6472);pointer-events:none;z-index:0}
.iwb-plp-hlvar{color: var(--iwb-text, #1d2129);font-weight:600}
.iwb-plp-dialog .iwb-plp-vdesc{background:transparent;border: 1px dashed var(--iwb-plugin-border, #dfe3e9)}
.iwb-plp-dvar{background:transparent;color: var(--iwb-text, #1d2129);font-weight:600;padding:0}
.iwb-plp-hres{height:6px;margin: -4px 0 0;cursor:ns-resize;flex:0 0 auto;border-radius: 6px}
.iwb-plp-hres:hover{background: var(--iwb-plugin-hover, #e7e9ee)}
/* 正文可见性:textarea 透明,显示下方高亮层 */
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap{flex:1 1 auto;min-height:0;position:relative;display:flex;background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eef0f3);border-radius: 8px}
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext{background:transparent!important;color:transparent!important;border:0!important;box-shadow:none!important;padding:10px 12px}
.iwb-plp-dialog .iwb-plp-hl{padding:10px 12px;font-size:13px;line-height:1.9}
.iwb-plp-namebox{min-height:34px;height:34px;line-height:1.45;padding: 6px 10px;resize:vertical;overflow:auto;font-size: 13px}
.iwb-plp-insvar{color: var(--iwb-text, #1d2129)!important;background: var(--iwb-plugin-card, #fff)!important;border-color: var(--iwb-plugin-border, #e2e6ec)!important}
.iwb-plp-insvar:hover{background: var(--iwb-plugin-inset, #f4f6f9)!important}
/* v1.7.5:编辑封面卡在框内;详情封面放大 */
.iwb-plp-dialog .iwb-plp-ecov{width:100%;height:250px;overflow:hidden;border-radius:12px;background:var(--iwb-plugin-inset,#f3f4f7)}
.iwb-plp-dialog .iwb-plp-ecov .iwb-plp-cover{width:100%;height:100%;object-fit:cover;object-position:center;display:block;border-radius:12px}
.iwb-plp-dialog-detail .iwb-plp-dbody{align-items:flex-start}
.iwb-plp-dialog .iwb-plp-dcov{width:264px;height:264px;flex:0 0 auto;overflow:hidden;border-radius:12px;background:var(--iwb-plugin-inset,#f3f4f7)}
.iwb-plp-dialog .iwb-plp-dcov .iwb-plp-cover{width:100%;height:100%;object-fit:cover;object-position:center;display:block;border-radius:12px}
/* v1.7.6:封面完整展示(contain),不裁剪 */
.iwb-plp-dialog .iwb-plp-ecov .iwb-plp-cover{object-fit:contain;background:transparent}
.iwb-plp-dialog .iwb-plp-dcov .iwb-plp-cover{object-fit:contain;background:transparent}
.iwb-plp-dialog .iwb-plp-ecov{background:var(--iwb-plugin-inset,#f3f4f7)}
.iwb-plp-dialog .iwb-plp-dcov{background:var(--iwb-plugin-inset,#f3f4f7)}
/* v1.7.7:编辑区文字层与高亮层使用完全一致的字体度量,修复光标/选区错位 */
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext,
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-hl{
font-family:-apple-system,BlinkMacSystemFont,'PingFang SC','Helvetica Neue',system-ui,sans-serif!important;
font-size:13px!important;
line-height:1.85!important;
letter-spacing:0!important;
padding:10px 12px!important;
margin:0!important;
border:0!important;
box-sizing:border-box!important;
white-space:pre-wrap!important;
overflow-wrap:break-word!important;
word-break:break-word!important;
tab-size:4!important;
}
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext{overflow-y:auto!important;scrollbar-gutter:stable}
/* v1.9.3:高亮层与 textarea 用同样的滚动条占位,避免换行位置不一致导致色块漂移 */
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-hl{overflow:hidden!important;scrollbar-gutter:stable}
/* v1.7.9:详情正文独立滚动,长文不再压到底部按钮 */
.iwb-plp-dialog-detail .iwb-plp-dbody{overflow:hidden;align-items:stretch}
.iwb-plp-dialog-detail .iwb-plp-dright{flex:1 1 auto;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden}
.iwb-plp-dialog-detail .iwb-plp-dtext{flex:1 1 auto;min-height:0;overflow:auto;padding-right:10px;margin-bottom:6px}
/* v1.8.0:详情标题/分组/标签移到封面下方;编辑标签改为输入+加号 */
.iwb-plp-dialog-detail .iwb-plp-dbody{align-items:flex-start}
.iwb-plp-dleftcol{flex:0 0 264px;width:264px;display:flex;flex-direction:column;min-width:0}
.iwb-plp-dtitle{font-size: 17px;font-weight:650;line-height:1.35;margin-top: 12px;color:var(--iwb-text,#1d2129)}
.iwb-plp-dmeta{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-top:8px}
.iwb-plp-dgroup{font-size: 12px;background: var(--iwb-plugin-inset, #eef0f4);color: var(--iwb-text2, #5b6472);border-radius:999px;padding: 2px 8px}
.iwb-plp-dtag{font-size: 12px;background: var(--iwb-plp-accent-soft, #f4f0ff);color: var(--iwb-plp-accent, #5a3fd0);border-radius:999px;padding: 2px 8px}
.iwb-plp-dlen{font-size: 12px;color: var(--iwb-text-dim, #9aa1ac)}
.iwb-plp-tagwrap{display:flex;flex-direction:column;gap:6px;flex:1;min-width:0}
.iwb-plp-tagchips{display:flex;flex-wrap:wrap;gap: 6px}
.iwb-plp-tagchip{display:inline-flex;align-items:center;gap:4px;font-size: 12px;background: var(--iwb-plugin-inset, #eef0f4);border-radius:999px;padding:2px 8px;color: var(--iwb-text, #3f4450)}
.iwb-plp-tagx{cursor:pointer;color: var(--iwb-text-dim, #9aa1ac);font-style:normal}
.iwb-plp-tagx:hover{color: var(--iwb-err, #c0392b)}
.iwb-plp-tagrow{display:flex;gap:6px}
.iwb-plp-tagin{flex:1;min-width:0;height:30px}
.iwb-plp-lrow-tags{align-items:flex-start}
.iwb-plp-tagadd{flex:0 0 auto;width:30px;height:30px;padding:0;font-size:15px;line-height:28px}
/* v1.8.1:详情标题/分组/标签左对齐并带标题;标签加号对齐修复 */
.iwb-plp-dtitle{font-size:20px;font-weight:650;line-height:1.35;margin-top:16px;color:var(--iwb-text,#1d2129)}
.iwb-plp-dmeta{display:flex;flex-direction:column;gap: 6px;margin-top:12px;align-items:flex-start}
.iwb-plp-dmrow{display:flex;align-items:center;gap:10px;width:100%}
.iwb-plp-dmk{flex:0 0 30px;width:30px;font-size: 12px;color: var(--iwb-text-dim, #9aa1ac)}
.iwb-plp-dmv{display:flex;flex-wrap:wrap;align-items:center;gap: 6px;min-width:0}
.iwb-plp-dgroup{font-size:12px;color: var(--iwb-text, #3f4450);background: var(--iwb-plugin-inset, #f2f4f7);border-radius:6px;padding: 2px 8px}
.iwb-plp-dtag{font-size: 12px;color: var(--iwb-plp-accent, #5a3fd0);background: var(--iwb-plp-accent-soft, #f4f0ff);border-radius:6px;padding: 2px 8px}
.iwb-plp-dempty{font-size:12px;color: var(--iwb-text-dim, #b3b9c2)}
.iwb-plp-dlen{font-size:12px;color: var(--iwb-text2, #8a919c)}
.iwb-plp-tagrow{display:flex;align-items:center;gap:6px}
.iwb-plp-tagin{height:30px;border-radius:8px}
.iwb-plp-tagadd{flex:0 0 auto;width:30px;height:30px;padding:0;border-radius:8px;background: var(--iwb-plugin-inset, #f2f4f7);border: 1px solid var(--iwb-plugin-border, #e2e6ec);color: var(--iwb-text2, #5b6472);font-size: 15px;line-height:1;display:inline-flex;align-items:center;justify-content:center}
.iwb-plp-tagadd:hover{background: var(--iwb-plugin-hover, #e9ecf1)}
/* v1.8.2:详情左右两栏卡片化 + 分割线 */
.iwb-plp-dialog-detail .iwb-plp-dbody{gap: 12px;padding:16px;background: var(--iwb-plugin-inset, #f4f5f7)}
.iwb-plp-dialog-detail .iwb-plp-dleftcol{flex:0 0 300px;width:300px;padding:12px;border: 1px solid var(--iwb-plugin-border, #e8eaee);border-radius:14px;background: var(--iwb-plugin-card, #fff);align-self:flex-start}
.iwb-plp-dialog-detail .iwb-plp-dcov{width:100%;height:270px;border-radius:10px}
.iwb-plp-dialog-detail .iwb-plp-dtitle{font-size:20px;font-weight:650;line-height:1.35;margin-top: 12px;color:var(--iwb-text,#1d2129)}
.iwb-plp-dialog-detail .iwb-plp-dmeta{margin-top:12px;padding-top:12px;border-top: 1px solid var(--iwb-plugin-border, #eef0f3);gap:8px}
.iwb-plp-dialog-detail .iwb-plp-dright{flex:1 1 auto;min-width:0;min-height:0;display:flex;flex-direction:column;padding: 12px 16px;border: 1px solid var(--iwb-plugin-border, #e8eaee);border-radius:14px;background: var(--iwb-plugin-card, #fff);overflow:hidden}
.iwb-plp-dsec{font-size: 12px;font-weight:600;color: var(--iwb-text2, #8a919c);letter-spacing:.04em;padding-bottom:8px;margin-bottom:8px;border-bottom: 1px solid var(--iwb-plugin-border, #eef0f3);flex:0 0 auto}
.iwb-plp-dialog-detail .iwb-plp-dtext{flex:1 1 auto;min-height:0;overflow:auto;padding-right:10px;font-size: 14px;line-height:2;color: var(--iwb-text, #3a4048)}
/* v1.8.3:详情左卡片撑到底、四边等距;正文恢复滚动不被底部遮挡 */
.iwb-plp-dialog-detail{display:flex;flex-direction:column;overflow:hidden}
.iwb-plp-dialog-detail .iwb-plp-dbody{display:flex;flex:1 1 auto;min-height:0;overflow:hidden;gap: 12px;padding:16px;background: var(--iwb-plugin-inset, #f4f5f7)}
.iwb-plp-dialog-detail .iwb-plp-dleftcol{align-self:stretch;display:flex;flex-direction:column;overflow:auto;padding:12px;border: 1px solid var(--iwb-plugin-border, #e8eaee);border-radius:14px;background: var(--iwb-plugin-card, #fff)}
.iwb-plp-dialog-detail .iwb-plp-dright{flex:1 1 auto;min-width:0;min-height:0;overflow:hidden;display:flex;flex-direction:column;padding: 12px 16px;border: 1px solid var(--iwb-plugin-border, #e8eaee);border-radius:14px;background: var(--iwb-plugin-card, #fff)}
.iwb-plp-dialog-detail .iwb-plp-dtext{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;padding-right:8px}
.iwb-plp-dialog-detail .iwb-plp-dfooter{flex:0 0 auto}
/* v1.8.4:右卡片纵向拉伸填满,正文出现滚动条 */
.iwb-plp-dialog-detail .iwb-plp-dbody{align-items:stretch!important}
.iwb-plp-dialog-detail .iwb-plp-dright{align-self:stretch!important;height:100%;max-height:100%;overflow:hidden!important}
.iwb-plp-dialog-detail .iwb-plp-dtext{flex:1 1 0;min-height:0;overflow-y:auto!important;overflow-x:hidden}
/* v1.8.7:详情标题缩小;分组/标签去底色;元信息加分割线与行高 */
.iwb-plp-dialog-detail .iwb-plp-dtitle{font-size:17px!important;font-weight:650;margin-top:12px}
.iwb-plp-dialog-detail .iwb-plp-dmeta{margin-top:12px;padding-top: 12px;border-top: 1px solid var(--iwb-plugin-border, #eef0f3);gap:10px}
.iwb-plp-dialog-detail .iwb-plp-dmrow{gap:6px}
.iwb-plp-dialog-detail .iwb-plp-dmk{flex:0 0 auto;width:auto;font-size:12px;line-height:1.6;color: var(--iwb-text-dim, #9aa1ac)}
.iwb-plp-dialog-detail .iwb-plp-dgroup,.iwb-plp-dialog-detail .iwb-plp-dtag{background:transparent!important;padding:0!important;border-radius:0!important;font-size: 13px;line-height:1.6;color: var(--iwb-text, #2f3540)}
.iwb-plp-dialog-detail .iwb-plp-dtag{color: var(--iwb-plp-accent, #5a3fd0);}
.iwb-plp-dialog-detail .iwb-plp-dlen{font-size: 13px;line-height:1.6;color: var(--iwb-text, #2f3540)}
/* v1.8.8:详情标题 14px;元信息行间浅分割线;封面底色更接近白色(编辑/详情统一) */
.iwb-plp-dialog-detail .iwb-plp-dtitle{font-size:14px!important;font-weight:650;line-height:1.5;margin-top:12px}
.iwb-plp-dialog-detail .iwb-plp-dmeta{gap:0}
.iwb-plp-dialog-detail .iwb-plp-dmrow{padding: 6px 0;border-bottom: 1px solid var(--iwb-plugin-border, #f3f5f8)}
.iwb-plp-dialog-detail .iwb-plp-dmrow:last-child{border-bottom:0}
.iwb-plp-dialog .iwb-plp-dcov,.iwb-plp-dialog .iwb-plp-ecov{background: var(--iwb-field, #fcfcfd)!important}
.iwb-plp-dialog .iwb-plp-dcov .iwb-plp-cover,.iwb-plp-dialog .iwb-plp-ecov .iwb-plp-cover{background:transparent!important}
/* v1.8.19:编辑区高亮变量不得加粗——加粗会改变字形宽度,导致点击位置逐次向左偏移 */
.iwb-plp-hlvar{font-weight:400!important;letter-spacing:normal!important}
/* v1.9.3:变量着色改为「textarea 只负责文字 + 背层只画浅主色色块」——
两层字体/换行/滚动条占位由 v1.7.7 规则保持一致,变量 span 沿用 400 字重(不加粗,宽度不漂移),
文字仍由 textarea 自己画(可见),所以插入点/点击/选区完全不受影响。
注:v1.8.20 停用高亮层是因为当时「透明 textarea + 背层画文字」两层文字错位;本版不画文字,只画色块,不会复发。 */
.iwb-plp-ewrap .iwb-plp-hl{display:block!important;color:transparent!important;-webkit-text-fill-color:transparent!important}
.iwb-plp-hlvar{color:transparent!important;-webkit-text-fill-color:transparent!important;background:color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 16%, transparent);border-radius:6px;box-shadow:0 0 0 1px color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 22%, transparent)}
.iwb-plp-ewrap .iwb-plp-etext{color:var(--iwb-text,#2a2f36)!important;background:transparent!important}
/* v1.8.21:正文文字必须可见(覆盖旧的 transparent !important) */
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext{color:var(--iwb-text,#2a2f36)!important;caret-color:var(--iwb-text,#2a2f36)!important;-webkit-text-fill-color:var(--iwb-text,#2a2f36)!important}
/* v1.9.3:右侧变量名与详情正文里的变量也用主色呼应(只读区,零功能风险) */
.iwb-plp-dialog .iwb-plp-vname{color:var(--iwb-plp-accent,#5a3fd0)}
.iwb-plp-dialog .iwb-plp-dvar{color:var(--iwb-plp-accent,#5a3fd0);background:var(--iwb-plp-accent-soft,#f1ecff);border-radius:6px;padding:0 2px}
/* 回滚开关:若真机发现任何点击/光标异常,把下行打开即回到 v1.8.20 纯 textarea 状态。
.iwb-plp-ewrap .iwb-plp-hl{display:none!important} */
/* v1.13.1:变量栏去掉 i 圆按钮,按设计 token 在「行与行之间」画分割线(位置 2)。
依据 design-tokens.md §3.11:--iwb-set-divider 是容器内行间线,首行不画线。
注意该变量只在 .iwb-settings-modal 作用域定义,插件面板不在其中 ⇒ 按同一公式就地兜底,
否则会掉到全强度 --iwb-border(比规范深一档)。暗色下 --iwb-border 自动换值。
用相邻兄弟选择器,首项自然不画、末项之后也没有线;标题下与展开字段前都不另画线,
避免一屏出现三层线。整行 hover + 展开态 caret 接替原来 i 按钮的「可点击」提示。 */
.iwb-plp-vitem + .iwb-plp-vitem{border-top:var(--iwb-bw, 1px) solid var(--iwb-set-divider, color-mix(in srgb, var(--iwb-border) 55%, transparent));padding-top:var(--iwb-space-8)}
.iwb-plp-dialog .iwb-plp-vrow2{padding:0 var(--iwb-space-4)}
.iwb-plp-dialog .iwb-plp-vrow2:hover{background:var(--iwb-plugin-hover);border-radius:var(--iwb-radius-control, var(--iwb-radius-card))}
.iwb-plp-vitem.is-open .iwb-plp-vcaret{color:var(--iwb-plp-accent, var(--iwb-text2))}
+275
View File
@@ -0,0 +1,275 @@
// promptlib 本地契约测试(纯 node):
// - v1.9.2:分享带封面开关
// - v1.9.3:编辑区变量浅主色底色(方案 C,只画色块不改输入)
// - v1.10.0:文本分享 / 文件分享双路径 + 顶部三按钮 + 右键去分类 + 设置去导入入口
// - v1.10.1:移除「分享时附带封面图片」开关 + 详情底部分享/插入组间竖向分割线
// 运行:node promptlib/tools/harness.mjs (退出码 0 = 全过)
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import vm from 'node:vm'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const ROOT = path.resolve(HERE, '..')
const src = fs.readFileSync(path.join(ROOT, 'src/index.js'), 'utf8')
const css = fs.readFileSync(path.join(ROOT, 'styles.css'), 'utf8')
let failed = 0
const ok = (name, cond) => {
if (!cond) failed++
console.log((cond ? '✓ ' : '✗ ') + name)
}
// ---- 1) 版本 / manifest ----
ok("manifest.version = 1.13.1", /version:\s*'1\.13\.1'/.test(src))
ok('package.json version = 1.13.1',
JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version === '1.13.1')
ok('manifest 已移除「分享时附带封面图片」开关声明',
!/shareWithCover:\s*\{\s*type:\s*'boolean'/.test(src))
ok('源码不再定义/读取 shareWithCover 设置',
!/function shareWithCover \(\)/.test(src) && !/S\.get\('shareWithCover'\)/.test(src))
// ---- 2) sharePayload 两条显式分支 ----
const m = src.match(/ function sharePayload \(p, withCover\) \{[\s\S]*?\n \}\n function shareFileName/)
ok('从 src 找到 sharePayload(p, withCover)', !!m)
const fnSrc = m ? m[0].replace(/\n function shareFileName$/, '') : ''
const sandbox = {
SHARE_TAG: 'IWB-PROMPT-SHARE',
varsOf: () => [],
coverToDataUrl: () => { throw new Error('不该读封面') },
Promise, JSON, String, Number, Array, Object,
}
vm.createContext(sandbox)
vm.runInContext(fnSrc, sandbox)
const p = { name: '测试词', text: '一只猫', group: '分组A', tags: ['x'], cover: { img: 'a.jpg' } }
const textPlain = await sandbox.sharePayload(p, false)
const bodyPlain = JSON.parse(textPlain.split('\n')[1])
ok('文本分享(false):分享文本无 cover 字段', !('cover' in bodyPlain.sharing))
ok('文本分享(false):不读封面(stub 抛错未触发)', true)
ok('文本分享(false):名字/正文/分组仍在',
bodyPlain.sharing.name === '测试词' && bodyPlain.sharing.text === '一只猫' && bodyPlain.sharing.group === '分组A')
sandbox.coverToDataUrl = () => Promise.resolve('data:image/jpeg;base64,AAAA')
const textFile = await sandbox.sharePayload(p, true)
const bodyFile = JSON.parse(textFile.split('\n')[1])
ok('文件分享(true):分享文本带 cover', bodyFile.sharing.cover === 'data:image/jpeg;base64,AAAA')
// ---- 3) v1.10.0 UI 契约 ----
ok('文本分享复制纯文字(doShareText 用 api.copy)',
/function doShareText \(p\)[\s\S]{0,260}api\.copy\(text\)/.test(src))
ok('文件分享导出为文件(doShareFile 用 api.exportText)',
/function doShareFile \(p\)[\s\S]{0,260}api\.exportText\(shareFileName\(p\), text\)/.test(src))
ok('文件名做安全化(过滤 \\/:*?"<>|)',
/replace\(\/\[\\\\\/:\*\?"<>\|]\/g, '_'\)/.test(src))
ok('剪贴板导入与文件导入共用 importShareItem(1 定义 + 2 调用)',
(src.match(/importShareItem\s*\(item\)/g) || []).length >= 3)
ok('文件导入走 api.importText()',
/function importShareFromFile \(\)[\s\S]{0,160}api\.importText\(\)/.test(src))
ok('顶部三按钮:文件 / 文本 / 新建',
/text: '文件'[\s\S]{0,200}text: '文本'[\s\S]{0,200}text: '新建'/.test(src))
ok('右键菜单已去掉「移动到分组」分类',
!/移动到分组/.test(src))
ok('右键菜单含 文本分享 / 文件分享(iwb-ctx-item 项)',
/iwb-ctx-item', text: '文本分享'[\s\S]{0,260}iwb-ctx-item', text: '文件分享'/.test(src))
ok('详情底部含 文本分享 / 文件分享 两按钮',
/text: '文本分享'/.test(src) && /text: '文件分享'/.test(src))
ok('详情底部分享组与插入组之间是竖向分割线(DOM 顺序:文件分享 → 竖线 → 复制全文)',
/footEl\.appendChild\(shareFile\)[\s\S]{0,240}iwb-plp-foot-vsep[\s\S]{0,160}footEl\.appendChild\(cp\)/.test(src))
ok('竖线样式:1px 宽 / 18px 高 / 边框色 / 居中',
/\.iwb-plp-foot-vsep\s*\{[^}]*width:\s*1px[^}]*height:\s*18px[^}]*align-self:\s*center[^}]*background:\s*var\(--iwb-border\)/.test(css))
ok('设置面板不再有单条导入入口(impShareBtn 已移除)',
!/impShareBtn/.test(src))
ok('旧的「分享…」按钮(带图完整版)已删除',
!/text: '分享'/.test(src) && !/function doShare \(p\)/.test(src))
// ---- 4) v1.9.3 变量着色样式不变量(回归保护)----
ok('高亮层恢复显示(不再 display:none)',
/\.iwb-plp-ewrap \.iwb-plp-hl\{display:block!important/.test(css))
ok('高亮层整层文字透明(不与 textarea 重影)',
/\.iwb-plp-ewrap \.iwb-plp-hl\{[^}]*color:transparent!important[^}]*-webkit-text-fill-color:transparent!important/.test(css))
ok('变量 span 只画主色背景、不画文字',
/\.iwb-plp-hlvar\{[^}]*color:transparent!important[^}]*background:color-mix\(in srgb, var\(--iwb-plp-accent/.test(css))
ok('变量 span 不加粗(避开点击偏移根因)',
/\.iwb-plp-hlvar\{font-weight:400!important/.test(css))
ok('textarea 文字仍可见(-webkit-text-fill-color 兜底)',
/\.iwb-plp-etext\{color:var\(--iwb-text[^}]*-webkit-text-fill-color:var\(--iwb-text/.test(css))
ok('高亮层与 textarea 滚动条占位一致',
/\.iwb-plp-emid \.iwb-plp-ewrap \.iwb-plp-hl\{overflow:hidden!important;scrollbar-gutter:stable\}/.test(css))
ok('高亮层跟随 textarea 横向滚动',
/hl\.scrollTop = textIn\.scrollTop; hl\.scrollLeft = textIn\.scrollLeft/.test(src))
ok('右侧变量名与详情变量用主色呼应',
/\.iwb-plp-vname\{color:var\(--iwb-plp-accent/.test(css) && /\.iwb-plp-dvar\{color:var\(--iwb-plp-accent/.test(css))
// ---- 5) v1.11.0 封面文件治理(P1)----
// 目标:① 保存/上传时把内联 base64 落成文件;② 孤儿封面能被回收;③ 回收不能误删。
// 纯文本断言跑不了真实 FS ⇒ 这里用「函数抽出来 + 假 fileApi」跑行为。
ok('封面命名统一走 coverFileName(哈希只在它内部实现一次)',
/function coverFileName \(dataUrl\)/.test(src) && (src.match(/var h = 5381/g) || []).length === 1 && (src.match(/coverFileName\(/g) || []).length >= 6)
ok('保存路径先落文件(ensureCoverFile 包住 doSave)',
/function doSave \(\)[\s\S]{0,600}ensureCoverFile\(c\.cover\)/.test(src))
ok('上传封面即落文件(不再把 dataURL 写回 draft.cover)',
/api\.putCover\([\s\S]{0,400}ensureCoverFile\(r\.ref\)/.test(src))
ok('删词条后安排一次回收', /已删除'[\s\S]{0,80}scheduleCoverGc\(/.test(src))
ok('启动加载后安排一次回收(等 convertInlineCovers 写完)',
/convertInlineCovers\(\)[\s\S]{0,120}scheduleCoverGc\(4000\)/.test(src))
ok('自动回收有「数据来源」闸门(不是插件 JSON 读来的就不删)',
/!o\.manual && !dataFromPlugin\) return Promise\.resolve\(\{ removed: 0, bytes: 0, skipped: 'no-source' \}\)/.test(src))
ok('keep 为空时不删(空集合 = 全删的形状)',
/if \(!kept && !o\.manual\) return Promise\.resolve\(\{ removed: 0, bytes: 0, skipped: 'empty' \}\)/.test(src))
ok('只删图片扩展名文件', src.includes('/\\.(jpg|jpeg|png|webp)$/i.test(name)'))
ok('设置页有显式清理入口 + 现读一次数据',
/text: '清理未引用封面'/.test(src) && /plpGcCoverFiles\(FA, plpCoverNamesOf\(state\.prompts\), \{ manual: true \}\)/.test(src))
ok('pending(刚 put 未被引用)不会被回收',
/Object\.keys\(pendingCoverNames\)\.forEach\(function \(n\) \{ names\.push\(n\) \}\)/.test(src))
// 行为:抽出 plpGcCoverFiles 本体,用假 fileApi 验证「只删未被引用的图片文件」
const gcMatch = src.match(/ function plpGcCoverFiles \(FA, keepNames, opts\) \{[\s\S]*?\n \}\n/)
ok('从 src 抽出 plpGcCoverFiles', !!gcMatch)
if (gcMatch) {
const removed = []
const fakeFA = {
list: async () => [
{ name: 'cused1.jpg', size: 100 },
{ name: 'corphan1.jpg', size: 200 },
{ name: 'cshared.jpg', size: 300 },
{ name: 'notes.txt', size: 1 },
],
remove: async (name) => { removed.push(name); return { ok: true } },
}
const gcSandbox = { Promise, JSON, String, Number, Array, Object, RegExp, console }
vm.createContext(gcSandbox)
vm.runInContext('var PLP_GC_BUSY = false\n' + gcMatch[0] + '\nthis.gc = plpGcCoverFiles', gcSandbox)
const r1 = await gcSandbox.gc(fakeFA, ['cused1.jpg'], {})
ok('回收:只删未引用图片(保留引用项与非图片文件)',
JSON.stringify(removed) === '["corphan1.jpg","cshared.jpg"]')
ok('回收:返回删除数与字节数', r1.removed === 2 && r1.bytes === 500)
const r2 = await gcSandbox.gc(fakeFA, [], {})
ok('回收:keep 为空且非人工 ⇒ 不删(skipped=empty)', r2.skipped === 'empty' && r2.removed === 0)
const r3 = await gcSandbox.gc(null, [], {})
ok('回收:无文件能力 ⇒ skipped=no-fs', r3.skipped === 'no-fs')
}
// ---- 8) v1.12.0 变量四字段(名称/内容/说明/占位符)+ 节点多行变量框 ----
ok('节点变量框已换成 textarea 且显式 rows=1(默认 2 行会把单行撑成两行高)',
src.includes("el('textarea', { class: 'iwb-input iwb-plp-nin', rows: '1'"))
ok('自动增高三步:先 height=auto 再读 scrollHeight',
/ta\.style\.height = 'auto'[\s\S]{0,160}scrollHeight/.test(src))
ok('节点变量框拦 pointerdown(宿主白名单不含 textarea,否则拖选文字会拖动节点)',
src.includes("inp.addEventListener('pointerdown'") && src.includes('e.stopPropagation()'))
ok('节点变量框只在内容溢出时拦滚轮(不破坏画布缩放)',
src.includes('if (inp.scrollHeight > inp.clientHeight + 1) e.stopPropagation()'))
ok('v1.13.0 插入变量时选中的原文直接当占位符(塞不进 {} 才退到变量N)',
src.includes('var embed = contentKeyOf(picked)') && src.includes("if (picked) varEd.preset(name, { def: picked })"))
ok('v1.12.3 编辑器只有三个输入项(名称/内容/说明),占位符框已移除',
src.includes("'变量名称(节点上最多显示 4 字)'") &&
src.includes("class: 'iwb-input iwb-plp-vdef', rows: '3'") &&
src.includes("placeholder: '说明(可选)'") &&
!src.includes('iwb-plp-vkey') && !src.includes('占位符(≤'))
ok('v1.12.3 变量区的功能性说明文案已删(顶部 hint / 橙色 tip / 底部 khint)',
!src.includes('名称只影响显示 · 内容可多行 · 与正文双向同步') &&
!src.includes('iwb-plp-vtip') && !src.includes('iwb-plp-vkhint'))
ok('sync 保留 label 与 def(旧实现每次 sync 吃掉名称与内容)',
src.includes('label: prev.label, desc: prev.desc, def: prev.def'))
ok('v1.13.0 内容框显示「内容」,空时退回正文里的键',
src.includes('function bodyOf (v) { return v.def || v.key }'))
ok('v1.12.3 新建节点不再预填 vars(输入框默认为空)',
src.includes('vars: {}, cover:') && !src.includes('vars: defaultVarsOf'))
ok('v1.12.3 节点 placeholder 取「说明 → 内容」(不填说明时展示内容文案)',
src.includes('placeholder: v.desc || v.def ||'))
ok('v1.12.3 节点输入框默认空(不再回退 def 当 value)',
src.includes("inp.value = String((d.vars && d.vars[v.key]) || '')"))
ok('v1.12.3 留空时输出用内容兜底(否则 outputText 会把这段从提示词删掉)',
src.includes('vv[k] = st.inputs[k].value || st.defOf(k)') &&
src.includes('eff[k] = String(raw[k] || \'\') || defOf(k)'))
ok('v1.12.3 vars 只存原始输入(空就是空,下次打开仍为空)',
src.includes('var patch = { vars: raw, text: outputText'))
ok('v1.12.3 「未填」只统计既没填也没内容的变量',
src.includes('!st.defOf(k).trim()) missing++'))
ok('v1.12.3 defOf 挂在 st 上(scheduleUpdate 与 syncTplNode 是两个函数,局部声明会 ReferenceError)',
src.includes('st.defOf = function (k)') &&
src.includes("var defOf = (typeof st.defOf === 'function') ? st.defOf"))
ok('v1.12.3 空框按 placeholder 折行量高度(提示第二行不被裁)',
src.includes('ta.value = ph; restore = true') && src.includes('if (restore) { ta.value = \'\''))
ok('样式:变量行不再是固定 26px 单行',
!css.includes('.iwb-plp-nrow{display:flex;align-items:center;gap:6px;height:26px}') &&
css.includes('.iwb-plp-nrow{display:flex;align-items:flex-start;gap:6px;min-height:26px}'))
ok('样式:变量框不再固定 24px 高',
!css.includes('.iwb-plp-nin{flex:1;height:24px') && css.includes('min-height:24px'))
ok('样式:收起态摘要与三角已定义',
css.includes('.iwb-plp-vsum{') && css.includes('.iwb-plp-vcaret{'))
ok('样式:内容多行框 3 行起步(min-height 66px,overflow 由 JS 控制)',
css.includes('.iwb-plp-vdef{height:auto;min-height:66px'))
ok('v1.13.0 节点变量标签列定宽 4 字(56px),输入框左边缘才对齐',
css.includes('.iwb-plp-nk{flex:0 0 56px;width:56px;max-width:56px') &&
!css.includes('.iwb-plp-nk{flex:0 0 auto'))
ok('v1.13.0 名称框提示说明「节点上最多显示 4 字」',
src.includes("'变量名称(节点上最多显示 4 字)'"))
// ---- 10) v1.13.0 名称 ⇄ 正文联动 + 内容框 10 行 ----
ok('v1.13.0 内容框上限 10 行(VDEF_MAX 212,用户要求 +4 行)',
/var VDEF_MAX = 212/.test(src) && !/var VDEF_MAX = 132/.test(src))
ok('v1.13.0 占位符上限与所有正则一致(KEY_MAX 60,5 处 {1,60})',
/var KEY_MAX = 60/.test(src) &&
(src.match(/\{1,60\}/g) || []).length >= 6 &&
!/\{1,24\}/.test(src))
ok('v1.13.0 内容 → 正文联动:改内容即改 {…}(curText 取实时正文,不吃防抖的旧值)',
src.includes('function curText ()') &&
src.includes('var next = contentKeyOf(area.value)') &&
src.includes("cur.split('{' + old + '}').join('{' + next + '}')"))
ok('v1.13.0 名称只改节点显示,不动正文',
/nameIn\.addEventListener\('input', function \(\) \{\s*\n\s*v\.label = nameIn\.value\s*\n\s*title\.textContent = v\.label \|\| v\.key/.test(src))
ok('v1.13.0 内容塞不进 {} 时保留原键 + 摘要里提示(绝不硬塞,免得变量被识别掉)',
src.includes('正文未同步(需单行 ≤') &&
/v1\.13\.0: 不|v1\.13\.0:不再在打开时改写正文/.test(src))
ok('v1.13.0 抽屉把实时正文 getText 交给编辑器',
src.includes('getText: function () { return textIn.value }'))
// ---- 9) v1.12.2 搜索框常驻(中文输入法组合态不被重建打断)----
ok('v1.12.2 搜索框不再在 render 里 clear(fixed) 重建(render 只清其余节点)',
!/function render \(\) \{\s*\n\s*clear\(fixed\); clear\(scrollBox\)/.test(src) &&
src.includes('Array.prototype.slice.call(fixed.children).forEach'))
ok('v1.12.2 搜索框只创建一次(ensureSearchRow 复用同一个节点)',
src.includes('function ensureSearchRow ()') && src.includes('if (searchRow) return searchRow'))
ok('v1.12.2 输入法组合态:compositionstart/end + 组合中不重排',
src.includes("searchEl.addEventListener('compositionstart'") &&
src.includes("searchEl.addEventListener('compositionend'") &&
/composing \|\| \(e && e\.isComposing\)\) return/.test(src))
ok('v1.12.2 结果重排走 120ms 防抖(打字不再逐键全量重建)',
src.includes('function scheduleResults ()') && src.includes('setTimeout(function () { searchTimer = 0; render() }, 120)'))
ok('v1.12.2 清空搜索后焦点回到搜索框',
/query = ''; render\(\)\s*\n\s*if \(searchEl\)/.test(src))
// ---- 11) v1.13.1 变量栏:去 i 按钮 + 行间分割线(位置 2) ----
ok('v1.13.1 源码不再创建 i 圆按钮(iwb-plp-vi / iBtn 全清)',
!/\biwb-plp-vi\b/.test(src) && !/iBtn/.test(src))
ok('v1.13.1 样式表不再有 .iwb-plp-vi 规则(词边界防误伤 vitem/vin)',
!/\biwb-plp-vi\b/.test(css))
ok('v1.13.1 变量行只挂 caret / 名称 / 摘要三项(整行点击是唯一入口)',
/row\.appendChild\(caret\); row\.appendChild\(title\); row\.appendChild\(sum\)\s*$/m.test(src))
// 依据 design-tokens.md §3.11:容器内行间用 --iwb-set-divider,首行不画线。
ok('v1.13.1 分割线用 --iwb-set-divider(1px 实线,暗色自动跟随)',
/\.iwb-plp-vitem \+ \.iwb-plp-vitem\{[^}]*border-top:var\(--iwb-bw, 1px\) solid var\(--iwb-set-divider/.test(css))
ok('v1.13.1 该 token 只在设置弹窗作用域定义 ⇒ 按同公式就地兜底,不掉到全强度边框',
/var\(--iwb-set-divider, color-mix\(in srgb, var\(--iwb-border\) 55%, transparent\)\)/.test(css) &&
!/var\(--iwb-set-divider, var\(--iwb-plugin-border/.test(css))
ok('v1.13.1 用相邻兄弟选择器 ⇒ 首行不画线、末行之后也没有线',
/\.iwb-plp-vitem \+ \.iwb-plp-vitem\{/.test(css) &&
!/\.iwb-plp-vitem:last-child\{[^}]*border-bottom/.test(css))
ok('v1.13.1 旧的每行虚线边框已删除',
!/\.iwb-plp-vitem\{[^}]*border-bottom:1px dashed/.test(css))
ok('v1.13.1 dialog 作用域不再用 border:0 盖掉行间线',
!/\.iwb-plp-dialog \.iwb-plp-vitem\{[^}]*border:0/.test(css))
ok('v1.13.1 标题下 / 展开字段前都不另画线(一屏只留一层线)',
!/\.iwb-plp-vhead\{[^}]*border/.test(css) &&
!/\.iwb-plp-vfield\{[^}]*border-top/.test(css))
ok('v1.13.1 去掉 i 后补整行 hover 反馈(接替「可点击」提示)',
/\.iwb-plp-dialog \.iwb-plp-vrow2:hover\{[^}]*var\(--iwb-plugin-hover\)/.test(css))
ok('v1.13.1 展开态 caret 用主色呼应状态',
/\.iwb-plp-vitem\.is-open \.iwb-plp-vcaret\{[^}]*var\(--iwb-plp-accent/.test(css))
ok('v1.13.1 新增尺寸全走 token(无裸 px/font-size)',
/\.iwb-plp-vitem \+ \.iwb-plp-vitem\{[^}]*padding-top:var\(--iwb-space-8\)/.test(css) &&
/\.iwb-plp-dialog \.iwb-plp-vrow2\{padding:0 var\(--iwb-space-4\)/.test(css))
console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过')
if (failed) process.exitCode = 1
+164
View File
@@ -0,0 +1,164 @@
// 搜索框中文输入法回归验证(v1.12.2 起)
// 为什么单独一个脚本:宿主 CI 里没有 playwright,跑不进 harness 门禁;但改搜索框时值得手动跑一次。
// 依赖宿主仓的 playwright:image-workbench-desktop/node_modules/playwright。
// 用法:node promptlib/tools/plp-search-ime-check.mjs
// PLP_SRC=/path/to/other/index.js node promptlib/tools/plp-search-ime-check.mjs # 对照旧版
// 覆盖:组合态中搜索框不被重建 / 不按拼音过滤 / 光标不跳末尾 / 上屏后过滤生效
// CDP Input.imeSetComposition 走真实输入法通道
// 验证 promptlib 搜索框:中文输入法组合态不再被打断(v1.12.2)
// 做法:真实 Chromium 加载插件源码 + 最小宿主 stub,挂载面板后
// ① 模拟 compositionstart → input(拼音) → compositionend(中文)
// ② 用 CDP Input.imeSetComposition 走真实输入法通道
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
// playwright 装在宿主仓(插件仓没有 node_modules);按本级目录推,别写死绝对路径
const HERE = path.dirname(fileURLToPath(import.meta.url))
const PW = pathToFileURL(path.resolve(HERE, '..', '..', '..', 'image-workbench-desktop', 'node_modules', 'playwright', 'index.mjs')).href
const { chromium } = await import(PW)
const SRC = process.env.PLP_SRC || path.resolve(HERE, '..', 'src', 'index.js')
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 900, height: 700 } })
const errors = []
page.on('pageerror', (e) => errors.push(String(e)))
await page.setContent('<!doctype html><html><body style="margin:0"><div id="host"></div></body></html>')
// 宿主 stub:捕获 register → 拿到 factory
await page.evaluate(() => {
window.IWBPluginHost = { register: (meta, factory) => { window.__reg = { meta, factory } } }
})
await page.addScriptTag({ path: SRC })
const mountInfo = await page.evaluate(() => {
const prompts = [
{ id: 'a', name: '水光肌底妆', text: '水光 底妆 提亮 通透', group: '美妆' },
{ id: 'b', name: '复古胶片', text: '胶片 颗粒 暖调 怀旧', group: '风格' },
{ id: 'c', name: '水果静物', text: '水果 静物 清新', group: '美妆' },
{ id: 'd', name: '水波纹背景', text: '水波 纹理 背景', group: '风格' },
]
const groups = [{ id: '美妆', name: '美妆' }, { id: '风格', name: '风格' }]
const data = { schemaVersion: 3, prompts, groups }
const ctx = {
data: {
read: async () => data,
write: async () => ({ ok: true }),
set: async () => ({ ok: true }),
get: async () => null,
},
promptlib: {
list: async () => ({ prompts, groups }),
save: async () => ({ ok: true }),
insert: async () => ({ ok: true }),
notify: () => {},
onChanged: () => () => {},
filePut: async () => ({ ok: true }),
fileGet: async () => '',
fileList: async () => [],
fileRemove: async () => ({ ok: true }),
fileStat: async () => ({ count: 0, bytes: 0 }),
},
files: {
put: async () => ({ ok: true }),
get: async () => '',
list: async () => [],
remove: async () => ({ ok: true }),
stat: async () => ({ count: 0, bytes: 0 }),
},
storage: { set: () => {}, get: () => null },
ui: { registerPanel: (p) => { window.__panel = p }, toast: () => {} },
}
window.__reg.factory(ctx)
const host = document.getElementById('host')
window.__dispose = window.__panel.mount(host)
return { meta: window.__reg.meta.version, hasPanel: !!window.__panel }
})
console.log('插件版本', mountInfo.meta, '面板已注册', mountInfo.hasPanel)
await page.waitForTimeout(600)
const countCards = () => page.evaluate(() => document.querySelectorAll('.iwb-plp-card').length)
const before = await countCards()
console.log('初始卡片数', before)
// ---- ① 合成事件:组合态期间搜索框不能被重建、列表不能按拼音过滤 ----
const synth = await page.evaluate(async () => {
const host = document.getElementById('host')
const el = host.querySelector('input.iwb-grow')
el.__mark = 'same-node'
el.focus()
el.setSelectionRange(2, 2)
const fire = (type, extra) => el.dispatchEvent(new (type === 'input' ? InputEvent : CompositionEvent)(type, Object.assign({ bubbles: true }, extra || {})))
fire('compositionstart', { data: '' })
// 拼音逐个上屏:真实输入法每敲一个字母都会派发 isComposing=true 的 input
el.value = '水'
fire('input', { isComposing: true, data: 'shui' })
el.value = '水s'
fire('input', { isComposing: true, data: 'shuis' })
await new Promise((r) => setTimeout(r, 250)) // 超过 120ms 防抖窗口
const during = {
sameNode: host.querySelector('input.iwb-grow') === el,
connected: el.isConnected,
mark: el.__mark,
cards: document.querySelectorAll('.iwb-plp-card').length,
selStart: el.selectionStart,
}
// 上屏
el.value = '水'
el.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '水' }))
await new Promise((r) => setTimeout(r, 300))
const after = {
sameNode: host.querySelector('input.iwb-grow') === el,
value: el.value,
cards: document.querySelectorAll('.iwb-plp-card').length,
names: Array.from(document.querySelectorAll('.iwb-plp-t')).map((n) => n.textContent),
}
return { during, after }
})
console.log('组合态中 :', JSON.stringify(synth.during))
console.log('上屏之后 :', JSON.stringify(synth.after))
// ---- ② CDP 真实输入法通道 ----
const cdp = await page.context().newCDPSession(page)
await page.evaluate(() => { const el = document.querySelector('#host input.iwb-grow'); el.value = ''; el.focus() })
await cdp.send('Input.imeSetComposition', { text: 'shui', selectionStart: 4, selectionEnd: 4 })
await page.waitForTimeout(120)
const composingState = await page.evaluate(() => document.querySelector('#host input.iwb-grow').value)
await cdp.send('Input.insertText', { text: '水' })
await page.waitForTimeout(300)
const imeState = await page.evaluate(() => ({
value: document.querySelector('#host input.iwb-grow').value,
cards: document.querySelectorAll('.iwb-plp-card').length,
names: Array.from(document.querySelectorAll('.iwb-plp-t')).map((n) => n.textContent),
}))
console.log('imeSetComposition 后 value =', JSON.stringify(composingState))
console.log('真实输入法提交后 :', JSON.stringify(imeState))
// ---- 判定 ----
const checks = [
['组合态中搜索框未被重建(同一节点)', synth.during.sameNode === true],
['组合态中搜索框仍在文档里(没被移除)', synth.during.connected === true],
['组合态中保留自定义属性(未被克隆替换)', synth.during.mark === 'same-node'],
['组合态中不按拼音过滤(卡片数不变)', synth.during.cards === before],
['组合态中光标位置不被打到末尾', synth.during.selStart === 2],
['上屏后搜索框仍是同一节点', synth.after.sameNode === true],
['上屏后搜索框值 = 水', synth.after.value === '水'],
['上屏后过滤到 3 条含水的结果', synth.after.cards === 3],
['真实输入法:组合态拼音留在框内', composingState === 'shui'],
['真实输入法:提交后可搜到 3 条', imeState.cards === 3],
]
let failed = 0
for (const [name, okv] of checks) { if (!okv) failed++; console.log((okv ? '✓ ' : '✗ ') + name) }
if (errors.length) { console.log('页面异常:', errors.slice(0, 3)) }
console.log(failed ? `✗ ${failed} 项失败` : '✓ 全部通过')
await page.screenshot({ path: '/tmp/plp-search.png' })
await browser.close()
process.exit(failed ? 1 : 0)
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more