Compare commits

...
Author SHA1 Message Date
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
87 changed files with 35437 additions and 21 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
+39 -8
View File
@@ -28,9 +28,10 @@ cp /绝对路径/<插件目录>/src/index.js /tmp/plugin-<id>.js
node scripts/plugins-publish.mjs /tmp/plugin-<id>.js --upload --version <id>=<ver>
```
- **必须用 `plugins-publish.mjs`**:它算 **SHA-256(SRI integrity)** 写进 `plugins/index.json`;宿主用 `<script integrity>` 强制校验,
**缺失/不符即拒载(fail-closed)**。
⚠️ **不要用 `plugins-publish.sh`**:它写清单时不产 `integrity`,会被 fail-closed 拒载。
- **发布器必须写出 `SHA-256`(SRI integrity)到 `plugins/index.json`**;宿主用 `<script integrity>` 强制校验,
**缺失/不符即拒载(fail-closed)** —— 这是硬要求。
- 推荐 `plugins-publish.mjs`(默认 dry-run、`--upload` 才写 KV;输入文件名须为 `plugin-<id>.js`)。
`plugins-publish.sh`(`<id> <file> [version]`)**现已同样产出 `integrity`**,可放心使用。
- A2 Function 已在**测试站与正式站**上线;本地发布后刷新浏览器即生效。
### 路径 B:构建期并入 `src/plugin-<id>.js`
@@ -48,7 +49,7 @@ npm run deploy:test # 发到测试站
## 校验(本地 + CI)
```bash
npm run validate # 校验每个插件的 ibwPlugin 契约、entry 语法、entry 内 manifest 与契约是否一致
npm run validate # 契约:ibwPlugin 字段、entry 语法、entry 内 manifest(id/apiVersion/version/name/capabilities)与 package.json 一致
```
`.github/workflows/ci.yml` 在 push / PR 时跑同一条命令(只读源码,不需要网络或依赖)。
@@ -93,13 +94,43 @@ npm run validate # 校验每个插件的 ibwPlugin 契约、entry 语法、e
## 目录约定
```
template/ # 最小可运行插件(复制它开始)
xianyi-cutout/ # 真实插件:鲜艺抠图(A2 运行时插件,已发布到宿主 KV)
template/ # 最小可运行插件(复制它开始;手写单文件)
xianyi-cutout/ # 真实插件:鲜艺抠图(A2 运行时插件,已发布到宿主 KV;手写单文件)
white-bg-800/ # 真实插件:白底图(移植自 iwb-cutout-extension;已发布到宿主 KV;手写单文件)
image-annotate/ # 真实插件:标注 / 修图(编辑器移植自 iwb-plaus;需要构建,见下节)
batch-export/ # 真实插件:批量出图(panels 面板 + 串行队列 + 可选抠图 + 双版本 + ZIP + 行内单张下载;手写单文件)
scripts/ # validate.mjs(CI 必跑)+ build-plugin.mjs(仅需构建的插件用)
```
> 顶层目录**没有 `package.json` 就不会被当成插件**(`scripts/validate.mjs` 的发现规则),
> 因此将来两个以上插件共用的源码可以放顶层 `shared/`,不需要改校验器或 CI。
## 需要构建的插件(复杂插件)
编辑器/多文件类插件用 ESM 写,构建成单文件 IIFE 产物:
```
<插件>/
plugin/entry.js # 打包入口(import 编辑器 + 胶水,导出工厂到全局)
plugin/manifest.banner.js # 手写 manifest(单引号,原样放产物最前)
plugin/manifest.footer.js # 手写注册 IIFE(原样放产物最后)
plugin/editor/…、*.css # 源码;CSS 以 text loader 内联
src/index.js # 构建产物(提交进仓,CI 只校验不构建)
```
```bash
npm install # esbuild 是 devDependency,只有构建时需要
npm run build -- image-annotate # 含产物自检:首个 id / register / version / 无 eval
npm run validate
```
**为什么分三段拼接**:esbuild 会把字符串统一改写成双引号,而校验器只认单引号 manifest;
且校验器用「文件里第一个 id 字面量」判定插件 id,manifest 必须排在 bundle 之前。
`version` 只有一处真源 —— 构建时用 `package.json` 的 `version` 替换 banner 里的 `__PLUGIN_VERSION__`。
每个插件目录含 `src/index.js`(IIFE 产物)与 `package.json`(`version` + `ibwPlugin.entry` 供人读,
`version` 用于来源追溯)。合入/发布时把 `src/index.js` 的绝对路径传给对应脚本:路径 A 传
`plugins-publish.sh` 的第二参数,路径 B 传 `plugins-sync.sh` 的第三参数(默认 `dist/plugin.js`)。
`version` 用于来源追溯)。合入/发布时把 `src/index.js` 交给对应脚本:路径 A 交给发布器
(`.mjs` 需先拷成 `plugin-<id>.js` 再传文件;`.sh` 直接传 `<id> <file>`),路径 B 传 `plugins-sync.sh` 的第三参数(默认 `dist/plugin.js`)。
## 运行时机制(插件怎么跑 / 为什么发布更新不用宿主)
+49
View File
@@ -0,0 +1,49 @@
# AI 对话(ai-chat)
浮窗式 AI 对话插件:直接连你本机的 **[Magpie](https://github.com/yetone/magpie)**(OpenAI 兼容网关,默认 `http://127.0.0.1:3425/v1`),在画布上方开聊。不嵌网页、不走后端代理(Pages Function 跑在边缘、连不到本机 `127.0.0.1`,故插件直连)。
## 能力
- **模型动态拉取**:打开即从 `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 端点。改端口需同步放宽宿主 `_headers` 的 `connect-src`。 |
| API Key | `magpie` | Magpie 走 loopback,任意值均可(只认本机)。 |
## 前置
1. 本机跑起 Magpie,并配好你想用的 provider(详见 Magpie 文档)。
2. 宿主 `_headers` 的 `connect-src` 已放行 `http://127.0.0.1:3425` 与 `http://localhost:3425`(本仓已加)。
## 用法
- 启用插件 → 右下角出现「AI」悬浮按钮,同时对话窗自动展开在画布上方。
- 先点模型栏选一个模型(红色状态点变绿 = 已连上 Magpie)。
- 输入消息,Enter 发送 / Shift+Enter 换行。
- 要聊图:先在画布选中一个节点,模型支持视觉时点「附带当前选中图」。
- 收到回复后点「写回提示词节点」,会在画布上(贴近选中节点处)新建一个提示词节点。
## 契约
- `capabilities: ['canvas', 'canvasWrite']`
- 无沙箱(可信代码),与画布同页同源,可发网络请求。
## 发布
手写单文件(IIFE),`src/index.js` 即产物,无需构建:
```bash
# 路径 A:运行时发布到 KV(推荐)
cp src/index.js /tmp/plugin-ai-chat.js
node ../../image-workbench-web/scripts/plugins-publish.mjs /tmp/plugin-ai-chat.js --upload --version ai-chat=1.0.0
# 注:实际发布需把全部插件一并传入,保持 index.json 完整(见宿主发布流程)
```
+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)
+149
View File
@@ -0,0 +1,149 @@
# 批量出图(插件)
在资源中心新增一个「批量出图」面板:勾选画布上的 `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'`,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 # 测试站
IWB_BASE_URL=https://iwb.maqiart.eu.org node batch-export/tools/e2e-site.mjs # 正式站
```
覆盖:真实 KV 加载 + SRI + 资源中心 tab 出现 + 面板挂载 + 列表 2 行 +
**勾选框与文字同行(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)** +
队列跑通 + 下载 ZIP + python3 校验 4 条目 / CRC / PNG·JPEG magic / UTF-8 名。
## 发布
```bash
cd /Users/qiqi/open/github/image-workbench-web
cp /Users/qiqi/open/github/iwb-plugins/batch-export/src/index.js /tmp/plugin-batch-export.js
# ⚠️ 必须把所有插件文件一起传入:发布器用「传入的文件」重建 plugins/index.json,不做合并
cp /Users/qiqi/open/github/iwb-plugins/white-bg-800/src/index.js /tmp/plugin-white-bg-800.js
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
cp /Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js /tmp/plugin-image-annotate.js
cp /Users/qiqi/open/github/iwb-plugins/blank-canvas/src/index.js /tmp/plugin-blank-canvas.js
node scripts/plugins-publish.mjs /tmp/plugin-batch-export.js /tmp/plugin-white-bg-800.js \
/tmp/plugin-xianyi-cutout.js /tmp/plugin-image-annotate.js /tmp/plugin-blank-canvas.js \
--version batch-export=1.1.0 # 默认 dry-run,检查 diff 后再加 --upload
```
发布后刷新即生效;新插件在「设置 → 插件」里**默认未启用**,需手动勾选。
⚠️ `--upload` 时脚本按清单顺序逐个 put,最后才 put `index.json`。代理抖动会让它在半路 `fetch failed` 退出,
此时**清单可能已经指向还没上传成功的文件**(1.0.1 发布时踩过)⇒ 线上 fail-closed 直接不加载。
稳妥做法:先把插件字节 put 上去,`curl` 确认 200 且大小对,再 put `index.json`。
## 版本记录
- **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.0",
"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)
+42
View File
@@ -0,0 +1,42 @@
# 空白画布(插件)
给**空白的参考图节点**填入一张指定尺寸的**纯白图片**,作为插图 / 标注的起点。
典型用途:新建参考图节点(还没有图)→ 直接铺一张 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 字符阈值),属正常路径。
## 发布
与其它插件一致:先 `npm run validate`,再由宿主仓的 `scripts/plugins-publish.mjs` 以哈希名入库。
⚠️ 发布时**必须把所有插件文件一起传入**(发布器用传入的文件重建清单,不做合并)。
+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)
+371
View File
@@ -0,0 +1,371 @@
# 标注 / 修图(插件)
在宿主里选中一个带图的节点,打开**全屏单张图片编辑器**:画笔 / 矩形 / 箭头 / 文字 / 橡皮 / 吸管 / 抓手 / 裁剪,
外加 **v1.1 的框选与套索选区**(复制/剪切到新层、清除、填充、反选、羽化、选区旁浮动操作条)、
图层(多选 / 向下合并 / 合并可见 / 排序 / 显隐 / 锁定)、撤销重做、缩放平移;一次只处理一张、一次只输出一个结果(覆盖原节点 / 新建节点 / 下载)。
编辑器**最初移植自** `iwb-plaus` 仓库的 `iwb-cutout-extension`(纯 Canvas 2D、零第三方库):
- 源:`/Users/qiqi/open/github/iwb-plaus/iwb-cutout-extension/src/editor/`(11 个模块)+ `src/shared/{image-math,layer-logic}.js`
- 差异:只有「宿主胶水」(`plugin/glue.js`、`plugin/entry.js`)是新写的;编辑器模块与样式最初逐字移植 —— **例外见下几节**(`loadImage` 的 CSP 适配、v1.0.5 的图层顺序修复、v1.1 的独立演进)。
- ⚠️ **v1.1 起正式分叉、独立演进**:新增命令层 / 选区 / 输出管道 / 便利版 UI 与三张独立交互层,
并重写了历史快照模型(支持图层增删的可撤销恢复)。**不要再整目录回灌上游**,会冲掉 1.0.5 与 1.1.0 的全部修复。
目标与分期见 `docs/PS_LITE_ROADMAP.md`。
- 原扩展的 CSS 由 `manifest.json` 的 `content_scripts.css` 注入;插件没有 manifest,改为构建时以字符串内联、运行时注入 `<style>`。
> ⚠️ **回灌上游前先看这里**:v1.0.5 改了多个编辑器模块(`objects.js` / `layers.js` / `events.js` / `tools.js` / `placement.js` / `crop.js` / `history.js` / `index.js` / `viewport.js` 的相邻逻辑、`editor.css`),修的是上游的图层 z 序缺陷。整目录覆盖会把修复冲掉。
### 移植改动之一:CSP 适配
`plugin/editor/dom.js` 的 `loadImage()`:上游用 `fetch(dataURL)` 把 dataURL 转成 blob URL(避免 `img.src` 在整个编辑会话里
持有几十 MB 的 base64 字符串)。但宿主 CSP 是 `connect-src 'self' https: …`,**不含 `data:`** ⇒ `fetch(data:)` 必被浏览器拦,
每次打开编辑器都产生一次 CSP 违规(上游的 `catch` 回退让它「还能用」,所以功能看起来正常、只在控制台报错)。
现改为**纯本地解码**(`atob` → `Uint8Array` → `Blob` → blob URL),与上游行为一致(同样拿到 blob URL),且不依赖 CSP/网络。
> 这类问题**只有带 CSP 的真站能测出来**(无 CSP 的 mock 页永远绿)。真实站点用例见 `image-annotate/tools/e2e-site.mjs`。
### v1.1:选区、便利版 UI、单张输出
**范围裁定**:只做单张,不做多图队列 / 批量导出 / 批量改名 / 批量下载;UI 以「顺手」为第一目标,不做菜单栏。
已拍板:`Delete` 只作用当前图层;「还原原图」=清空标注全部还原(删所有非原图层、清绘制、复位变换)且可 Ctrl+Z;
`≤500KB` 做成可切换预设;选区浮动操作条**先上线,等实际体验后再裁定**保留/调整/移除(它是纯视图,随时可换)。
- 新模块:`commands.js`(统一 `execute(label, mutator)` + 命令注册表 + toast)、`selection.js`(`Path2D` 选区 / bbox 局部软掩膜 / 像素命令)、
`floating.js`(选区旁浮动条 + 右键菜单定位)、`export.js`(格式 / 背景 / 800×800 / ≤500KB 降质 + `ctx.settings` 记忆)。
- 地基:`history.js` 快照升级为「完整图层集合」,图层增删也能撤销;三张交互 canvas 分离
(选中框 / 蚂蚁线 / 笔刷环互不擦除),尺寸与坐标基准由 `viewport.js` 统一同步。
- 交互:精简顶栏(撤销重做 + 还原原图 + 更多 ▾ + 常驻输出)、就地选项栏、状态栏、toast、
侧栏一键收起、粘贴图片一步落层。数字键 1–0 保留,新增 `M/L/V/B/E/T/C` 与
`Ctrl+A / J / X / D`、`Ctrl+Shift+I`、`Esc`、`Delete`。浮动条 / 右键 / 快捷键三入口共用同一命令层。
- 输出:一次一个结果;「透明 PNG / 白底 JPG」是单选开关,不默认产两个文件;预设存 `ctx.settings`。
- **v1.1.2**:JPG 没有 alpha 通道,选 JPG 时背景自动收敛为白底并禁用「透明」按钮,
摘要/状态与文件三者一致(此前会显示透明却输出白底)。
- **v1.1.2**:「电商方图」预设补齐 **边长**(750/800/1000/1200)与 **体积上限**(不限/300/500/800KB)两个控件,
两者只在电商预设下可见;`≤KB` 也只在该预设下参与降质 —— 切回「原尺寸」会把 `maxKB` 写回 0,
不会因为宿主里残留的 `exportMaxKB` 让限制「复活」或让原尺寸偷偷降质。
- **v1.1.2**:下载后与「还原原图(尺寸复位)」后都会走统一重绘,摘要里的尺寸和「上次输出 …KB」即时更新。
### v1.2:非破坏性裁剪 + 工具参数解耦
- **裁剪可撤销**:`confirmCrop()` 不再合成成一张图、也不再把 `S.history` 清零,改为
① 先 `saveSnapshot('裁剪')`;② **逐图层**把可见区域搬进新尺寸画布(图层名/透明度/锁定全保留);
③ `viewport.js#resizeWorkspace()` 只换尺寸不重建图层。撤销时 `restoreState()` 会先把画布尺寸
复位到快照里的 `imgW/imgH` 再回填像素,所以 Ctrl+Z / Ctrl+Shift+Z 能来回切。
- **工具参数解耦**:新增 `S.shapeLineWidth`(矩形/圆形/箭头/钢笔线宽)与 `S.textSize`(文字字号),
不再借用 `S.brushSize` —— 以前「调细画笔」会顺手改掉所有形状描边、文字大小也跟画笔联动。
- **就地选项栏**:每个工具在顶栏下方都有自己最常用的 2–4 个参数
(画笔/橡皮:大小·硬度·透明;矩形/圆形:线宽·描边/实心;箭头/钢笔:线宽;文字:字号;
框选:形状·羽化;套索:羽化)。控件直接写回 `S`,与右侧参数面板双向同步;
选中形状/文字时调线宽或字号会同步改选中对象,松手才记一步历史。
- **打断输入的修复**:`renderAll()` 不再整块重建选项栏(改为 `syncOptionBar()` 只更新值),
拖滑杆和输数字不会被重绘打断;`isTyping()` 只对文字输入框为真,参数数字框里按
`Ctrl+A / Ctrl+J / Delete / Esc` 不再被当成「正在打字」吞掉。
## v1.2.1
- **默认不预建「画笔标注」层**(用户裁定):打开编辑器只有「原图」1 层。
画笔起笔或对锁定原图执行「填充」时,`ensureWritableLayer()` 自动落一个「标注 N」层并激活
—— 建层发生在 `saveSnapshot()` 之前,所以首笔 Ctrl+Z 连自动建的层一起撤掉,不留空层。
「还原原图」后同样只剩原图单层。Delete/剪切保持提示不自动建层(它们是「减内容」操作)。
- **侧栏去重**:移除硬度/透明两条滑杆(与就地选项栏画笔/橡皮态完全重复);
侧栏保留调色板全量 + 笔刷大小(滑杆/数字/快捷点)+ 缩放行。
- 测试:`node image-annotate/tools/harness.mjs`(合成宿主,发布前,79 项);
`node image-annotate/tools/e2e-site.mjs`(真站 CSP/SRI,发布后)。
## v1.2.2
- **变换手柄只在「选择」工具出现**:画笔/橡皮等绘制工具下不再画选中层的虚线框与 8 个手柄(用户裁定)。
- **面板高亮跟随绘制目标**:画笔/橡皮落笔时 `selectedLayerId` 同步为绘制目标层,
杜绝「面板没选中这层却能画上去」的逻辑矛盾。
- **选项栏快捷值圆点**:画笔/橡皮有 7 个大小快捷点(2/4/8/12/16/24/32),
矩形/圆形/箭头/钢笔有 7 个线宽快捷点(1/2/3/6/10/16/24),点击即时生效并与侧栏滑杆同步。
- **侧栏「实心」按钮移除**:矩形/圆形的描边/实心切换只在选项栏(一处真源)。
- **裁剪参数迁入选项栏**:比例/尺寸约束、尺寸摘要、确认/取消按钮全部在裁剪工具的选项栏里,
画布下方浮窗删除;**Enter 确认、Esc 取消**(按钮保留)。旧直连绑定改为选项栏委托,重渲染不丢事件。
## v1.3:色板进工具栏 + 矢量/文字工具只负责「创建」
两条都是用户裁定(2026-11-05):色板要顺手、矢量工具要能叠着画。
### 色板搬进工具栏弹层
侧栏的 `.iwb-editor-color-panel` 整块删除,工具栏最左新增「当前色圆点」(`data-action="toggleColorPop"`)。
点开是一个横排弹层:`[SV 180×104 + 色相条] | [吸管 + #hex] | [6×2 推荐色]`。
- **弹层必须挂在 `.iwb-editor-modal` 下**,不能塞进 `.iwb-editor-tools`:工具栏是
`overflow-x: auto; overflow-y: hidden`,`.iwb-editor-canvas-wrap` 是 `overflow: clip`,
放里面会被直接裁掉(踩过)。定位由 `positionColorPop()` 用「按钮矩形 − modal 矩形」现算,
上方放不下翻到下方,左右夹在 modal 内 —— 这样宿主页面有 transform 也不会错位。
- 关闭:再点色点 / 点外面(document 捕获阶段,画布 `preventDefault` 让冒泡收不到)/ Esc
(`closeColorPop()` 排在 Esc 链路最前,是真正的「先收浮层」)。
- 侧栏此时只剩缩放。**下一步可选**:把缩放搬进状态栏、整个删掉右侧栏,画布能多 220px
(要连带改 `panels-collapsed` 与 `computeFit`,本轮没做)。v1.4 在侧栏补了「快速效果」,
这条「整个删掉」的选项作废,除非把效果挪到别处。
两个连带修的旧 bug(都不是这次才存在,是搬过来后变明显):
1. **拖调色器会爆撤销栈**:`applyColorChange` 每改一次颜色都 `saveSnapshot()`,SV 拖一下
就是几百张全画质 `ImageData`。现在 pointerdown 拍一次(此时颜色还没变),拖动期间走
`applyColorChange(color, { skipHistory: true })`。测试断言「历史只 +1」。
2. **色相状态会过期**:取色器的 h/s/v 是 `bindColorPanel` 的闭包变量,而推荐色/hex/吸管
只改 `S.color`。以前点绿色再拖 SV 会跳回红色。现在每次 `pointerdown` 从 `S.color`
重新同步一次;灰阶(`d=0`,如 `#000`)反推不出色相,沿用旧色相。
### 矢量/文字工具不再具备选择功能
`onShapeMouseDown` 以前先 `hitShapeHandle`(拖手柄)、再 `hitShapeLayer` 并拖动同类型形状,
只有点空白才起笔 —— 于是「在已有矩形上面按住」永远被当成拖旧矩形,没法叠着画。
现在规则统一:**选中只属于 V(选择工具)与临时吸管**。
- `onShapeMouseDown` / `onTextMouseDown` 只负责起笔,不再命中已有对象;
- `setTool` / `exitPicker` 的 `keepSel` 只剩 `select | picker`,切到 矩形/圆形/箭头/钢笔/文字
就清掉三个选中 id;
- `onShapeDrawUp`、`commitPenPath` 不再自动选中新对象(否则矢量工具下会冒出选中框与手柄,
但手柄点不动,自相矛盾)。
连带效果:画完图形不会自动选中,选项栏里的线宽/描边是「下一个图形的默认值」;
要改刚画的就按 V 点它。钢笔的节点编辑入口保留双击(V 或 P 下都能进)。
## v1.4:侧栏「快速效果」
用户 2026-11-05 提出「侧栏加个快速效果栏,先要反白」,并授权补齐其它常用效果。
侧栏顶部是一块 3×2 的效果面板(`plugin/editor/effects.js`),底部仍是缩放条。
**「反白」= 反相(Invert),不是排版意义的黑底白字标签。** 白底变黑底、黑字变白字,
用于快速出一版深色图。如果要做「文字反白标签」,那是标注样式,属于另一个入口。
| 键 | 名称 | 实现 |
| --- | --- | --- |
| `invert` | 反白 | `filter: invert(1)` |
| `gray` | 灰度 | `filter: grayscale(1)` |
| `boost` | 增强 | `brightness(1.12) contrast(1.1) saturate(1.06)` |
| `contrast` | 高对比 | `grayscale(1) contrast(2.4)` |
| `soft` | 柔化 | `blur(半径)`,半径 = 短边/500 并夹在 0.8~8px |
| `mosaic` | 马赛克 | 缩到 1/block 再关平滑放大,block = 短边/60(最小 6px) |
实现上的三条约束:
1. **目标只有一个:当前位图图层。** 侧栏标题右侧的标签实时显示层名(`renderLayerPanel`
顺带刷新)。无活跃层时退回「原图」。矢量层(文字/形状)不参与 —— 反白一张图不应该
顺手改掉标注颜色。
2. **不碰图层几何,也不改 `image`。** 全部在图层自己的 canvas 上做重绘;
`ctx.setTransform(1,0,0,1,0,0)` + `globalCompositeOperation = 'copy'`,
否则会带上视图变换、或者留下旧内容。
3. **撤销靠快照。** `applyQuickEffect` 先 `saveSnapshot()`。`base` 与画笔层走
`restorePath = 'pixels'`,`putImageData` 直接回退;**导入图片层**走 `image/sourceCanvas`
重绘,原地改像素会被下一次重绘冲掉,所以先按 PS「栅格化」的做法拷一个普通位图副本
(名字 `xxx · 效果`,z 取「原层 → 上一层」的中点),原层 `visible = false` 而不删除。
Ctrl+Z 时副本被快照机制移除、原层恢复可见(`layerOrder` 里存了 visible),实测来回都干净。
未做的:**有选区时只作用于选区**。当前一律整层处理,弹层提示写的也是「作用于当前层」。
## v1.5:画完自动回 V,编辑统一走 V
用户 2026-11-05 测试后提出:**图形/文字画完应该自动退出当前工具、切到 V**,否则每次画完还要手动按一次 V 才能调。
同一轮追加裁定:**钢笔的节点编辑也只用 V 双击**,P 下不再给入口。
### 画完即回 V 并选中
| 工具 | 落成点 | 收尾 |
| --- | --- | --- |
| 矩形 / 圆形 / 箭头 | `onShapeDrawUp` | 切 V + 选中新形状 |
| 钢笔 | `commitPenPath` | 同上 |
| 文字 | `commitTextInput` | 切 V + 选中新文字 |
统一走 `finishCreateTool()`(events.js):**先 `setTool('select')` 再 `selectUnit`** —— 反过来
会被 `setTool` 里「非 V/吸管就清选中」的规则立刻清掉。尺寸不达标(点一下没拉出形状)不切,
路径点数不足不切,空文字不切。
连带代价:连续画多个同类图形,每次都要重新点工具(用户选择「画完即退出」的必然结果)。
文字这条要绕开 `setTool` 第一行的 `commitTextInput()`(同步调用会自我递归),所以用
`queueMicrotask` 延后一个微任务再切;延后期间若又弹出了新的输入框(在 T 下连续点着输入),
就放弃这次切换,不抢工具。
### 双击判定改成自己算
`dblclick` 在画布上**不可靠**:单击选中会重绘矢量画布,浏览器有时干脆不派发 `dblclick`
(无头环境 100% 复现,`page.mouse.dblclick` 也拿不到事件),此前的「V 双击钢笔进节点编辑」
其实一直是坏的,只是没有用例覆盖。
现在改为 `isDoubleClick()`:同一位置 **380ms 内两次 mousedown**,命中后清空记录(三连击不重复触发)。
切工具时清 `S.lastClick`,避免跨工具拿上一次点击配对。
双击语义(只属于 V,`onCanvasDoubleClick`):
1. 正在编辑钢笔 → 双击节点 = 删节点(点数不足则删整个形状);
2. 未编辑 → 双击钢笔形状 = 进节点编辑;
3. 双击文字 = 改内容。
P 下双击 = 结束当前路径(`commitPenPath`),不再进节点编辑。
另外 `setTool` 里 `penEditId` 的清理条件从「非 select 且非 pen」收紧为「非 select」——
从 V 带着编辑态切到 P 会留下「钢笔下能拖节点但点不动」的半状态。
## v1.6:笔刷环即时反馈 + 图层合并
用户 2026-11-05 提出两件事:按 `[` / `]` 调笔刷大小时圆环不跟着变(要动一下鼠标才刷新);
图层需要像 PS 一样支持「选多层合并」和「合并已有图层」。
### 笔刷环不再等 mousemove
`drawToolRing` 原先只在 `mousemove` 里调用,所以键盘改大小后环还是旧尺寸。
现在把「最后一次悬停点」记进 `S.hoverPos`,并导出 `refreshBrushRing()`:大小变化
(`[` / `]`、选项栏滑杆 / 数字 / 快捷点、图层面板线宽)与工具切换都按这个点立刻重画。
鼠标离开画布时清空 `hoverPos`,避免把环画到旧位置。
### 图层合并(PS 语义)
| 操作 | 入口 | 行为 |
| --- | --- | --- |
| 向下合并 | `Ctrl/⌘+E`、标题栏「合并」按钮 | 当前层合进下一层,结果继承下层名字与位置 |
| 合并选中 | ⌘/Ctrl 点击图层多选后同上 | 合并多选集合;隐藏层跳过并保留 |
| 合并可见 | `Ctrl/⌘+Shift+E`、标题栏第二个按钮 | 所有可见层合成一层,隐藏层不动 |
多选:图层项上 **⌘(macOS)/ Ctrl(Windows)点击** 加入或移出集合,青色高亮与单选的橙色侧条区分;
第一次加选会把当前单选层一起纳入。点击画布、切换单选、撤销都会退出多选。
实现要点(`layers.js` 的 `mergeUnits`):
- **有「原图」参与时写回 base 本身**:base 的快照走 `pixels` 路径,撤销能逐像素恢复,
且「还原原图」始终有锚点。
- **否则新建一张普通位图层承载**:导入图片层走 `image` 重绘路径,原地改像素后再清掉 `image`,
撤销时 `restorePath` 会按「像素」去读一份根本没拍的快照(history.js 注释里记过这个坑)。
- 合成规则与导出 / 吸管共用(同一套 `layerUnits()` z 序与 `opacity` alpha),
「合并后看到的」等于「导出得到的」。
- 文字 / 形状 / 钢笔会被直接栅格化进结果层(PS 合并矢量层也是这个结果)。
- 结果层落回「原最低参与层」的位置,`assignLayerZ` 重新连续编号,不产生重复 z。
## v1.7:图层面板补齐(缩略图 / 改名 / 不透明度)
发布后通读全仓(10 个模块 9368 行)发现的缺口,按「改完就能天天用到」的顺序处理。
### 不透明度终于能调了
`opacity` 字段一直在(合成、合并、导出、快照都读它),但面板上没有任何控件能写它,
roadmap 里标着「✅ 已有」与实际不符。现在选中图层后,该项下方展开一条滑杆:
| 项 | 行为 |
| --- | --- |
| 载体 | 位图走 canvas 的 CSS `opacity`(像素不动);文字/形状改完重绘矢量层 |
| 导出 / 合并 | 位图在合成时乘 `globalAlpha`,与屏幕所见一致 |
| 撤销 | 一次拖动只拍 1 张快照(`input` 先到才拍,松手不再重复) |
| 复位 | 双击滑杆回 100%;非 100% 且未选中的层在名字旁挂 `55%` 角标 |
**矢量层不重复乘 alpha**:`drawVectorToCanvas` / `drawShape` 已经把 `opacity` 画进像素,
`getCompositeCanvas` 与 `composeUnitsInto` 再乘一次就是双倍透明 —— 两处都改成只对位图乘。
### 缩略图与重命名
- 每项左侧 22px 缩略图(设备像素 44,高分屏不糊),把图层 canvas 等比缩进框内;
空图层没内容时缩略图透明,垫在下面的类型图标就露出来当兜底。
- 画缩略图**合批 90ms**:连续选中 / 拖动时不会每次 `renderLayerPanel` 都重画几十张。
- 双击图层名进入改名(Enter 提交、Esc 放弃,自动拍快照)。重命名期间禁用整项拖动,
否则在输入框里拖选文字会变成拖动图层排序。
- 双击判定是**自己算的**:点一下名字就 `setActiveLayer` → `renderLayerPanel` 重建整块
`innerHTML`,第二次点击落在新节点上,浏览器不会再派发 `dblclick`(和 v1.5 画布双击同一个坑)。
顺带让 `setActiveLayer` 在「已经是它」时直接返回,少一次无谓重建。
### 顺手清掉的三处
1. **删掉两个永远看不见的控件**:面板里 `.iwb-layer-color` / `.iwb-layer-width` 被 CSS
`display:none !important` 连写三遍隐藏(v1.2 把颜色/线宽搬去选项栏后的遗留),
绑定还在,每次 `input` 都 `renderLayerPanel()` 把整块 DOM 换掉 —— 一旦哪天取消隐藏,
取色器会当场断开、数字框打不进两位数。连同绑定与死样式一起删除。
2. **`pasteImageFromUrl` 不再用 `window.alert`**:改走 `toast`,阻塞弹窗在宿主里会卡住整页。
3. **`resetState()` 补齐跨会话残留**:`layerMulti` / `hoverPos` / `lastClick` / `lastNameClick` /
`altPicker` 之前不清,重开编辑器时会指向上一张图已经不存在的图层。
## 入口
- **节点漂浮菜单**「标注 / 修图」(**仅 `ref` 图片输入节点**)
- `out` / `gen` / `layer` 是产图节点:一个节点可能有多张结果或多个图层,`getNodeImage` 只能取 `result[0]`,在漂浮菜单放「编辑图片」会被误读成「编辑结果图」。要处理产出的图,先「复制 / 插入为参考图节点」。
- 右键菜单「插件命令 → 标注 / 修图:选中节点」
导出后由编辑器自己 `close()`:
- 点「覆盖」→ `ctx.canvas.setNodeImage(nodeId, dataUrl)`
- 点「新建」→ `ctx.canvas.createImageNode({ dataUrl, name })`(宿主会建一个 `ref` 节点)
- 点「下载」→ 只下载当前这一张,**不回写节点、不关闭编辑器**(v1.1)
### 剪贴板粘贴(v1.0.4)
编辑器打开时按 **⌘/Ctrl+V**,把剪贴板里的图片**贴为新图层**。
v1.1 起**一步落层**(原大不超过画布 50%、居中),不再需要先调整再按 Enter 确认;
要改大小/位置直接切「选择」工具拖 8 个手柄,Ctrl+Z 可撤销这一步。优先级:
1. 剪贴板里的**图片文件**(截图 / 右键复制图片)
2. `text/html` 里的 `<img src>`(网页里复制图片的形态)
3. `text/plain` 的图片 URL / data URL
实现要点:URL 必须 **fetch→blob→dataURL**(直接 `new Image(url)` 会污染画布,导出时 toBlob 抛 SecurityError),
而 `data:` URL 不能 fetch(CSP `connect-src` 不含 `data:`,会被拦)要直接走 `loadImage`。
正在文字输入框打字时不抢文本粘贴。
### 移植改动之二:图层顺序与选中(v1.0.5 修复)
上游存在**两套 z 计数器**:位图初始化 `base=0 / draw=1 / zCounter=1`,矢量与空白层用 `++zCounter`,
而「粘贴/导入图片」落层却用 `z = S.layers.length` ⇒ 画一个图形(z=2)后粘贴截图(z=2)**z 撞车**。后果:
- 排序按钮靠「交换相邻两项 z」实现上移/下移,2↔2 交换后没变化;同 z 时矢量被判成最顶层,`置顶/上移` 直接 return;
`置底` 算出 `-1` 被不透明原图盖住,看起来像图层消失了;
- 命中测试先查矢量、再查位图,**两段各自排序、从不比较彼此 z** ⇒ 截图下面有图形时永远选不中截图,
于是排序按钮作用在了错误对象上;面板高亮还用 `selectedLayerId || activeLayerId`,出现两个图层同时亮。
本插件的修法(**`objects.js` 的 `layerUnits()` 是图层顺序唯一真源**):
- 所有新建对象统一 `++S.zCounter`;重排后按索引重新分配连续 z(`assignLayerZ`),z 永不重复;
- 面板 / DOM 叠放 / 导出合成 / 命中测试**共用同一份 z 序**;置顶/上移/下移/置底改为「统一列表重排」;
- 命中测试合并为 `hitTopmost()`,按统一 z 降序逐项判定(位图按矩形/像素、矢量按包围盒/形状);
- 选中态统一走 `selectUnit()`,四个 id 一起写;**高亮只代表选中**,画笔/橡皮作用目标改用图层项上的 `✎` 标记;
- `base` 是锁定且不透明的底图,固定在最下层,「置底」到它上面为止(不会再让元素消失);
- 删除图层不再把位图 z 重置成 `0..n-1`;裁剪 / 清空标注 / 重开编辑器时清掉旧的位图选中 id。
## 已知限制(v1)
- **远程 http(s) 图片不支持**:`ctx.canvas.getNodeImage` 对非 data: 字符串只返回 `{ url }`(画布读像素会污染),
插件会给出「请先转存为本地位图」的提示。对象引用(`{__blob}` 等)会被宿主解成 dataUrl,正常可用。
- 4K 图导出走 Blob → 再转 dataURL 回写(约 44MB base64 一次),内存开销已在编辑器侧尽量压到最低。
## 开发 / 构建
源码在 `plugin/`,产物是 `src/index.js`(**提交进仓**,CI 只校验不构建)。
```bash
cd /Users/qiqi/open/github/iwb-plugins
npm install # 只为 esbuild(devDependency)
npm run build -- image-annotate # plugin/entry.js → src/index.js(含产物自检)
npm run validate # 契约校验
```
**构建为什么要分三段**(`scripts/build-plugin.mjs`):
1. esbuild 会把字符串统一改写成双引号,而 `scripts/validate.mjs` 只认单引号 manifest;
2. 校验器取「文件里第一个 id 字面量」判定插件 id,manifest 必须排在 bundle 之前。
→ `plugin/manifest.banner.js`(单引号 manifest,原样放最前)+ esbuild bundle + `plugin/manifest.footer.js`(注册调用)。
`version` 只有一处真源:构建时用 `package.json` 的 `version` 替换 banner 里的 `__PLUGIN_VERSION__`。
> 注意:banner 的**注释**里也不能出现 id + 冒号 + 单引号的组合,否则会被校验器当成 manifest 抢走(踩过一次)。
## 发布(按 HANDBOOK 第八节:先提交 → 合主干 → 再发布)
```bash
# 1) 源码与产物先落库,并确保 HEAD 已在 origin/main(脚本会强制校验这两条)
cd /Users/qiqi/open/github/iwb-plugins
npm run build -- image-annotate && npm run validate
git add image-annotate && git commit -m "feat(image-annotate): v1.7.0 ..." && git push
git switch main && git merge --ff-only <你的分支> && git push
# 2) 用带守卫的发布脚本(旧 plugins-publish.mjs 会绕过校验,不要再用)
cd /Users/qiqi/open/github/image-workbench-web
scripts/plugins-publish.sh image-annotate \
/Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js 1.7.0
# 3) 脚本会打 annotated tag 但不会推,手动补
git -C /Users/qiqi/open/github/iwb-plugins push origin [email protected]
```
脚本的三道前置校验:工作区干净、HEAD 是 `origin/main` 的祖先、`wrangler.toml` 有 KV namespace。
任一条不满足直接拒发(紧急热修才用 `IWB_PUBLISH_SKIP_CHECKS=1`,事后必须补合并与 tag)。
发布脚本**默认与线上清单合并**(本次没传的插件原样保留),只传自己的文件即可;`--remove` 才是从清单移除。
版本两处一起改:`package.json`(构建时注入 manifest)+ 脚本第 3 个参数。上传后回读校验清单与本地一致。
发布后刷新即生效(KV 为测试站/正式站共享;新插件在插件管理里**默认未启用**,需手动开启)。
## 验证(可选,开发用)
`tools/e2e-site.mjs`:**带 CSP 的真实站点**端到端(真 KV 加载 + 浏览器 SRI + 漂浮菜单 → 编辑器 → 覆盖/新建),
另含 v1.0.5 的图层顺序回归:画图形 + 粘贴截图 → 唯一高亮、点重叠区选中最上层截图、四个排序按钮逐一生效、原图始终在最底。
需要 Playwright(可从宿主仓 `node_modules` 或全局解析),**不进 CI**(本仓 CI 只跑 `npm run validate`,不联网、无依赖)。
```bash
IWB_BASE_URL=https://test.image-workbench-web.pages.dev node image-annotate/tools/e2e-site.mjs
```
> 为什么值得留着:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在 mock 下永远绿,只有真站能抓出来。
+373
View File
@@ -0,0 +1,373 @@
# 简化版 PS(Image Editor Lite)目标与实施分析
> 基线:`image-annotate` v1.0.5(`plugin-image-annotate.cfecb6e2ec17.js`),宿主 `image-workbench-web` 插件 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(localStorage),**不是像素仓库** |
---
## 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 点击多选合并;编组仍待做 | 部分完成 |
| `resetDraw()` 语义歧义 | 「清空标注」只清非 base 层像素,留下空白粘贴层(1.0.5 遗留)⇒ **已裁定改为「全部还原」**:删所有非 base 层 + 清绘制 + 复位变换,一步可撤销;按钮改名「还原原图」 | P0 定语义(已定) |
### 3.4 输出(单张)
| 缺口 | 说明 | 优先级 |
| -------------- | ------------------------------------------------------------------------------------ | ----------- |
| 只有 PNG | 无 JPG/WebP、无质量控制 | P4 |
| 无背景切换(透明 / 白底) | 电商出图要手工来回切换 | P4 |
| 无体积上限策略 | 无法保证 ≤500KB 这类交付规范 ⇒ **已裁定做成可切换预设**(800×800 / 长边 640 / 质量迭代 ≤500KB,存 `ctx.settings`) | P4(随 P1 带上) |
| 无下载 / 复制到系统剪贴板 | 只能回写宿主节点 | P4 |
| 导出步骤偏多 | 覆盖 / 新建 / 退出三个按钮分散,没有「记住上次选择」 | 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` 只是 localStorage 小 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` → **先提交源码并合进 `origin/main`** → 宿主仓 `scripts/plugins-publish.sh image-annotate <插件路径> <版本>`(带守卫,拒发脏工作区/未合主干)→ 补推 tag → 真站 e2e(带 CSP)。版本两处同步(`package.json` + 脚本参数),禁止手改 `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 迭代降质、下载、设置记忆;无队列 |
| 历史快照升级 | ✅ `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 降级 |
| 草稿持久化 | `ctx.storage` 是 localStorage 命名空间小 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.js`、id 一致、SRI、内容寻址名、清单合并、tag 反查;脚本守卫强制「工作区干净 + HEAD 已在 origin/main」 |
| 测试 | 本地 mock 探针(直接注入 `src/index.js` + mock host)用于发布前验证;真站 e2e(CSP / KV / 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.7.0",
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
"ibwPlugin": {
"id": "image-annotate",
"entry": "src/index.js",
"apiVersion": 1
}
}
+1802
View File
File diff suppressed because it is too large. Load diff
+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)
}
+358
View File
@@ -0,0 +1,358 @@
/* crop.js - 裁剪工具
* 节:裁剪、裁剪栏。
* 遮罩绘制写 S.overlayCanvas;确认裁剪后逐图层搬运像素(v1.2 起不再 flatten)。
*/
'use strict'
import { S, runtime } from './state.js'
import { resizeWorkspace } from './viewport.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
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
}
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 / S.zoom
ctx.setLineDash([8 / S.zoom, 4 / S.zoom])
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 / S.zoom
ctx.save()
ctx.fillStyle = '#ffffff'
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 1.5 / S.zoom
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 / S.zoom
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() { /* 同上 */ }
+319
View File
@@ -0,0 +1,319 @@
/* dom.js - 编辑器 DOM 构建与图片加载
* 节:DOM 创建、图片加载。
* createEl 负责创建遮罩根节点并写入 runtime.el,随后把各 canvas/面板
* 引用挂到 S 上;open() 依赖它保证 el 只创建一次。
*/
'use strict'
import { S, runtime } from './state.js'
import { bindEvents } from './events.js'
// ============ 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>
<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>
<span class="iwb-editor-divider"></span>
<!-- 顶栏命令带(v1.2.6):撤销/重做/还原 | 顺序 | 视图;图层新建/导入回图层面板标题栏 -->
<div class="iwb-editor-commands">
<div class="iwb-editor-cmdgroup" data-group="order" title="调整选中元素的图层顺序">
<button class="iwb-editor-layer-btn" data-layer="top" title="置顶:选中元素移到最上层 (Ctrl+Shift+])"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" y1="5" x2="20" y2="5"/><line x1="12" y1="19" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg></button>
<button class="iwb-editor-layer-btn" data-layer="up" title="上移一层 (Ctrl+])"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg></button>
<button class="iwb-editor-layer-btn" data-layer="down" title="下移一层 (Ctrl+[)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="6 13 12 19 18 13"/></svg></button>
<button class="iwb-editor-layer-btn" data-layer="bottom" title="置底:选中元素移到最下层 (Ctrl+Shift+[)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="6 13 12 19 18 13"/><line x1="4" y1="19" x2="20" y2="19"/></svg></button>
</div>
<span class="iwb-editor-divider"></span>
<div class="iwb-editor-cmdgroup" data-group="view">
<button class="iwb-editor-action" 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-action" 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>
</div>
</div>
<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-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">选区也可右键;Ctrl+J 复制 · Delete 清除 · Ctrl+D 取消</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>
<input class="iwb-editor-text-input" type="text" placeholder="输入文字,Enter确认,Esc取消">
<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.3):点开就是完整色板,侧栏不再放调色板 -->
<button type="button" class="iwb-editor-color-btn" data-action="toggleColorPop" aria-expanded="false" title="颜色:点开色板(调色器 / 吸管 / 推荐色)"><i></i></button>
<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="套索 (L):按住拖动自由圈选,松手闭合"><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="矩形 (U):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="圆形 (U):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="箭头 (U):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>
<span class="iwb-editor-divider"></span>
</div>
</div>
<div class="iwb-editor-zoom-hint">滚轮缩放 · 抓手/空格/中键拖拽自由移动画布</div>
<aside class="iwb-editor-left">
<!-- 调色板已迁到工具栏弹层(v1.3,用户裁定 2026-11-05):
侧栏只留快速效果 + 缩放;色板 DOM 在 modal 末尾的 .iwb-editor-color-pop -->
<!-- 快速效果(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>
<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):工具栏色点点击展开。
必须挂在 modal 下、不能塞进 .iwb-editor-tools —— 工具栏是 overflow-x:auto,
canvas-wrap 是 overflow:clip,塞进去弹层会被直接裁掉;定位由 events.js 计算。 -->
<div class="iwb-editor-color-pop" hidden>
<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>
<div class="iwb-color-pop-fields">
<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="十六进制颜色,回车生效">
</div>
<span class="iwb-color-pop-sep"></span>
<div class="iwb-editor-color-swatches">
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff4444" style="background:#ff4444" title="#ff4444"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff8a00" style="background:#ff8a00" title="#ff8a00"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ffd400" style="background:#ffd400" title="#ffd400"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#4cd964" style="background:#4cd964" title="#4cd964"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#00bfa5" style="background:#00bfa5" title="#00bfa5"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#4488ff" style="background:#4488ff" title="#4488ff"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#aa44ff" style="background:#aa44ff" title="#aa44ff"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ff66aa" style="background:#ff66aa" title="#ff66aa"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#ffffff" style="background:#ffffff" title="#ffffff"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#d0d0d0" style="background:#d0d0d0" title="#d0d0d0"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#808080" style="background:#808080" title="#808080"></button>
<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="#000000" style="background:#000000" title="#000000"></button>
</div>
</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 */ } }
}
}
+161
View File
@@ -0,0 +1,161 @@
/* effects.js - 侧栏「快速效果」(v1.4)
*
* 作用对象只有一个:当前位图图层(侧栏标题后面实时显示层名)。
* 全部走 canvas 2D 的 ctx.filter / 缩放重采样,不引入依赖、不动矢量层、
* 不改图层几何,因此对「原图」这种带 locked 标记的层也安全(效果不是画笔)。
*
* 撤销:应用前 saveSnapshot()。base 与画笔层走像素快照(putImageData),
* 天然可回退;导入图片层走 image/sourceCanvas 重绘,原地改像素会被下一次
* 重绘冲掉,所以先按 PS「栅格化」的做法落一个普通位图副本(原层隐藏)。
*/
'use strict'
import { S } 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'
/** 效果表:label 用于按钮与提示,css 可依赖画布尺寸(柔化半径随图缩放) */
export const QUICK_EFFECTS = {
invert: { label: '反白', hint: '反相:明暗翻转,白底变黑底', css: () => 'invert(1)' },
gray: { label: '灰度', hint: '去色,保留明暗层次', css: () => 'grayscale(1)' },
boost: { label: '增强', hint: '提亮并略加对比', css: () => 'brightness(1.12) contrast(1.1) saturate(1.06)' },
contrast: { label: '高对比', hint: '压成黑白硬调', css: () => 'grayscale(1) contrast(2.4)' },
soft: { label: '柔化', hint: '轻微模糊,弱化背景', css: (c) => 'blur(' + softRadius(c) + 'px)' },
mosaic: { label: '马赛克', hint: '像素化,用于打码', pixel: true }
}
const SOFT_MIN = 0.8
const SOFT_MAX = 8
function softRadius(canvas) {
const side = Math.min(canvas.width || 0, canvas.height || 0)
return Math.max(SOFT_MIN, Math.min(SOFT_MAX, Math.round(side / 500 * 10) / 10))
}
function mosaicBlock(canvas) {
const side = Math.min(canvas.width || 0, canvas.height || 0)
return Math.max(6, Math.round(side / 60))
}
/** 效果目标:当前活跃位图图层;没有就退回「原图」 */
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()
}
/** 马赛克:缩到 1/block 再关掉平滑放大,比逐像素 getImageData 快一个量级 */
function pixelateCanvas(canvas, block) {
const w = canvas.width, h = canvas.height
if (!w || !h) return
const sw = Math.max(1, Math.round(w / block))
const sh = Math.max(1, Math.round(h / block))
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()
}
/**
* 把「导入图片层」栅格化成普通位图,插在它上面一层。
* 只拷当前 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
}
/** 唯一入口:应用一个快速效果 */
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
}
saveSnapshot('效果:' + fx.label)
let target = layer
if (!needsPixelSnapshot(layer)) target = rasterizeLayer(layer)
if (!target) { toast('栅格化失败,效果未应用'); return false }
if (fx.pixel) pixelateCanvas(target.canvas, mosaicBlock(target.canvas))
else filterCanvas(target.canvas, fx.css(target.canvas))
target._bounds = undefined
S.pickerComposite = null
if (S.renderAll) S.renderAll()
renderLayerPanel()
toast('已应用「' + fx.label + '」到 ' + target.name + ' · Ctrl+Z 撤销', 'success')
return true
}
File diff suppressed because it is too large. Load diff
+296
View File
@@ -0,0 +1,296 @@
/* 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')
}
+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 }
+366
View File
@@ -0,0 +1,366 @@
/* 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.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.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() }
+355
View File
@@ -0,0 +1,355 @@
/* 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 } from './objects.js'
import { setupCanvas } from './viewport.js'
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar } from './events.js'
import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js'
import { bindFloating, positionFloating, hideSelectionContext } from './floating.js'
import { loadExportOptions, prepareOutput, downloadBlob, bindExportUI, renderExportUI } from './export.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
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()
bindLiteUI()
bindFloating()
bindExportUI()
initPanels()
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.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) {
const pad = S.overlayPad || 0
S.cursorCtx.setTransform(1, 0, 0, 1, 0, 0)
S.cursorCtx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
S.cursorCtx.setTransform(1, 0, 0, 1, pad, pad)
}
}
/** 命令层统一重绘出口:所有新操作的像素/UI/选区状态在这里对齐 */
function renderAll() {
if (!S.open || !runtime.el) return
renderObjects()
renderLayerPanel()
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
// 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) || '图片跨域'))
}
}
// ============ 暴露接口 ============
/**
* 快照/历史开销观测口(性能回归与手测用):
* 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, z: s.z, color: s.color })),
texts: S.textLayers.map(t => ({ id: t.id, text: t.text })),
selectedShapeId: S.selectedShapeId,
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,
interaction: S.interaction,
ants: !!S._antFrame,
view: S.viewX !== null ? [Math.round(S.viewX), Math.round(S.viewY)] : 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
+722
View File
@@ -0,0 +1,722 @@
/* 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 { 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, updateLayerUI } from './events.js'
import { isDrawableLayer } from '../vendor/layer-logic.js'
// ============ 文字图层 ============
export const TEXT_FONT = (size) => 'bold ' + size + 'px sans-serif'
export function textBounds(t) {
const ctx = S.textCtx
ctx.font = TEXT_FONT(t.fontSize)
const w = ctx.measureText(t.text).width
const h = t.fontSize * 1.25
return { x: t.x, y: t.y, w, h }
}
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 / S.zoom
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 / S.zoom, 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 / S.zoom, 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 / S.zoom, 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 / S.zoom, 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 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()
// base 是锁定且不透明的底图,固定在最下层;任何元素都不许置底到它下面(否则等于消失)
const baseIdx = units.findIndex(u => u.obj.id === 'base')
if (baseIdx > 0) { const [b] = units.splice(baseIdx, 1); units.unshift(b) }
const from = units.findIndex(u => u.obj === sel.obj)
if (from < 0) return
const min = baseIdx >= 0 ? 1 : 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 / S.zoom
const R = Math.max(14 / S.zoom, 9)
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 / S.zoom
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 / S.zoom, 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) / S.zoom
ctx.setLineDash([8 / S.zoom, 5 / S.zoom])
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, Math.max(4, 6 / S.zoom), 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 / S.zoom
octx.setLineDash([6 / S.zoom, 3 / S.zoom])
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()
octx.setLineDash([])
const hs = 5.5 / S.zoom
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()
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 / S.zoom
octx.setLineDash([6 / S.zoom, 3 / S.zoom])
const corners = boxCorners(b.x - 2 / S.zoom, b.y - 2 / S.zoom, b.w + 4 / S.zoom, b.h + 4 / S.zoom, 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()
octx.setLineDash([])
const hs = 5.5 / S.zoom
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()
updateLayerUI()
}
// ============ 钢笔二次编辑(移动/添加/删除节点) ============
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 = Math.max(12 / S.zoom, 6)
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 = Math.max(7 / S.zoom, 5)
ctx.save()
ctx.lineWidth = 1.5 / S.zoom
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, Math.max(3 / S.zoom, 2), 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 rect = S.canvasStack.getBoundingClientRect()
const wrapRect = S.canvasWrap.getBoundingClientRect()
const sx = rect.width / S.imgW
const sy = rect.height / S.imgH
input.style.left = (rect.left - wrapRect.left + x * sx) + 'px'
input.style.top = (rect.top - wrapRect.top + y * sy) + 'px'
input.style.display = 'block'
if (layer) {
input.value = layer.text
S.textEditingId = layer.id
} else {
input.value = ''
S.textEditingId = null
}
input.focus()
input.select()
input.dataset.x = x
input.dataset.y = y
}
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),
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()
}
}
+277
View File
@@ -0,0 +1,277 @@
/* 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 { 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 / S.zoom
ctx.setLineDash([8 / S.zoom, 4 / S.zoom])
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 / S.zoom
ctx.fillStyle = '#fff'
ctx.strokeStyle = '#4488ff'
ctx.lineWidth = 1.5 / S.zoom
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 / S.zoom) + '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 / S.zoom
const tw = ctx.measureText(hintText).width
ctx.fillStyle = 'rgba(0,0,0,0.6)'
ctx.fillRect(cx - tw / 2 - 6 / S.zoom, hintY, tw + 12 / S.zoom, 22 / S.zoom)
ctx.fillStyle = 'rgba(255,255,255,0.95)'
ctx.fillText(hintText, cx, hintY + 4 / S.zoom)
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 / S.zoom
// 四角外侧圆弧 = 旋转手柄
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
}
+445
View File
@@ -0,0 +1,445 @@
/* 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 { 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
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
}
export function clearCursorCanvas() {
const ctx = S.cursorCtx
if (!ctx) return
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
}
/** 蚂蚁线:黑白两段错位的虚线,rAF 只重绘这一张小画布 */
export function renderSelection() {
if (!S.selectionCtx) return
clearSelectionCanvas()
const ctx = S.selectionCtx
const k = 1 / Math.max(S.zoom, 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 }
}
+115
View File
@@ -0,0 +1,115 @@
/* state.js - 编辑器唯一状态所有者
* 持有 S(全局状态对象)、ZOOM_* 常量,以及 runtime(可变持有对象)。
* 约定:ES 模块 import 绑定不可重新赋值,所以编辑器根节点 el 不用
* `export let el`,而是放在 runtime.el 里,各模块统一读写 runtime.el。
* 本模块不 import 任何编辑器内部模块(保持叶子节点,避免循环 TDZ)。
*/
'use strict'
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, // 吸管取样用的合成画布缓存(切工具/画布变化时失效)
rectFill: false, // 矩形/圆形是否实心填充
penFill: true, // 钢笔闭合路径是否实心填充(只对闭合路径有意义)
// v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细,
// 否则「调细画笔」会顺手把所有形状的描边一起改掉。
shapeLineWidth: 3, // 矩形/圆形/箭头/钢笔的描边粗细
textSize: 32, // 新建文字的字号 px
// 图层系统
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 注入的统一重绘出口
lastExport: null // 观测口:{ bytes, width, height, format, preset }
}
export const runtime = { el: null }
+447
View File
@@ -0,0 +1,447 @@
/* 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 { 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'
// ============ 绘制工具 ============
// 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
}
/** 按形状对象绘制(矩形/箭头),预览与最终渲染共用 */
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 = s.color
ctx.lineWidth = s.lw
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
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 = s.color; ctx.fill() } 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)
if (s.fill) { ctx.fillStyle = s.color; ctx.fillRect(rx, ry, rw, rh) }
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 = s.color; ctx.fill() }
ctx.stroke()
} else {
ctx.fillStyle = s.color
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
const pad = S.overlayPad || 0
ctx.save()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.clearRect(0, 0, S.imgW + pad * 2, S.imgH + pad * 2)
ctx.restore()
ctx.setTransform(1, 0, 0, 1, pad, pad)
}
/** 圆形笔刷光标:画在独立 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
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) {
if (!skipHistory) saveSnapshot()
sh.color = S.color
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()
}
+345
View File
@@ -0,0 +1,345 @@
/* viewport.js - 画布尺寸、缩放平移、旋转辅助与坐标换算
* 节:画布设置、旋转辅助、坐标。
* 约定:所有屏幕坐标 <-> 图片坐标的换算都过 getPos/rotPt/unrotPt,
* 缩放状态只写 S.zoom / S.viewX / S.viewY。
*/
'use strict'
import { S, ZOOM_MAX, ZOOM_MIN } from './state.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))
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = S.imgW + S.overlayPad * 2
c.height = S.imgH + S.overlayPad * 2
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
}
// 创建图层 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()
computeFit()
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))
for (const [c, cx] of [[S.overlayCanvas, S.overlayCtx], [S.selectionCanvas, S.selectionCtx], [S.cursorCanvas, S.cursorCtx]]) {
if (!c || !cx) continue
c.width = S.imgW + S.overlayPad * 2
c.height = S.imgH + S.overlayPad * 2
cx.setTransform(1, 0, 0, 1, S.overlayPad, S.overlayPad)
}
purgeVectorCanvases()
for (const layer of S.layers) {
layer.canvas.width = S.imgW
layer.canvas.height = S.imgH
layer._bounds = undefined
}
S.pickerComposite = null
clearOverlay()
computeFit()
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)) }
// ============ 旋转辅助 ============
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
const d = 26 / Math.max(S.zoom, 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)
const R = Math.max(11 / Math.max(S.zoom, 0.0001), 8)
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(S.zoom, 0.0001)
const r = Math.max(6.5 / k, 5)
const lw = 1.5 / k
const ah = Math.max(3 / k, 2.6) // 箭头长度
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
}
}
+17
View File
@@ -0,0 +1,17 @@
/* 打包入口(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)
}
+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() 与像素释放,这里无额外订阅需要解绑 */ },
}
}
+23
View File
@@ -0,0 +1,23 @@
// 手写 manifest —— 必须保持单引号:scripts/validate.mjs 只认单引号形式,而 esbuild 打印器会改成双引号,
// 所以本文件不经 esbuild 转换,由 build-plugin.mjs 原样放在产物最前面(banner)。
//
// 为什么必须排在最前:校验器用「文件里第一个形如 id 冒号 单引号 的字面量」判定插件 id,
// 排在 bundle 之前才能保证取到的是下面这份 manifest,而不是打包代码里的同形字面量。
// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。
//
// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。
var __IWB_ANNOTATE_MANIFEST__ = {
id: 'image-annotate',
name: '标注 / 修图',
version: '__PLUGIN_VERSION__',
apiVersion: 1,
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 }
},
}
+9
View File
@@ -0,0 +1,9 @@
// 手写注册尾部(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)
+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
+271
View File
@@ -0,0 +1,271 @@
// 真实站点端到端(开发用,不进 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') || '' })))
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))
const before = await panelSeq()
await page.locator('.iwb-editor-layer-btn[data-layer="down"]').click()
const afterDown = await panelSeq()
check('「下移一层」改变图层顺序', before !== afterDown, before + ' → ' + afterDown)
await page.locator('.iwb-editor-layer-btn[data-layer="up"]').click()
check('「上移一层」恢复原顺序', (await panelSeq()) === before, await panelSeq())
await page.locator('.iwb-editor-layer-btn[data-layer="bottom"]').click()
const afterBottom = await panelSeq()
check('「置底」生效且原图仍在最底(元素不会消失)',
afterBottom !== before && afterBottom.endsWith('原图'), afterBottom)
await page.locator('.iwb-editor-layer-btn[data-layer="top"]').click()
check('「置顶」生效', (await panelSeq()) !== afterBottom, await panelSeq())
check('排序后仍只有一个选中项', (await activeCount()) === 1, 'active=' + await activeCount())
// 复原成画笔工具,避免影响后面「覆盖」链路的画笔取样
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
+134
View File
@@ -0,0 +1,134 @@
# 位图转矢量(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(便于整体缩放/移动)
- 预览:按住空格对比原图;面板显示元素数 / 层数 / 体积 / 耗时
- 输出:**复制 SVG**(写 `image/svg+xml` + `text/html` + `text/plain` 三种剪贴板口味,
Figma / Illustrator 粘进去就是真矢量)· **下载 SVG** · **保存为节点**(PNG,按输出倍率 1–4× 从矢量重绘)
## 按孤岛拆分(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 极淡描边 +
细阴影;这是唯一一处「为了看清边界」而加的装饰。
## 复制到剪贴板为什么写三种口味
剪贴板不像文件,只有一个「格式」——它同时可以装多份不同 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,47 项)
node image-vectorize/tools/e2e-site.mjs # 真站(KV / 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/)
```
发布:
```bash
cp image-vectorize/src/index.js /tmp/plugin-image-vectorize.js
cd ../image-workbench-web && node scripts/plugins-publish.mjs /tmp/plugin-image-vectorize.js \
--version image-vectorize=0.3.0 --upload
```
## 已知限制
- **照片不适合**: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.3.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
}
+31
View File
@@ -0,0 +1,31 @@
// 手写 manifest —— 必须保持单引号:scripts/validate.mjs 只认单引号形式,而 esbuild 打印器会改成双引号,
// 所以本文件不经 esbuild 转换,由 build-plugin.mjs 原样放在产物最前面(banner)。
//
// 为什么必须排在最前:校验器用「文件里第一个形如 id 冒号 单引号 的字面量」判定插件 id,
// 排在 bundle 之前才能保证取到的是下面这份 manifest。
// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。
//
// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。
var __IWB_VECTORIZE_MANIFEST__ = {
id: 'image-vectorize',
name: '位图转矢量',
version: '__PLUGIN_VERSION__',
apiVersion: 1,
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 }
}
+472
View File
@@ -0,0 +1,472 @@
/* 位图转矢量:全屏模态。深色,与「标注 / 修图」同一套视觉语言。
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: 92vw;
height: 88vh;
min-width: 760px;
min-height: 520px;
max-width: 1680px;
background: #1b1b22;
border: 1px solid #33333f;
border-radius: 12px;
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55);
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; }
.vz-btn-primary {
background: #1f7a52;
border-color: #27875c;
color: #eafff5;
}
.vz-btn-primary:hover { background: #248a5d; border-color: #2f9c69; }
.vz-btn-primary:disabled { background: #24503e; border-color: #2a5c47; }
/* ---------- 主体 ---------- */
.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;
}
/* 白底之上用一圈极淡的描边 + 细阴影标出画面边界:
白底稿(如菜单/白底商品图)与预览区同色时,否则看不出图到哪里 */
.vz-stage {
max-width: 100%;
max-height: 100%;
display: block;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.07);
}
.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;
}
/* 描摹中/出错的浮层 */
.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: 96vw; height: 92vh; min-width: 0; }
.vz-body { flex-direction: column; }
.vz-panel { width: auto; max-height: 46%; border-left: 0; border-top: 1px solid #2e2e3a; }
}
+688
View File
@@ -0,0 +1,688 @@
/* 「位图转矢量」的 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>' +
'<button type="button" class="vz-btn" data-act="cancel">取消</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-primary" data-act="save">保存为节点</button>' +
'</header>' +
'<div class="vz-body">' +
'<div class="vz-preview">' +
'<img class="vz-stage" data-stage="vector" alt="矢量预览">' +
'<img class="vz-stage" data-stage="original" alt="原图" 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">空格 对比原图 · 「复制 SVG」可直接粘到 Figma</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
// ---------- 设置读写 ----------
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 ? '原图' : '矢量预览'
}
// ---------- 描摹 ----------
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
}
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
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]'),
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.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)
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
}
+228
View File
@@ -0,0 +1,228 @@
// 真实站点端到端(开发用,不进 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)
}))
// ---------- 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
}))
// ---------- 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)
+465
View File
@@ -0,0 +1,465 @@
// 位图转矢量(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-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'
}))
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=/tmp/vz-panel.png 出一张面板截图(验证「填充 / 背景」这排没挤坏布局)
if (process.env.VZ_SHOT) await page.locator('.vz-modal').screenshot({ path: process.env.VZ_SHOT })
// ---------- 背景色 / 带底(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 ----------
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)
}))
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"
}
}
}
}
+5 -1
View File
@@ -4,6 +4,10 @@
"version": "1.0.0",
"description": "IWB 插件仓:只写插件,不复制宿主契约",
"scripts": {
"validate": "node scripts/validate.mjs"
"validate": "node scripts/validate.mjs",
"build": "node scripts/build-plugin.mjs"
},
"devDependencies": {
"esbuild": "^0.24.2"
}
}
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env node
/**
* 构建「需要打包的插件」:ESM 源码 → 单文件 IIFE 产物。
*
* 用法:node scripts/build-plugin.mjs <插件目录名> (或 npm run build -- <插件目录名>)
* 输入:<插件>/plugin/{entry.js, manifest.banner.js, manifest.footer.js, *.css}
* 输出:<插件>/<ibwPlugin.entry>(通常是 src/index.js,产物提交进仓,CI 不构建)
*
* 为什么分三段拼接,而不是把 manifest 交给 esbuild:
* 1. esbuild 的打印器会把字符串统一改写成双引号,而 scripts/validate.mjs 只认 '...' 形式;
* 2. 校验器用「文件里首个 id: '...'」判定插件 id,manifest 必须排在 bundle 之前。
* 所以 manifest 走 banner 通道(原样文本)、bundle 走 esbuild、注册调用走 footer 通道(原样文本)。
*/
import { readFileSync, existsSync } from 'node:fs'
import { resolve, dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const name = process.argv[2]
if (!name) {
console.error('用法: node scripts/build-plugin.mjs <插件目录名>')
process.exit(1)
}
const dir = join(ROOT, name)
const pkgPath = join(dir, 'package.json')
if (!existsSync(pkgPath)) {
console.error('[build] 不是插件目录(缺 package.json):' + dir)
process.exit(1)
}
let pkg
try { pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) } catch (error) {
console.error('[build] package.json 解析失败:' + error.message)
process.exit(1)
}
const meta = pkg.ibwPlugin || {}
const id = String(meta.id || '')
const outFile = resolve(dir, String(meta.entry || 'src/index.js'))
const entryFile = join(dir, 'plugin', 'entry.js')
const bannerFile = join(dir, 'plugin', 'manifest.banner.js')
const footerFile = join(dir, 'plugin', 'manifest.footer.js')
for (const file of [entryFile, bannerFile, footerFile]) {
if (!existsSync(file)) {
console.error('[build] 缺少构件:' + file.replace(ROOT + '/', ''))
process.exit(1)
}
}
let esbuild
try {
esbuild = await import('esbuild')
} catch (error) {
console.error('[build] 未安装 esbuild(devDependency),请先在本仓执行:npm install')
process.exit(1)
}
// 版本只有一处真源:package.json → 注入 banner 的 __PLUGIN_VERSION__ 占位符。
const banner = readFileSync(bannerFile, 'utf8').replace(/__PLUGIN_VERSION__/g, String(pkg.version))
const footer = readFileSync(footerFile, 'utf8')
await esbuild.build({
entryPoints: [entryFile],
outfile: outFile,
bundle: true,
format: 'iife',
platform: 'browser',
target: ['chrome100', 'edge100', 'firefox100', 'safari15'],
loader: { '.css': 'text' }, // 样式以字符串内联,运行时注入 <style>(宿主 CSP 允许 unsafe-inline)
charset: 'utf8',
legalComments: 'none',
banner: { js: banner },
footer: { js: footer },
logLevel: 'warning',
})
// ===== 产物自检:宁可构建失败,也不交出会被 CI 拦下或被宿主 fail-closed 拒载的文件 =====
const out = readFileSync(outFile, 'utf8')
const fail = (message) => {
console.error('✗ ' + name + ' 产物自检失败:' + message)
process.exit(1)
}
if (!/(?:^|[\s{,])id:\s*'([^']+)'/.exec(out) || /(?:^|[\s{,])id:\s*'([^']+)'/.exec(out)[1] !== id) {
fail('首个 id 字面量不是 ' + id + '(manifest 没有排在 bundle 之前?)')
}
if (out.indexOf('IWBPluginHost.register(') < 0) fail('缺少 IWBPluginHost.register(')
if (!out.includes("version: '" + pkg.version + "'")) fail('version 与 package.json(' + pkg.version + ')不一致')
if (!/apiVersion:\s*1\b/.test(out)) fail('缺少 apiVersion: 1')
if (!/capabilities:\s*\[/.test(out)) fail('缺少 capabilities 数组')
if (/\beval\s*\(|new Function\s*\(/.test(out)) fail('含 eval/new Function,宿主 CSP(无 unsafe-eval)会拦')
console.log('✓ ' + name + ' → ' + outFile.replace(ROOT + '/', '') +
' (' + out.length + ' B, id=' + id + ', version=' + pkg.version + ')')
+5 -2
View File
@@ -1,4 +1,5 @@
// 校验本仓每个插件的契约:package.json 的 ibwPlugin 字段、entry 语法、以及 entry 内 manifest 与契约一致。
// 校验本仓每个插件的契约:package.json 的 ibwPlugin 字段、entry 语法、以及 entry 内 manifest 与契约一致
//(含 version 与 package.json 一致 —— 需构建的插件由 build-plugin.mjs 从 package.json 注入版本)。
// 只读源码、不构建(dist/ 被 gitignore),因此 CI 不需要网络或依赖。
//
// 用法:node scripts/validate.mjs (退出码 0 = 全部通过)
@@ -44,7 +45,9 @@ export const checkPlugin = (dir) => {
if (!apiMatch) errors.push('entry 内未找到 apiVersion 字面量')
else if (Number(apiMatch[1]) !== meta.apiVersion) errors.push('entry 内 apiVersion (' + apiMatch[1] + ') 与 ibwPlugin.apiVersion (' + meta.apiVersion + ') 不一致')
if (!/version:\s*'[^']+'/.test(src)) errors.push("entry 内未找到 version: '<ver>' 字面量")
const versionMatch = /version:\s*'([^']+)'/.exec(src)
if (!versionMatch) errors.push("entry 内未找到 version: '<ver>' 字面量")
else if (versionMatch[1] !== String(pkg.version)) errors.push('entry 内 version (' + versionMatch[1] + ') 与 package.json version (' + pkg.version + ') 不一致')
if (!/name:\s*'[^']+'/.test(src)) errors.push("entry 内未找到 name: '<name>' 字面量")
if (!/capabilities:\s*\[/.test(src)) errors.push('entry 内未找到 capabilities 数组')
+156
View File
@@ -0,0 +1,156 @@
# 风格库(style-source)
资源库面板里的 AI 绘画风格浏览器。310 个风格、12 个分类,点到哪个风格就能把**预览图**插进画布(`ref` 节点)或把**提示词**插进画布(`prompt` 节点)。
风格数据来自开源项目 [style-source](https://github.com/malongan/style-source),插件直连它的 GitHub Pages 静态资源,无后端、无 Key。
## 能力
| 声明 | 用途 |
|---|---|
| `panels` | 注册「风格库」标签页到资源库面板 |
| `canvas` | `getNodes` / `getSelectedNode`(算插入坐标) |
| `canvasWrite` | `createImageNode`(插参考图)/ `createNode('prompt', …)`(插提示词) |
## 交互
- **搜索**:匹配名称 / 编号 / id / 分类 / 摘要 / 标签 / 触发词,150ms 防抖。
- **分类**:chips 按面板宽度**自动换行**(宽档一行铺完,窄档折两三行,永远不会把后面的分类藏起来);按数量降序,记住上次选的分类。窄档不显示数量后缀,省一行高度。
- **网格**:分批渲染(每批 90 个),滚到底自动续渲染;缩略图原生懒加载。
- **详情**:窄面板铺满覆盖层,宽面板变右侧栏;大图 + 标签 + 摘要 + 提示词 + 变量表单。
- **变量替换**:提示词里的 `{角色描述}` 这类占位符给输入框,填了就替换,**留空的保留 `{原占位符}`**(换成空串会把提示词结构弄丢)。未填数量实时提示。**变量全部平铺,不做折叠**——折叠的「收起」状态容易让人以为变量就这几个(Vigo 那批曾最多 24 个,详情页本身可滚动)。输入框的灰色提示**优先用数据里的 `desc`**(「主体花卉,如:栀子花 / 白牡丹」),没有才退回占位符名。
- **插入参考图**:`fetch` 大图 → blob → dataURL → `createImageNode`(宿主只认 `data:` URL)。
- **插入位置(两种方式)**
- **点击**:不传坐标(`createNode('prompt', null, null, …)`),交给宿主 `findSpot()` —— 从**视口中心**向外螺旋扫空位、跳过已有节点、并**避开压在画布上的浮层**(资源中心 / 插件面板 / 左右侧栏)。插件只有节点的 `x/y`,拿不到 pan/zoom 和实测高度,自己排必然插到看不见的地方或压在别的节点上(旧版就是「选中节点右侧固定 380,无避让」)。
- **按住拖到画布上松手**:节点落在**松手点**(`screenToWorld` 换算,节点左上角对齐光标)。落点由宿主算:pan/zoom 只有它知道。拖动中光标下跟一张幽灵卡片,进入画布会提示「松手放这里」;松手点不在画布上(还在面板里)⇒ 取消。位移不足 6px 视作点击,两条路径并存、互不干扰。落点**压住已有节点或被浮层遮住**时,宿主会就近吸附到旁边的空位(`snapToFreeSpot`,20px 间隙、优先留在视口内);落在空处则**完全按松手点**,不偏移。
## 变量:只有提示词里的 `{占位符}` 才算数
**判断依据只有一条**:`prompt` 里真实出现的 `{名字}`。插入时替换的就是这段文本,所以
- 「`variables` 里声明了、但提示词里没有这个占位符」⇒ 输入框是摆设,填了什么都不会被替换(线上 970 条声明里 271 条属于这种);
- 「提示词里有 `{xxx}`、`variables` 里一条都没写」⇒ 以前干脆不出输入框,`{xxx}` 原样插进画布(75 个风格)。
现在统一按提示词抽变量,`variables` 退化成「给占位符配标签」,两种写法都认:
| 写法 | 数据里的样子 | 结果 |
|---|---|---|
| 推荐 | `{ 诗词: '{诗词}' }` | 标签「诗词」→ 替换 `{诗词}` |
| 也认 | `{ 诗词: 诗词 }` | 同上(值没花括号时自动按名字比) |
| 兜底 | key 写成 `` `SUBJECT` ``、值写成人话 `main subject` | 值对不上时拿 key 去找 `{SUBJECT}`,标签取 SUBJECT |
两个都没对上的占位符**照样出输入框**,标签退化成占位符名(`brand_name` → `brand name`,浅色斜体标记)。
### `desc`:输入框里那句灰色提示
数据仓 `variables[].desc` 会被 `generate_data.py` 收进 `variable_descs`(按 `kv_var` 索引),插件把它当输入框的 placeholder:
| 数据 | 输入框表现 |
|---|---|
| 有 `desc` | 灰色提示「主体花卉,如:栀子花 / 白牡丹」,完整原文同时挂在 `title` 上,hover 看全 |
| 无 `desc` | 退回占位符名(`SUBJECT`),与旧版一致 |
超出输入框宽度的部分会被截断,hover 可看全。**提示文字不算已填**:留空的变量仍然原样保留 `{占位符}`,未填计数也不受影响。
输入框另外带 `data-var-name="占位符名"`——因为 `placeholder` 现在可能是中文说明,靠它反推槽位名会出错,测试和排错都认这个属性。
写新风格时要注意的:
1. 想被替换的地方一律用**半角花括号**包一个短标识符:`{主角}`、`{SUBJECT}`、`{brand_name}`;带引号/逗号/冒号的内容会被当成 JSON 碎片忽略。
2. 每个占位符在 `variables` 里补一条,标签写中文、值是占位符本体(`style_var: "{主角}"`),面板才会显示中文标签。
3. 别用 `[SQUARE_BRACKETS]`:16 个风格这么写,插件只认花括号,这些不会被替换。
4. `variables` 必须是**列表** `[{kv_var, style_var, desc?}]`;`generate_data.py` 只解析列表,写成 mapping 会被静默丢掉(`validate_style.py` 会报错)。
5. 标签里别留 markdown 反引号(Vigo 那批导入数据有 392 条 `` `SUBJECT` ``,插件会剥掉但源数据该改)。
数据体检脚本(在 [style-source](https://github.com/malongan/style-source) 仓):`python3 scripts/audit_variables.py [--strict]`,会列出声明落空、有占位符没声明、标签带残留的风格。当前 310 个风格:234 个含占位符、234 个有声明、76 个两者都无;声明命中 1411 条 / 落空 0 条。
> 数据侧的**强制性写法规范**在数据仓:[`docs/PROMPT_VARIABLES_SPEC.md`](https://github.com/malongan/style-source/blob/main/docs/PROMPT_VARIABLES_SPEC.md)。给收集提示词的 Agent 看的是那份,不是这里。
## 面板宽度自适应(重要)
资源库面板宽度不是固定的:侧栏 240–560 可拖、放大窗口 920×600 可八向缩放、还有 embedded 嵌入形态。所以:
- 网格列数交给 `repeat(auto-fill, minmax(112px, 1fr))`,不写死:面板越宽**只加列、不撑宽卡片**(1040 宽时一行 5 张,卡片仍是 ~122px)。
- 详情用 **480px 一个拐点**切两种形态(窄=覆盖层 / 宽=右侧栏),**同一个 DOM 只换定位** —— 切档时变量输入和滚动位置不丢。
- 宽档详情栏宽度 = `clamp(300px, 40%, 380px)`:**上限 380 是刻意的**,详情是「停下来看」的动作,栅格才是浏览主体,再宽就少一列。
- 判定用 `ResizeObserver` 而不是 `@media`:拖侧栏时视口没变,`@media` 完全不响应。
- 面板容器 `.iwb-full-panel-plugin` 在宿主 `style.css` 里**没有任何样式定义**(裸 div):
- 根元素自带 `width/height:100%; min-width/height:0; display:flex`;
- 容器自身补 `flex:1 1 0%`(**仅当它没有显式宽度、且父容器是 flex row 时**)—— 否则 flex 子项按内容宽收缩,
面板拉到 1040 时只占 664,右边留一大片空白;反过来若无条件设 flex,固定宽度的侧栏会被拉满父容器。
> 侧栏 ↔ 放大窗口是两个不同的 React 位置,同一个插件会被 `mount` 两次(不同 DOM 节点)。DOM 每次重建,但数据 / 图片 blob / 选中项 / 搜索词 / 变量输入都在模块级缓存里,切形态不会重拉 1.1MB JSON、不重下预览图、不丢选中。
## 设置项
| 键 | 说明 |
|---|---|
| `dataUrl` | styles.json 地址,默认 `https://malongan.github.io/style-source/data/styles.json`。国内访问慢可自行镜像后改这里。 |
| `promptMaxH` | 文本节点最大高度(px,默认 240,可填 120~800)。见下节。 |
## 长提示词:节点内滚动,不把画布撑爆
风格提示词动辄上千字。宿主 `renderPromptBody` 用 `autoGrow` 把 textarea 高度直接设成 `scrollHeight`(**没有上限**),
所以一条长提示词插进画布会变成一根两米高的柱子,一张卡吃掉整个视口。
插件在挂载时注入两条(幂等的)样式:
```css
/* 自动高节点:压住上限,高度来自设置项 promptMaxH */
.iwb-node:not(.iwb-node-fixed) .iwb-textarea-plain { max-height: 240px }
/* 用户手动拉过尺寸的节点(node.h 有值 → 宿主加 .iwb-node-fixed):让开上限,交给宿主拉伸规则 */
.iwb-node.iwb-node-fixed .iwb-textarea-plain { max-height: none }
```
- **默认**节点尺寸固定(≈ max-height + 内边距),插了几张卡一眼看清;
- 宿主 `.iwb-textarea` 本来就是 `overflow-y: auto`,超出的部分在节点内滚动,**内容一个字都不丢**;
- **手动拉过右下角缩放手柄**的节点不受上限约束:宿主 `.iwb-node-fixed .iwb-textarea{flex:1 1 auto;height:auto!important}`
会把文本域撑满节点,想多高就多高(⚠️ 前提是选择器带 `:not(.iwb-node-fixed)`——两条规则特异性同为 `(0,2,0)`,
且插件样式注入得更晚,不排除的话会把宿主的拉伸规则压掉,节点被拉高后文字仍卡在 240px,下面留一片空白);
- 想看全文照旧用节点气泡的「**放大编辑**」(⌘/Ctrl + E),那是不限高的浮层;
- 选择器只碰**节点内**的纯文本域,宿主的弹窗 / 设置面板(`.iwb-modal-lg .iwb-textarea`)不受影响。
> 这条规则在宿主 `style.css` 里补一次更「正」,但插件自带可以保证换宿主版本也生效;宿主自己后续若要收编,删掉插件里的 `ensureNodeCapStyle` 即可。
插图默认用 `preview_webp`(大图,清晰)。详情里勾「插图用缩略图」改用 `*.thumb.webp`,省画布体积(dataURL 会让存档膨胀约 33%)。
## 不需要改宿主 CSP
数据与图片都是公网 `https://`,宿主 `_headers` 的 `img-src … https:` / `connect-src … https:` 已经放行。对比 `ai-chat`(连本机 `http://127.0.0.1:3425`)必须单独加端口。
## 发布
`src/index.js` 是手写单文件 IIFE,不构建,直接发布:
```bash
cp src/index.js /tmp/plugin-style-source.js
cd ../image-workbench-web
node scripts/plugins-publish.mjs /tmp/plugin-<其余插件>.js /tmp/plugin-style-source.js --upload --version style-source=1.0.5
```
图标:宿主 `app.js` 的 `PLUGIN_ICONS` 可加 `'style-source': 'palette'`(不加则用面板 manifest 自带的 `palette`,效果一致)。
## 数据结构(上游 styles.json)
```jsonc
{
"meta": { "total": 310, "categories": ["brand_kv", "creative", …] },
"styles": [{
"id": "y3k_cool_girl_portrait",
"code": "ST0001",
"name": "Y3K 酷酷女孩",
"category": "creative",
"tags": ["Y3K", "赛博朋克"],
"triggers": ["Y3K", "酷女孩"],
"ratio": "9:21",
"summary": "……",
"features": ["……"],
"prompt": "……一个3D风格的虚拟{角色描述}半身肖像……",
"variables": { "画面-角色": "角色描述", "画面-诗词": "{诗词}" }, // value 可能自带花括号
"preview_webp": "https://…/xxx.webp",
"preview_webp_thumb": "https://…/xxx.thumb.webp",
"source_url": "https://jimeng.jianying.com/…",
"source_author": "卢西西"
}]
}
```
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/style-source",
"private": true,
"version": "1.2.0",
"description": "风格库:资源库面板里浏览 310 个 AI 绘画风格(12 分类 / 搜索 / 变量替换),一键把预览图插入画布 ref 节点、把提示词插入 prompt 节点",
"ibwPlugin": {
"id": "style-source",
"entry": "src/index.js",
"apiVersion": 1
}
}
File diff suppressed because it is too large. Load diff
+137
View File
@@ -0,0 +1,137 @@
// 风格库真实网络冒烟(开发用,不进 CI)。
//
// harness.mjs 用 page.route 把资源和图片都本地化了 —— 好处是离线可复现,坏处是**掩盖了 CORS**。
// 这个脚本不拦截任何请求,直接打真实 GitHub Pages,验证:
// 1) 线上 styles.json 能拉到 310 条(含真实体积 1.1MB)
// 2) 缩略图真的能在 <img> 里解码出来(naturalWidth > 0,说明 CORS + referrerpolicy 没问题)
// 3) 「插入参考图」能把真实 webp 转成 dataURL 交给画布(长度 > 5KB,说明不是空图)
//
// 运行:node style-source/tools/e2e-real.mjs
// 需要外网(走系统代理时给 Chromium 传 proxy 即可;脚本会自动读 HTTP(S)_PROXY)
import { createRequire } from 'node:module'
import { createServer } from 'node:http'
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')
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,设置 IWB_PLAYWRIGHT_ROOT 指向含 node_modules 的目录')
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 = 40000, step = 250) => {
const end = Date.now() + timeout
for (;;) {
const v = await fn()
if (v) return v
if (Date.now() > end) return null
await new Promise((r) => setTimeout(r, step))
}
}
const HTML = `<!doctype html><html><head><meta charset="utf-8">
<style>html,body{margin:0;height:100%}#stage{display:flex;height:100vh}</style></head>
<body><div id="stage"></div></body></html>`
async function main() {
const server = createServer((req, res) => { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); res.end(HTML) })
await new Promise((r) => server.listen(0, '127.0.0.1', r))
const port = server.address().port
const proxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy
const browser = await chromium.launch(proxy ? { proxy: { server: proxy } } : {})
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } })
const netFail = []
page.on('requestfailed', (req) => {
if (req.url().includes('malongan.github.io')) netFail.push(req.url().slice(-40) + ' ' + (req.failure() || {}).errorText)
})
const errors = []
page.on('pageerror', (e) => errors.push(String(e)))
await page.goto(`http://127.0.0.1:${port}/`)
await page.evaluate(() => {
window.__calls = { panels: [], images: [], nodes: [] }
window.__nodes = [{ id: 'n1', type: 'prompt', x: 100, y: 100, data: { text: 'x' } }]
window.__sel = { id: 'n1', type: 'prompt', name: 'x' }
window.IWBPluginHost = { register(m, s) { window.__m = m; window.__s = s } }
})
await page.addScriptTag({ path: PLUGIN_ENTRY })
await page.evaluate(() => {
const ctx = {
id: window.__m.id,
settings: { get: (k) => (window.__m.settings[k] || {}).default },
storage: null,
ui: { registerPanel: (p) => window.__calls.panels.push(p) },
canvas: {
getNodes: () => window.__nodes,
getSelectedNode: () => window.__sel,
createNode: (t, x, y, d) => { window.__calls.nodes.push({ t, x, y, d }); return 'n_new' },
createImageNode: (p) => { window.__calls.images.push(p); return 'n_img' },
},
}
window.__s(ctx)
const host = document.createElement('div')
host.id = 'h'
host.style.cssText = 'width:980px;height:720px;display:flex;min-width:0'
document.getElementById('stage').appendChild(host)
window.__calls.panels[0].mount(host)
})
const gotData = await poll(async () => {
const n = await page.locator('#h .iwb-ss-card').count()
return n > 0 ? n : null
})
check('真实网络拉到数据并渲染卡片', Boolean(gotData), 'cards=' + gotData)
const status = await page.locator('#h .iwb-ss-status').innerText().catch(() => '')
check('总数显示 310', /310/.test(status), status.replace(/\n/g, ' '))
// 真实缩略图必须真的解码出来
const decoded = await poll(async () => {
const n = await page.evaluate(() => {
const imgs = Array.from(document.querySelectorAll('#h .iwb-ss-thumb'))
return imgs.filter((i) => i.complete && i.naturalWidth > 0).length
})
return n >= 3 ? n : null
}, 45000)
check('缩略图真实解码成功(≥3 张 naturalWidth>0)', Boolean(decoded), 'decoded=' + decoded)
// 真实 webp → dataURL
await page.locator('#h .iwb-ss-card').first().click()
await page.waitForTimeout(300)
await page.locator('#h .iwb-ss-dfoot .iwb-ss-btn').first().click()
const img = await poll(() => page.evaluate(() => window.__calls.images[0] || null), 30000)
check('真实图插入画布(createImageNode 被调用)', Boolean(img))
check('dataURL 是真实内容而非空图', Boolean(img) && String(img.dataUrl).length > 5000,
img ? 'len=' + String(img.dataUrl).length + ' head=' + String(img.dataUrl).slice(0, 22) : '')
check('无 GitHub 资源请求失败', netFail.length === 0, netFail.slice(0, 2).join(' | '))
check('无页面 JS 异常', errors.length === 0, errors.slice(0, 2).join(' | '))
const shot = path.resolve(HERE, 'shot-real.png')
await page.locator('#h').screenshot({ path: shot }).catch(() => {})
console.log('· 真实截图:' + shot)
await browser.close()
server.close()
console.log('')
console.log(failed === 0 ? '全部通过' : failed + ' 项失败')
process.exit(failed === 0 ? 0 : 1)
}
main().catch((e) => { console.error('崩溃:', e); process.exit(1) })
+773
View File
@@ -0,0 +1,773 @@
// 风格库插件本地端到端(开发用,不进 CI)。
//
// 为什么需要它:面板布局随宽度变化、变量替换、插图(blob → dataURL → createImageNode)都是浏览器行为,node 侧测不了。
// 这里装一个合成宿主(可注入的 ctx + 面板容器),addScriptTag 加载插件源码本体,在真实 Chromium 里验证:
// 注册 / 面板注册 / 数据加载 / 分批渲染 / 窄宽两态布局 / ResizeObserver 切档 / 搜索 / 分类 / 变量替换 / 两个插入动作 / 重复 mount 幂等
//
// 网络完全本地化:page.route 拦截 GitHub Pages,styles.json 读本地文件,预览图返回 1×1 PNG。
// 所以这里测不到真实 CORS(数据源是 *,已在方案阶段用 curl 实测过)。
//
// 运行:
// node style-source/tools/harness.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import { createServer } from 'node:http'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/style-source/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')
const STYLES_JSON = '/Users/qiqi/open/github/style-source/data/styles.json'
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 style-source/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 = 15000, step = 80) => {
const end = Date.now() + timeout
for (;;) {
const v = await fn()
if (v) return v
if (Date.now() > end) return null
await new Promise((r) => setTimeout(r, step))
}
}
const PNG_1PX = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
'base64',
)
const PAGE_HTML = `<!doctype html><html><head><meta charset="utf-8">
<style>html,body{margin:0;height:100%;font-family:system-ui,sans-serif}
#stage{display:flex;align-items:stretch;height:100vh;padding:0}
/* 从宿主 style.css 抄的关键几条,否则「手动拉过尺寸的节点」这条测不出来 */
.iwb-node{display:flex;flex-direction:column;border:1px solid #d5d9e0;border-radius:14px;position:relative}
.iwb-node-body{padding:8px 10px;flex:1 1 auto;min-height:0}
.iwb-textarea{min-height:56px;overflow-y:auto;width:100%;box-sizing:border-box;resize:none}
.iwb-node-fixed .iwb-node-body{display:flex;flex-direction:column;overflow:visible;min-height:0}
.iwb-node-fixed .iwb-textarea{flex:1 1 auto;max-height:none;min-height:56px;height:auto !important}
</style></head>
<body><div id="stage"></div></body></html>`
async function main() {
const stylesParsed = JSON.parse(readFileSync(STYLES_JSON, 'utf8'))
const stylesCount = stylesParsed.styles.length
console.log('· 本地 styles.json:' + stylesCount + ' 条')
// 线上数据已经 100% 声明变量,真实风格里再没有「有占位符但没声明」的样本。
// 那条降级分支仍然必须覆盖(宿主可能拿到旧版 / 第三方数据),所以克隆一条探针风格注入,
// 只改 id/name/prompt/variables —— 其余字段沿用真实数据,卡片渲染逻辑不特殊化。
const probe = JSON.parse(JSON.stringify(stylesParsed.styles[0]))
probe.id = '__probe_undeclared'
probe.code = ''
probe.number = ''
probe.name = '探针:未声明占位符'
probe.summary = 'harness 注入的探针风格,用来覆盖「有占位符但没声明」的降级分支'
probe.prompt = 'probe {alpha_desc} / {beta_desc} / {gamma_desc}'
probe.variables = []
delete probe.variable_descs
// 第二个探针:一半变量有 desc、一半没有。整改后线上数据已经「有就全有、没就全没」,
// 拿真实风格测不到「没 desc 降级成占位符名」这条分支。
const probe2 = JSON.parse(JSON.stringify(stylesParsed.styles[0]))
probe2.id = '__probe_desc_mix'
probe2.code = ''
probe2.number = ''
probe2.name = '探针:desc 混合'
probe2.summary = 'harness 注入的探针风格,一半变量带 desc、一半不带'
probe2.prompt = 'probe2 {主体} {标题}'
// 注意:styles.json 里 variables 是 {kv_var: style_var} 的字典,不是数组
probe2.variables = { 主体: '{主体}', 标题: '{标题}' }
probe2.variable_descs = { 主体: '如:一只猫、一台相机' }
const stylesRaw = JSON.stringify({ ...stylesParsed, styles: [...stylesParsed.styles, probe, probe2] })
const server = createServer((req, res) => {
if (req.url === '/' || req.url.startsWith('/?')) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
res.end(PAGE_HTML)
return
}
res.writeHead(404); res.end('not found')
})
await new Promise((r) => server.listen(0, '127.0.0.1', r))
const port = server.address().port
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } })
let dataHits = 0
// 拦截上游静态资源:json 用本地文件,图片用 1×1 png(保证离线可复现)
await page.route('https://malongan.github.io/style-source/**', async (route) => {
const url = route.request().url()
const cors = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET,HEAD',
'cache-control': 'no-store',
}
if (url.includes('/data/styles.json')) {
dataHits++
await route.fulfill({ status: 200, headers: { ...cors, 'content-type': 'application/json' }, body: stylesRaw })
return
}
await route.fulfill({ status: 200, headers: { ...cors, 'content-type': 'image/png' }, body: PNG_1PX })
})
const errors = []
page.on('pageerror', (e) => errors.push(String(e)))
await page.goto(`http://127.0.0.1:${port}/`)
// ---- 合成宿主 ----
await page.evaluate(() => {
window.__calls = { nodes: [], images: [], panels: [], manifests: [], setups: 0 }
window.__nodes = [
{ id: 'n_prompt', type: 'prompt', x: 100, y: 120, data: { text: '原有提示词' } },
{ id: 'n_ref', type: 'ref', x: 520, y: 120, data: { name: '参考图' } },
]
window.__sel = { id: 'n_prompt', type: 'prompt', name: '原有提示词' }
// 宿主 findSpot 的最小复刻:视口 1280×900,从中心向外按环形扫,返回第一个不与已有节点相交的格子
window.__mockFindSpot = () => {
const CW = 1280, CH = 900, W = 320, H = 216, PAD = 20
const boxes = (window.__nodes || []).map((n) => ({ x: n.x, y: n.y, w: 320, h: 216 }))
const hit = (x, y) => boxes.some((b) => x < b.x + b.w && x + W > b.x && y < b.y + b.h && y + H > b.y)
const cx = CW / 2 - W / 2, cy = CH / 2 - H / 2
for (let ring = 0; ring <= 6; ring++) {
for (let dy = -ring; dy <= ring; dy++) {
for (let dx = -ring; dx <= ring; dx++) {
if (Math.max(Math.abs(dx), Math.abs(dy)) !== ring) continue
const x = Math.round(cx + dx * (W + PAD)), y = Math.round(cy + dy * (H + PAD))
if (!hit(x, y)) return { x, y, noOverlap: true }
}
}
}
return { x: Math.round(cx), y: Math.round(cy), noOverlap: false }
}
window.IWBPluginHost = {
register(manifest, setup) {
window.__calls.manifests.push(manifest)
window.__calls.setups++
window.__manifest = manifest
window.__setup = setup
},
}
})
await page.addScriptTag({ path: PLUGIN_ENTRY })
const registered = await page.evaluate(() => Boolean(window.__setup))
check('插件调用 IWBPluginHost.register', registered)
if (!registered) { await finish(); return }
const manifest = await page.evaluate(() => {
const m = window.__manifest
return { id: m.id, name: m.name, version: m.version, apiVersion: m.apiVersion, caps: m.capabilities, hasDataUrl: Boolean(m.settings && m.settings.dataUrl) }
})
// 版本号从 package.json 读,不写死:写死时改版本忘了同步 manifest,CI 会报错但这里不会
const pkgVersion = JSON.parse(readFileSync(path.resolve(HERE, '../package.json'), 'utf8')).version
check('manifest id/version 与 package.json 一致',
manifest.id === 'style-source' && manifest.version === pkgVersion,
JSON.stringify({ id: manifest.id, manifest: manifest.version, pkg: pkgVersion }))
check('capabilities 含 panels+canvas+canvasWrite',
['panels', 'canvas', 'canvasWrite'].every((c) => manifest.caps.includes(c)), manifest.caps.join(','))
check('settings 暴露 dataUrl', manifest.hasDataUrl)
// ---- 建面板(窄:320) ----
const mounted = await page.evaluate(() => {
const ctx = {
id: window.__manifest.id,
settings: { get: (k) => (window.__manifest.settings[k] || {}).default },
storage: null,
ui: { registerPanel: (p) => { window.__calls.panels.push(p) } },
canvas: {
getNodes: () => window.__nodes,
getSelectedNode: () => window.__sel,
// 模拟宿主新语义:x/y 为 null/undefined ⇒ 走 findSpot(视口中心起螺旋找空位、避开已有节点)
createNode: (type, x, y, data) => {
const auto = x === null || x === undefined || y === null || y === undefined
const rec = { type, x, y, data, auto }
if (auto) {
const s = window.__mockFindSpot()
rec.x = s.x
rec.y = s.y
rec.noOverlap = s.noOverlap
}
window.__calls.nodes.push(rec)
return 'n_new_' + window.__calls.nodes.length
},
createImageNode: (payload) => { window.__calls.images.push(payload); return 'n_img_' + window.__calls.images.length },
// 模拟宿主新能力(2026-11-02):屏幕坐标 → 世界坐标。
// 视口口径:画布容器左上角 (320,0),平移 (100,-50),缩放 0.5
screenToWorld: (clientX, clientY) => ({ x: (clientX - 320 - 100) / 0.5, y: (clientY - 0 + 50) / 0.5, scale: 0.5 }),
},
}
window.__setup(ctx)
const panel = window.__calls.panels[0]
const stage = document.getElementById('stage')
const host = document.createElement('div')
host.id = 'hostA'
host.style.cssText = 'width:320px;height:640px'
stage.appendChild(host)
panel.mount(host)
window.__hostA = host
return { panelId: panel && panel.id, title: panel && panel.title, icon: panel && panel.icon }
})
check('注册面板「风格库」+ palette 图标', mounted.title === '风格库' && mounted.icon === 'palette', JSON.stringify(mounted))
// ---- 长提示词:节点内滚动(宿主 autoGrow 把 textarea 撑成 scrollHeight,一条长提示词能拉成一米高) ----
const cap = await page.evaluate(() => {
const st = document.getElementById('iwb-ss-nodecap')
if (!st) return { injected: false }
// 造一个和宿主一致的节点结构,验证 max-height 真能压住内联 height
const wrap = document.createElement('div')
wrap.className = 'iwb-node'
wrap.style.cssText = 'width:280px;display:flex;flex-direction:column'
const ta = document.createElement('textarea')
ta.className = 'iwb-textarea iwb-textarea-plain'
ta.style.height = '1200px' // autoGrow 的产物
ta.value = 'x'.repeat(4000)
wrap.appendChild(ta)
document.getElementById('stage').appendChild(wrap)
const h = Math.round(ta.getBoundingClientRect().height)
const oy = getComputedStyle(ta).overflowY
wrap.remove()
return { injected: true, css: st.textContent, cappedH: h, overflowY: oy }
})
check('注入文本节点高度上限样式', cap.injected && /max-height:\s*240px/.test(String(cap.css)), String(cap.css))
check('内联 height=1200 的文本域被压到 240(节点不再被拉长)', cap.cappedH > 0 && cap.cappedH <= 260, 'h=' + cap.cappedH + '(240 内容 + 边框)')
check('超出部分在文本域内滚动', cap.overflowY === 'auto', cap.overflowY)
// 回归守门:默认只压「自动高」的节点;用户手动拉过尺寸(node.h → .iwb-node-fixed)时不能压,
// 否则节点被拉高一米,文字还卡在 240px,下面留一大片空白
const stretched = await page.evaluate(() => {
const wrap = document.createElement('div')
wrap.className = 'iwb-node iwb-node-fixed' // node.h 有值 → 宿主加这个 class
wrap.style.cssText = 'width:280px;min-height:520px'
const body = document.createElement('div')
body.className = 'iwb-node-body'
const ta = document.createElement('textarea')
ta.className = 'iwb-textarea iwb-textarea-plain'
ta.style.height = '1200px'
ta.value = 'x'.repeat(4000)
body.appendChild(ta)
wrap.appendChild(body)
document.getElementById('stage').appendChild(wrap)
const r = {
nodeH: Math.round(wrap.getBoundingClientRect().height),
taH: Math.round(ta.getBoundingClientRect().height),
cap: getComputedStyle(ta).maxHeight,
}
wrap.remove()
return r
})
check('手动拉高节点后文本域跟着撑满(不再卡在 240)',
stretched.taH > stretched.nodeH * 0.6, 'node=' + stretched.nodeH + ' textarea=' + stretched.taH + ' maxH=' + stretched.cap)
check('手动拉高节点时上限被让开', stretched.cap === 'none', stretched.cap)
// ---- 数据加载 ----
const loaded = await poll(async () => {
const txt = await page.locator('.iwb-ss-status').innerText().catch(() => '')
return /共 \d+ 个风格/.test(txt) ? txt : null
})
check('数据加载完成并显示总数', Boolean(loaded), loaded || '超时')
check('styles.json 只拉了一次', dataHits === 1, 'hits=' + dataHits)
const cards = await page.locator('#hostA .iwb-ss-card').count()
check('分批渲染首批卡片(' + cards + ' 张,应为 PAGE_SIZE=90)', cards === 90, 'cards=' + cards)
const chipCount = await page.locator('#hostA .iwb-ss-chip').count()
check('分类 chips = 全部 + 12 类', chipCount === 13, 'chips=' + chipCount)
// 回归守门:grid-auto-rows 默认 auto 会让图片未加载时的行高塌成一行文字,卡片被裁成横杠
const geom = await page.evaluate(() => {
const card = document.querySelector('#hostA .iwb-ss-card')
const img = card.querySelector('.iwb-ss-thumb')
const name = card.querySelector('.iwb-ss-cardname')
const h = (e) => Math.round(e.getBoundingClientRect().height)
return { cardH: h(card), imgH: h(img), nameH: h(name), name: name.textContent }
})
check('卡片高度容纳图片 + 文字(grid-auto-rows 守门)', geom.cardH >= geom.imgH + 20,
'card=' + geom.cardH + ' img=' + geom.imgH)
check('卡片名称可见', geom.nameH >= 10 && geom.name.length > 0, geom.name + ' / h=' + geom.nameH)
// 回归守门:13 个 chip 不换行,max-content 近 950px,要把祖先容器顶宽(真实宿主窗口只有 680,右侧全被裁)
const ov1 = await page.evaluate(() => {
const r = document.querySelector('#hostA .iwb-ss-root')
return { sw: r.scrollWidth, cw: r.clientWidth }
})
check('窄档无水平溢出(chip max-content 不顶宽容器)', ov1.sw <= ov1.cw + 1, 'scrollW=' + ov1.sw + ' clientW=' + ov1.cw)
// ---- 分类 chips 自适应换行 ----
// 以前 chips 是「单行 + 横向滚动 + scrollbar 隐藏」:面板拖窄时右边几类永远看不见,用户以为只有 7 个分类。
// 现在改 flex-wrap,这里守住两件事:所有 chip 都落在 chips 容器内(不被裁),且容器没有横向滚动条。
const measureChips = () => page.evaluate(() => {
const box = document.querySelector('#hostA .iwb-ss-chips')
const all = Array.from(box.querySelectorAll('.iwb-ss-chip'))
const bb = box.getBoundingClientRect()
const rows = new Set(all.map((c) => Math.round(c.getBoundingClientRect().top))).size
const outside = all.filter((c) => {
const r = c.getBoundingClientRect()
return r.right > bb.right + 1 || r.left < bb.left - 1 || r.bottom > bb.bottom + 1
}).length
const countShown = all[0] ? getComputedStyle(all[0].querySelector('.iwb-ss-chipn')).display !== 'none' : false
return { count: all.length, rows, outside, sw: box.scrollWidth, cw: box.clientWidth, h: Math.round(bb.height), countShown }
})
const chipsNarrow = await measureChips()
check('窄档 chips 全部落在容器内(换行而非横向滚动)',
chipsNarrow.outside === 0 && chipsNarrow.sw <= chipsNarrow.cw + 1,
JSON.stringify(chipsNarrow))
check('窄档 chips 折成多行', chipsNarrow.rows >= 2, 'rows=' + chipsNarrow.rows + ' h=' + chipsNarrow.h)
check('窄档隐藏数量后缀(省一行高度)', chipsNarrow.countShown === false)
// ---- 默认窄档 ----
const layoutNarrow = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
check('320px 初始为 narrow', layoutNarrow === 'narrow', String(layoutNarrow))
// ---- 选中第一张卡:窄档详情应为覆盖层 ----
await page.locator('#hostA .iwb-ss-card').first().click()
await page.waitForTimeout(120)
const narrowDetail = await page.evaluate(() => {
const root = window.__hostA.querySelector('.iwb-ss-root')
const d = root.querySelector('.iwb-ss-detail')
const cs = getComputedStyle(d)
const rb = root.getBoundingClientRect()
const db = d.getBoundingClientRect()
return { open: d.classList.contains('is-open'), position: cs.position, display: cs.display, coverW: Math.round(db.width), rootW: Math.round(rb.width) }
})
check('窄档选中后详情为覆盖层', narrowDetail.open && narrowDetail.position === 'absolute' && narrowDetail.display === 'flex',
JSON.stringify(narrowDetail))
check('覆盖层宽度等于面板宽度', Math.abs(narrowDetail.coverW - narrowDetail.rootW) <= 1, narrowDetail.coverW + ' vs ' + narrowDetail.rootW)
// ---- 变量替换 ----
const varResult = await page.evaluate(() => {
const inputs = Array.from(window.__hostA.querySelectorAll('.iwb-ss-varinput'))
if (!inputs.length) return { hasVars: false }
const first = inputs[0]
const name = first.getAttribute('placeholder')
first.value = '测试角色ABC'
first.dispatchEvent(new Event('input', { bubbles: true }))
const preview = window.__hostA.querySelector('.iwb-ss-text').textContent
return { hasVars: true, name, preview, replaced: preview.includes('测试角色ABC'), stillHasPlaceholder: preview.includes('{' + name + '}') }
})
check('详情渲染变量输入框', varResult.hasVars, varResult.name ? '第一个变量:{' + varResult.name + '}' : '')
check('填变量后预览实时替换', Boolean(varResult.replaced))
check('已填变量不再残留占位符', varResult.hasVars && !varResult.stillHasPlaceholder)
// ---- 插提示词 ----
await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').nth(1).click()
await page.waitForTimeout(120)
const promptCall = await page.evaluate(() => window.__calls.nodes[0] || null)
check('插入提示词调用 createNode', Boolean(promptCall) && promptCall.type === 'prompt', promptCall ? 'type=' + promptCall.type : '未调用')
check('提示词带变量替换结果', Boolean(promptCall) && String(promptCall.data.text).includes('测试角色ABC'))
check('提示词坐标交给宿主(插件不自己算,拿不到 pan/zoom)',
Boolean(promptCall) && promptCall.auto === true,
promptCall ? 'auto=' + promptCall.auto + ' raw=(' + promptCall.x + ',' + promptCall.y + ')' : '未调用')
check('宿主定位结果不压在已有节点上',
Boolean(promptCall) && promptCall.noOverlap === true,
promptCall ? '(' + promptCall.x + ',' + promptCall.y + ')' : '')
// ---- 拖拽插入:按住「插入提示词」拖到画布上松手 ⇒ 节点落在松手点 ----
await page.evaluate(() => {
// 造一块 .iwb-canvas(插件靠 elementFromPoint + closest('.iwb-canvas') 判断「是否在画布上」)
const cv = document.createElement('div')
cv.className = 'iwb-canvas'
cv.id = 'fakeCanvas'
cv.style.cssText = 'position:fixed;left:320px;top:0;width:900px;height:640px;z-index:1;background:#eee'
document.body.appendChild(cv)
window.__calls.nodes.length = 0
})
const btnBox = await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').nth(1).boundingBox()
const dropX = 700
const dropY = 300
await page.mouse.move(btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2)
await page.mouse.down()
await page.mouse.move(dropX - 60, dropY - 40, { steps: 6 })
const ghost = await page.evaluate(() => {
const g = document.querySelector('.iwb-ss-ghost')
return g ? { text: g.textContent, over: g.classList.contains('is-over'), pe: getComputedStyle(g).pointerEvents } : null
})
check('拖拽中出现跟随光标的幽灵卡片', Boolean(ghost), ghost ? ghost.text : '未出现')
check('幽灵卡片 pointer-events:none(不挡 elementFromPoint)', Boolean(ghost) && ghost.pe === 'none', ghost ? ghost.pe : '')
check('拖到画布上时幽灵提示「松手放这里」', Boolean(ghost) && ghost.over === true, ghost ? ghost.text : '')
await page.mouse.move(dropX, dropY, { steps: 4 })
await page.mouse.up()
await page.waitForTimeout(150)
const dragCall = await page.evaluate(() => window.__calls.nodes[0] || null)
const expectX = (dropX - 320 - 100) / 0.5
const expectY = (dropY + 50) / 0.5
check('拖拽松手 ⇒ createNode 带显式坐标(不再交给宿主猜)',
Boolean(dragCall) && dragCall.auto === false, dragCall ? 'auto=' + dragCall.auto : '未调用')
check('落点 = 松手点换算出的世界坐标',
Boolean(dragCall) && Math.abs(dragCall.x - expectX) < 1 && Math.abs(dragCall.y - expectY) < 1,
dragCall ? '(' + dragCall.x + ',' + dragCall.y + ') 期望 (' + expectX + ',' + expectY + ')' : '未调用')
check('拖拽只插入一次(松手后的 click 被抑制)',
await page.evaluate(() => window.__calls.nodes.length === 1),
'调用次数=' + await page.evaluate(() => window.__calls.nodes.length))
// 松手在面板里(不在画布上)⇒ 取消,不建节点
await page.mouse.move(btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2)
await page.mouse.down()
await page.mouse.move(btnBox.x + 40, btnBox.y - 60, { steps: 4 })
await page.mouse.up()
await page.waitForTimeout(150)
check('松手点不在画布上 ⇒ 不建节点', await page.evaluate(() => window.__calls.nodes.length === 1),
'调用次数=' + await page.evaluate(() => window.__calls.nodes.length))
await page.evaluate(() => { const cv = document.getElementById('fakeCanvas'); if (cv) cv.remove(); window.__calls.nodes.length = 0 })
// ---- 插参考图(blob → dataURL) ----
await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').first().click()
const imgCall = await poll(() => page.evaluate(() => window.__calls.images[0] || null), 8000)
check('插入参考图调用 createImageNode', Boolean(imgCall))
check('传入的是 data: URL(宿主只认这个)', Boolean(imgCall) && /^data:image\//.test(String(imgCall.dataUrl)), imgCall ? String(imgCall.dataUrl).slice(0, 24) + '…' : '')
check('节点名带风格编号', Boolean(imgCall) && /^ST\d+_/.test(String(imgCall.name)), imgCall ? imgCall.name : '')
// ---- 拉宽到 980:详情应切成右侧栏 ----
await page.evaluate(() => { window.__hostA.style.width = '980px' })
const wideLayout = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'wide' ? v : null
})
check('拉宽到 980 后 data-layout=wide(ResizeObserver 生效)', Boolean(wideLayout))
const wideDetail = await page.evaluate(() => {
const root = window.__hostA.querySelector('.iwb-ss-root')
const d = root.querySelector('.iwb-ss-detail')
const cs = getComputedStyle(d)
const rb = root.getBoundingClientRect()
const db = d.getBoundingClientRect()
return { position: cs.position, flexBasis: cs.flexBasis, ratio: db.width / rb.width, cols: getComputedStyle(root.querySelector('.iwb-ss-grid')).gridTemplateColumns.split(' ').length }
})
check('宽档详情为右侧栏(非 absolute)', wideDetail.position !== 'absolute', wideDetail.position)
check('宽档详情占比约 46%', wideDetail.ratio > 0.3 && wideDetail.ratio < 0.5, wideDetail.ratio.toFixed(2))
check('宽档网格列数增加', wideDetail.cols >= 4, 'cols=' + wideDetail.cols)
const ov2 = await page.evaluate(() => {
const r = document.querySelector('#hostA .iwb-ss-root')
return { sw: r.scrollWidth, cw: r.clientWidth }
})
check('宽档无水平溢出', ov2.sw <= ov2.cw + 1, 'scrollW=' + ov2.sw + ' clientW=' + ov2.cw)
const chipsWide = await measureChips()
check('宽档 chips 一行铺完(不再溢出到右侧看不见)',
chipsWide.rows === 1 && chipsWide.outside === 0,
JSON.stringify(chipsWide))
check('宽档恢复显示数量后缀', chipsWide.countShown === true)
// ---- 恢复窄档,测边界:479/480 ----
await page.evaluate(() => { window.__hostA.style.width = '479px' })
const at479 = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'narrow' ? v : null
})
await page.evaluate(() => { window.__hostA.style.width = '480px' })
const at480 = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'wide' ? v : null
})
check('拐点精确:479=narrow / 480=wide', Boolean(at479) && Boolean(at480))
// ---- 搜索 ----
await page.evaluate(() => { window.__hostA.style.width = '320px' })
await page.locator('#hostA .iwb-ss-search').fill('Y3K')
await page.waitForTimeout(320)
const searchState = await page.evaluate(() => ({
status: window.__hostA.querySelector('.iwb-ss-status').firstChild.textContent,
cards: window.__hostA.querySelectorAll('.iwb-ss-card').length,
}))
check('搜索「Y3K」过滤生效', /找到 \d+ 个/.test(searchState.status) && searchState.cards > 0 && searchState.cards < 90,
searchState.status + ' / ' + searchState.cards + ' 张')
// ---- 分类筛选 ----
await page.locator('#hostA .iwb-ss-search').fill('')
await page.waitForTimeout(280)
const clickCat = await page.evaluate(() => {
const chips = Array.from(window.__hostA.querySelectorAll('.iwb-ss-chip'))
const target = chips.find((c) => c.textContent.startsWith('电商'))
if (!target) return null
target.click()
return target.textContent
})
await page.waitForTimeout(160)
const catState = await page.evaluate(() => ({
on: (window.__hostA.querySelector('.iwb-ss-chip.is-on') || {}).textContent || '',
status: window.__hostA.querySelector('.iwb-ss-status').firstChild.textContent,
}))
check('点分类「电商」后 chips 高亮切换', Boolean(clickCat) && catState.on.startsWith('电商'), clickCat + ' → ' + catState.on)
check('分类筛选改变了结果数', /找到 \d+ 个/.test(catState.status), catState.status)
// ---- 变量来源:只认提示词里真实出现的 {占位符} ----
// 线上 970 条 variables 里有 625 条的值只是人话描述(没有花括号),按声明表造输入框时全都对不上号 ⇒
// 「有的有、有的没有」;反过来还有 78 个风格提示词里明明有 {xxx} 却一条都没声明。
// 现在统一从提示词抽,声明表只用来配中文标签(并兼容 key 上带反引号的脏数据)。
const openBySearch = async (q) => {
// 窄档里详情是**覆盖层**,不先关掉会挡住栅格,点不到卡片
await page.evaluate(() => {
const box = window.__hostA.querySelector('.iwb-ss-detail.is-open')
const close = box && box.querySelector('.iwb-ss-dclose')
if (close) close.click()
const all = document.querySelector('#hostA .iwb-ss-chip')
if (all && !all.classList.contains('is-on')) all.click()
})
await page.waitForTimeout(140)
await page.locator('#hostA .iwb-ss-search').fill(q)
await page.waitForTimeout(340)
await page.locator('#hostA .iwb-ss-card').first().click()
await page.waitForTimeout(140)
return page.evaluate(() => {
const box = window.__hostA.querySelector('.iwb-ss-detail')
const inputs = Array.from(box.querySelectorAll('.iwb-ss-varinput'))
const preview = (box.querySelector('.iwb-ss-text') || {}).textContent || ''
// 占位符名一律从 data-var-name 取:placeholder 现在可能是 desc 说明文字,
// 拿它反推槽位名会把「有 desc 的风格」全判成声明落空
const varNameOf = (i) => i.getAttribute('data-var-name') || i.getAttribute('placeholder')
const names = inputs.map(varNameOf)
return {
name: ((box.querySelector('.iwb-ss-dtitle') || {}).textContent || '').trim(),
labels: Array.from(box.querySelectorAll('.iwb-ss-varlabel')).map((e) => e.textContent),
pairs: inputs.map((i) => ({
name: varNameOf(i),
label: (i.parentNode.querySelector('.iwb-ss-varlabel') || {}).textContent || '',
placeholder: i.getAttribute('placeholder') || '',
title: i.getAttribute('title') || '',
implicit: Boolean(i.parentNode.querySelector('.iwb-ss-varlabel.is-implicit')),
})),
names: names,
visible: inputs.filter((i) => i.getBoundingClientRect().height > 0).length,
dead: names.filter((n) => preview.indexOf('{' + n + '}') < 0).length,
hasVarLabel: Array.from(box.querySelectorAll('.iwb-ss-label')).some((e) => e.textContent.indexOf('变量') >= 0),
hasToggle: Boolean(box.querySelector('.iwb-ss-vartoggle')),
}
})
}
const undeclared = await openBySearch('探针:未声明占位符')
check('提示词有占位符、数据没声明的风格也有输入框',
undeclared.names.length === 3 && undeclared.dead === 0, undeclared.name + ' → ' + undeclared.names.join(','))
check('每个输入框都有可读标签(不是空串/裸花括号)',
undeclared.pairs.length === 3 &&
undeclared.pairs.every((p) => p.label.trim().length > 0 && !/[{}]/.test(p.label)),
undeclared.pairs.map((p) => p.label + '→{' + p.name + '}').join(', '))
check('没声明的槽位按「未声明」处理(标签回退成占位符名)',
undeclared.pairs.every((p) => p.implicit && p.label === p.name.replace(/[_-]+/g, ' ')),
undeclared.pairs.map((p) => p.label + (p.implicit ? '(implicit)' : '') ).join(', '))
// 线上 1411 条声明已全部中文化,{SUBJECT} 这类脏 key 现在能认得中文标签「画面主体」
const vigo = await openBySearch('黄黑漫画食品小志广告风格')
const subj = vigo.pairs.find((p) => p.name === 'SUBJECT')
check('脏 key 的反引号被剥掉,占位符 {SUBJECT} 认回声明过的中文标签',
Boolean(subj) && subj.label === '画面主体' && !subj.implicit,
subj ? subj.label + ' → {' + subj.name + '}' + (subj.implicit ? '(按未声明处理)' : '') : '没有 SUBJECT 输入框')
check('声明表不会凭空造输入框(每个输入框都能在提示词里找到)',
vigo.dead === 0, 'inputs=' + vigo.names.length + ' dead=' + vigo.dead)
const mondrian = await openBySearch('蒙德里安秩序风')
check('中英文混写的 kv_var 都能对上声明(8 个全部 declared)',
mondrian.names.length === 8 && mondrian.pairs.every((p) => !p.implicit && p.label.indexOf('`') < 0),
mondrian.pairs.slice(0, 3).map((p) => p.label + '→{' + p.name + '}').join(', '))
check('变量全部平铺:8 个输入框全可见,且没有折叠按钮',
mondrian.names.length === 8 && mondrian.visible === 8 && mondrian.hasToggle === false,
'全部=' + mondrian.names.length + ' 可见=' + mondrian.visible + ' 折叠按钮=' + mondrian.hasToggle)
const noVar = await openBySearch('旷野的风')
check('提示词里没有占位符就不摆空输入框',
noVar.names.length === 0 && noVar.hasVarLabel === false, noVar.name + ' inputs=' + noVar.names.length)
// desc(variable_descs):有说明的变量用中文说明当灰色提示,没有的降级成占位符名
const withDesc = await openBySearch('东方花茶香氛海报')
const hasDesc = withDesc.pairs.filter((p) => p.placeholder && p.placeholder !== p.name)
check('desc 全覆盖的风格:每个输入框都拿到了说明',
hasDesc.length === withDesc.pairs.length && hasDesc.length > 0,
'inputs=' + withDesc.pairs.length + ' 带 desc=' + hasDesc.length)
const descMix = await openBySearch('探针:desc 混合')
const noDesc = descMix.pairs.filter((p) => p.placeholder === p.name)
check('带 desc 的变量用 desc 做 placeholder,而不是英文占位符名',
hasDesc.length > 0 && hasDesc.every((p) => /[\u4e00-\u9fa5]/.test(p.placeholder)),
hasDesc.slice(0, 3).map((p) => p.label + ' → 「' + p.placeholder.slice(0, 22) + '」').join(' | '))
check('完整 desc 同时挂在 title 上(长说明能看全)',
hasDesc.length > 0 && hasDesc.every((p) => p.title === p.placeholder),
hasDesc[0] ? '样例:' + hasDesc[0].title : '没有带 desc 的变量')
check('没有 desc 的变量降级成占位符名,不留空 placeholder',
noDesc.length === 1 && noDesc[0].placeholder === '标题' && descMix.pairs.length === 2,
descMix.pairs.map((p) => p.label + '→' + p.placeholder).join(', '))
check('加了 desc 后仍能正确算出未填数量(不把提示文字当成已填内容)',
withDesc.names.length === withDesc.pairs.length && withDesc.dead === 0,
'inputs=' + withDesc.names.length + ' dead=' + withDesc.dead)
await page.locator('#hostA .iwb-ss-search').fill('')
await page.waitForTimeout(200)
// ---- 多容器并存(宿主侧栏 + 放大窗口可能同时渲染同一插件面板) ----
// 早期版本用单个全局 dom 指针,第二个容器一挂载就把第一个容器的 RO 断掉 —— 这里专门守住这条
const dual = await page.evaluate(() => {
const stage = document.getElementById('stage')
const hostB = document.createElement('div')
hostB.id = 'hostB'
hostB.style.cssText = 'width:920px;height:600px'
stage.appendChild(hostB)
window.__calls.panels[0].mount(hostB)
window.__hostB = hostB
return {
rootsA: window.__hostA.querySelectorAll('.iwb-ss-root').length,
rootsB: hostB.querySelectorAll('.iwb-ss-root').length,
cardsB: hostB.querySelectorAll('.iwb-ss-card').length,
layoutB: hostB.querySelector('.iwb-ss-root').getAttribute('data-layout'),
}
})
check('两个容器各有且仅有一份根节点', dual.rootsA === 1 && dual.rootsB === 1, JSON.stringify({ a: dual.rootsA, b: dual.rootsB }))
check('第二个容器复用缓存(不重拉就有卡片)', dual.cardsB > 0, 'cards=' + dual.cardsB)
// 首帧同步判定,第二容器应该挂载即 wide(不该先闪一帧 narrow)
check('第二个容器 920px 挂载即判定 wide', dual.layoutB === 'wide', String(dual.layoutB))
check('styles.json 总计仍只请求过一次', dataHits === 1, 'hits=' + dataHits)
// ---- 回归守门:宿主资源中心的容器是 flex 子项,插件容器不能「按内容宽度收缩」 ----
// 真实宿主:.iwb-full-main{display:flex} > .iwb-full-panel-plugin(裸 div,无 width)。
// 之前只给了 min-width:0,容器按内容算出 664px,而父容器 1040 ⇒ 右侧留一大片空白。
const flexFill = await page.evaluate(() => {
const stage = document.getElementById('stage')
const wrap = document.createElement('div')
// position:fixed 让它脱离 stage 的 flex 布局(stage 已被 hostA/hostB 占满,放进去会被 shrink 压窄);
// pointer-events:none 防止它盖住 hostA 导致后续点击超时。
// 尺寸按用户实际场景取:总宽 1360 - 左栏 320 = 面板 1040
wrap.style.cssText = 'display:flex;position:fixed;left:0;top:0;width:1360px;height:640px;z-index:9999;background:#fff;pointer-events:none'
const left = document.createElement('div')
left.style.cssText = 'flex:0 0 320px'
const hostC = document.createElement('div')
hostC.id = 'hostC'
wrap.appendChild(left)
wrap.appendChild(hostC)
stage.appendChild(wrap)
window.__hostC = hostC
window.__calls.panels[0].mount(hostC)
const r = hostC.querySelector('.iwb-ss-root')
const grid = hostC.querySelector('.iwb-ss-grid')
return {
hostW: Math.round(hostC.getBoundingClientRect().width),
rootW: Math.round(r.getBoundingClientRect().width),
gridW: Math.round(grid.getBoundingClientRect().width),
avail: 1360 - 320,
}
})
check('flex 父容器下插件容器撑满剩余宽度(不再按内容宽度收缩)',
Math.abs(flexFill.rootW - flexFill.avail) <= 2 && Math.abs(flexFill.hostW - flexFill.avail) <= 2,
'host=' + flexFill.hostW + ' root=' + flexFill.rootW + ' 可用=' + flexFill.avail)
// 选中一个风格再量:宽档是「左栅格 + 右详情」常驻两栏,两栏之和必须等于容器宽,否则右边就是空白
await page.evaluate(() => {
const c = window.__hostC.querySelector('.iwb-ss-card')
if (c) c.click()
})
await page.waitForTimeout(320)
const flexCols = await page.evaluate(() => {
const hostC = window.__hostC
const q = (s) => Math.round(hostC.querySelector(s).getBoundingClientRect().width)
const cards = Array.from(hostC.querySelectorAll('.iwb-ss-card'))
const first = cards[0]
const det = hostC.querySelector('.iwb-ss-detail')
const foot = hostC.querySelector('.iwb-ss-dfoot')
const btn = hostC.querySelectorAll('.iwb-ss-dfoot .iwb-ss-btn')
// 同一行的卡片数 = 与第一张 top 相同的卡片数;卡片宽度用来确认「拉宽只加列、不撑宽卡片」
return {
root: q('.iwb-ss-root'),
grid: q('.iwb-ss-grid'),
detail: q('.iwb-ss-detail'),
detailSW: det ? det.scrollWidth : 0,
footW: foot ? Math.round(foot.getBoundingClientRect().width) : 0,
footSW: foot ? foot.scrollWidth : 0,
btnW: btn.length ? Array.from(btn).map((b) => Math.round(b.getBoundingClientRect().width)) : [],
btnSW: btn.length ? Array.from(btn).map((b) => b.scrollWidth) : [],
btnFs: btn.length ? Array.from(btn).map((b) => getComputedStyle(b).fontSize) : [],
bodyW: hostC.querySelector('.iwb-ss-dbody') ? Math.round(hostC.querySelector('.iwb-ss-dbody').getBoundingClientRect().width) : 0,
bodySW: hostC.querySelector('.iwb-ss-dbody') ? hostC.querySelector('.iwb-ss-dbody').scrollWidth : 0,
cardW: first ? Math.round(first.getBoundingClientRect().width) : 0,
perRow: cards.filter((c) => Math.abs(c.getBoundingClientRect().top - first.getBoundingClientRect().top) < 2).length,
}
})
check('宽档两栏横向无空白(栅格 + 详情 = 容器宽)',
Math.abs(flexCols.grid + flexCols.detail - flexCols.root) <= 2,
'grid=' + flexCols.grid + ' detail=' + flexCols.detail + ' root=' + flexCols.root)
check('面板 1040 时栅格一行 ≥4 张,且卡片不被撑宽(越宽只加列)',
flexCols.perRow >= 4 && flexCols.cardW > 90 && flexCols.cardW <= 150,
'每行=' + flexCols.perRow + ' 卡片宽=' + flexCols.cardW)
check('详情栏内部不横向溢出(按钮/长标签不撑出右边缘)',
flexCols.detailSW <= flexCols.detail + 1 && flexCols.footSW <= flexCols.footW + 1,
'detail=' + flexCols.detail + '/sw' + flexCols.detailSW + ' body=' + flexCols.bodyW + '/sw' + flexCols.bodySW +
' foot=' + flexCols.footW + '/sw' + flexCols.footSW + ' btn=' + JSON.stringify(flexCols.btnW) +
'/sw' + JSON.stringify(flexCols.btnSW) + '/fs' + JSON.stringify(flexCols.btnFs))
await page.locator('#hostC').screenshot({ path: path.resolve(HERE, 'shot-fill.png') }).catch(() => {})
await page.locator('#hostC .iwb-ss-detail').screenshot({ path: path.resolve(HERE, 'shot-detail.png') }).catch(() => {})
// hostB 挂载后,hostA 的 ResizeObserver 必须仍然有效(这是被抢指针时最先坏掉的地方)
await page.evaluate(() => { window.__hostA.style.width = '700px' })
const aStillAlive = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'wide' ? v : null
})
check('hostB 存在时 hostA 仍响应宽度变化', Boolean(aStillAlive))
// ---- 截图留档(先移除 hostB,否则 flex 会把 hostA 压缩、截不到真实宽度) ----
const shotWide = path.resolve(HERE, 'shot-wide.png')
const shotNarrow = path.resolve(HERE, 'shot-narrow.png')
const shotVars = path.resolve(HERE, 'shot-vars.png')
await page.evaluate(() => {
if (window.__hostB) window.__hostB.remove()
window.__hostA.style.width = '980px'
window.__hostA.style.height = '720px'
})
const shotLayout = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'wide' ? v : null
})
check('截图前 hostA 已回到 wide', Boolean(shotLayout))
await page.waitForTimeout(400)
await page.locator('#hostA').screenshot({ path: shotWide }).catch(() => {})
await page.evaluate(() => { window.__hostA.style.width = '320px'; window.__hostA.style.height = '640px' })
await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'narrow' ? v : null
})
await page.waitForTimeout(400)
await page.locator('#hostA').screenshot({ path: shotNarrow }).catch(() => {})
// 变量区留档:8 个占位符全部平铺
await page.evaluate(() => { window.__hostA.style.width = '980px'; window.__hostA.style.height = '1180px' })
await page.waitForTimeout(260)
// 变量特写拍「东方花茶香氛海报」:它同时有 19 个变量(平铺压力)和 4 条 desc(填写提示),
// 一张图能覆盖 desc 渲染 + 无 desc 降级两种形态
await page.locator('#hostA .iwb-ss-search').fill('东方花茶香氛海报')
await page.waitForTimeout(340)
await page.locator('#hostA .iwb-ss-card').first().click()
await page.waitForTimeout(380)
await page.locator('#hostA .iwb-ss-detail').screenshot({ path: shotVars })
console.log('· 截图:' + shotWide)
console.log('· 截图:' + shotNarrow)
console.log('· 截图:' + shotVars)
check('无页面 JS 异常', errors.length === 0, errors.slice(0, 2).join(' | '))
await finish()
async function finish() {
await browser.close()
server.close()
console.log('')
console.log(failed === 0 ? '全部通过' : failed + ' 项失败')
process.exit(failed === 0 ? 0 : 1)
}
}
main().catch(async (error) => {
console.error('harness 崩溃:', error)
process.exit(1)
})
+111
View File
@@ -0,0 +1,111 @@
# 白底图(插件)
把选中节点的图**等比缩放、居中**合成到一张正方形大图上(白底或透明底),按设置的格式 / 质量 /
体积上限编码,输出 `<name>_<size>x<size>.<ext>`。
典型用途:透明底抠图 → 电商主图白底大图(800×800,≤500KB 的 jpeg);开「双版本」可一次出
**透明 PNG + 白底 JPG** 两版。
**移植自** `iwb-plaus` 仓库的 `iwb-cutout-extension`:
- 源:`src/shared/image-math.js` 的 `fitRect`(等比缩放居中几何)+ `src/content.js` 的 `makeWhiteBgImage` / `performWhiteBg`(合成与写回流程)。
- 几何与合成算法逐字对齐上游;宿主胶水(`IWBPluginHost` 注册 / `ctx` 调用)与**导出编码**是新写的(上游只出 png)。
### 移植差异(有意为之)
- **文件名用真实边长与真实格式**:`<name>_<size>x<size>.<ext>`(如 `photo_800x800.jpg`)。上游 `autoWhiteBg` 分支硬编码 `_800x800`
且固定 png —— 这是上游 bug,这里按夹取后的实际边长、按 `blob.type` 的真实编码格式命名。
- **不移植 `autoWhiteBg`**(抠图后自动转白底):本插件只做白底图这一件事,入口即功能。
- **底色模式在设置里选**(`transparent` 开关),不是上游那种每次点击弹选择。
- 上游的批量处理 / 下载 / 剪贴板等能力不在本插件范围。
## 入口
- **节点漂浮菜单**「白底图」(**仅 `ref` 图片输入节点**;产图节点先「复制 / 插入为参考图节点」)
- 右键菜单「插件命令 → 白底图:选中节点」
## 设置
设置位置:宿主「设置 → 插件 → 白底图」。**宿主设置面板只支持 3 种控件**(`boolean` 勾选框 / `number` 数字框 /
`text` 文本框),没有下拉框,所以「导出格式」是文本框,填错会回退并留日志。
| 键 | 类型 | 默认 | 说明 |
|---|---|---|---|
| `bgSize` | number | 800 | 大图边长(像素);允许 64–4096,越界自动夹取 |
| `ratioPct` | number | 80 | 内容等比缩放后占边长的百分比;允许 10–100。默认 80 = 640/800(电商主图规范) |
| `dual` | boolean | false | 双版本:一次出透明 PNG + 白底 JPG 两个节点。**开启后 `format` / `transparent` 不生效,`replace` 被忽略** |
| `format` | text | `jpeg` | 单版本格式:`png` / `jpeg` / `webp`(`jpg` 也认,大小写与空格容错;未知值回退 `jpeg`) |
| `quality` | number | 82 | 仅 jpeg / webp 生效(png 忽略);允许 1–100。双版本下作用于 JPG 那一版 |
| `maxKB` | number | 500 | 体积上限(KB);填 `0` 或负数=不限制 |
| `transparent` | boolean | false | 单版本:关闭=填白底;开启=保留透明通道(jpeg 无 alpha,会自动改填白底并留日志) |
| `replace` | boolean | false | 关闭=新建参考图节点;开启=覆盖当前节点 |
## 双版本模式(`dual`)
开启后一次点击产出两个节点,正好对应电商平台的两套图:
| 输出 | 格式 | 底色 | 体积约束 |
|---|---|---|---|
| `<name>_800x800.png` | PNG(无损) | 透明 | **超限也照常输出**(PNG 无压缩参数,压不下去),只记日志 |
| `<name>_800x800.jpg` | JPEG(有损) | 白 | 自动降质保证 ≤ `maxKB` |
两条设计取舍:
- **`replace` 在双版本下被忽略**:两个版本没法覆盖同一个位置,总是新建两个节点。开启时会写一条日志说明,不是静默失效。
- **一版失败不拖累另一版**:两个版本各自 `try/catch`,只要有一个成功就落节点。若 JPG 压不进上限,报错信息会带上
「已生成:xxx.png」—— 宿主只把 `throw` 显示成红色提示,这是唯一能给用户的反馈通道,所以宁可红字也要把实情说全。
## 体积上限怎么保证(500KB)
有损格式(jpeg / webp)走**自动降质二分**:
1. 先按 `quality` 编码一次;不超限就直接用(画质最好)。
2. 超限则用固定下限质量 20 再编一次:**连 20 都超,直接报错**(提示调小 `bgSize` 或调大 `maxKB`)。
3. 否则在 `[20, quality]` 之间二分 6 次,取「能进上限的最高质量」—— 实测 800×800 噪声图从 1.1MB 收到 78KB 只多花几十毫秒。
**故意不做的**:不会偷偷降采样换体积。`bgSize` 是你指定的硬规范(800×800),缩了尺寸比超体积更难排查。
**PNG 的限制(重要)**:浏览器 `canvas.toBlob('image/png')` **没有压缩级别参数**,PNG 体积不可调。
所以 `format=png` 时超限只能报错(提示改 jpeg/webp 或调大 `maxKB`),不会降质 —— 这不是本插件的取舍,
是 Canvas 编码器的能力边界。白底 800² 纯色 PNG 通常 20–150KB 不触发;**透明底抠图 PNG 常在 300KB+ 会触发**。
体积判定用 `blob.size`(精确字节数),不走 base64 长度估算;`canvas.toBlob` 缺失的老环境才退化到 dataURL 反推。
## 远程图片
`getNodeImage` 返回 `{ dataUrl }` 时直接赋给 `img.src`(`img-src` 放行 `data:`,不污染画布);
**绝不对 `data:` URL 发网络请求**(宿主 CSP `connect-src` 不含 `data:`,必被拦 —— 姊妹插件 image-annotate 踩过并修掉的坑)。
返回 `{ url }`(远程 http(s))时插件会尝试 `fetch` 并转成 blob: URL 再解码;失败(含跨域/鉴权拦截、非 2xx、解码失败)会提示
「远程图片无法读取(可能被跨域限制):请先转存为本地位图」。
## 版本记录
- **1.2.0**:新增 `dual` 双版本(透明 PNG + 白底 JPG 一次出);PNG 版超限不阻断、JPG 版仍受 `maxKB` 硬约束;
双版本下忽略 `replace`、部分成功时错误信息带上已生成节点。
- **1.1.0**:新增 `format` / `quality` / `maxKB`(jpeg·webp 有损编码 + 体积上限自动降质);`ratioPct` 默认 85 → **80**(对齐 640/800);
`transparent` 遇 jpeg 自动改填白底;扩展名跟随真实 `blob.type`。
- 1.0.1 / 1.0.0:仅 png。
> 注意:默认值只对**没保存过设置**的环境生效;已存过 `ratioPct=85` 的旧记录会继续沿用 85,需要手动改成 80。
## 发布
```bash
cd /Users/qiqi/open/github/image-workbench-web
cp /Users/qiqi/open/github/iwb-plugins/white-bg-800/src/index.js /tmp/plugin-white-bg-800.js
# ⚠️ 必须把所有插件文件一起传入:发布器用「传入的文件」重建 plugins/index.json,不做合并。
# 只传自己 → 别的插件会从清单里消失(image-annotate 已实测踩到)。
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
cp /Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js /tmp/plugin-image-annotate.js
cp /Users/qiqi/open/github/iwb-plugins/blank-canvas/src/index.js /tmp/plugin-blank-canvas.js
node scripts/plugins-publish.mjs /tmp/plugin-white-bg-800.js /tmp/plugin-xianyi-cutout.js \
/tmp/plugin-image-annotate.js /tmp/plugin-blank-canvas.js \
--version white-bg-800=1.2.0 # 默认 dry-run,检查 diff 后再加 --upload
```
## 验证(开发用)
- `tools/harness.mjs`:本地 mock 端到端 —— 合成宿主 + `addScriptTag` 加载插件源码本体,在真实 Chromium 里验证
manifest / 注册 / `appliesTo` / 白底与透明底 / `fitRect` 居中 / 夹取 / 命名 / 写回 / 错误提示,
以及**格式归一化、jpeg 体积、500KB 自动降质、PNG 超限报错、透明底+jpeg 防黑底、双版本双节点与部分成功**。需要 Playwright
(可从宿主仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定),不进 CI。
```bash
node white-bg-800/tools/harness.mjs
```
- `tools/e2e-site.mjs`:带 CSP 的真实站点端到端(真 KV + SRI + 漂浮菜单 → 新建节点),透明底等设置类用例由 harness 覆盖。
> harness 里的 mock `ctx.log` 必须是**函数**(真实宿主如此),早先写成对象导致凡是走 `ctx.log` 的分支全炸。
> 另外几何断言在有损格式下要留 ±4px 容差(jpeg 边缘振铃),精确几何用 `format=png` 的用例测。
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@iwb-plugin/white-bg-800",
"private": true,
"version": "1.2.1",
"description": "白底图:把节点图等比缩放居中合成到正方形画布,按格式/质量/体积上限编码,输出 <name>_<size>x<size>.<ext>;可开双版本出透明 PNG + 白底 JPG",
"ibwPlugin": {
"id": "white-bg-800",
"entry": "src/index.js",
"apiVersion": 1
}
}
+313
View File
@@ -0,0 +1,313 @@
// iwb-plugin: 白底图 —— 把选中节点的图等比缩放、居中合成到正方形画布,按设置的格式/质量/体积上限编码,
// 输出 <name>_<size>x<size>.<ext>(默认 800×800 白底 jpeg,≤500KB;可开双版本一次出透明 PNG + 白底 JPG)。
// 移植自 iwb-plaus 仓库 iwb-cutout-extension:src/shared/image-math.js 的 fitRect + src/content.js 的 makeWhiteBgImage / performWhiteBg;
// 几何与合成算法逐字对齐上游,只有宿主胶水(IWBPluginHost 注册 / ctx 调用)与导出编码是新写的。
;(function (global) {
'use strict'
// 上游 shared/image-math.js 的 clamp
function clamp(v, min, max) {
return Math.max(min, Math.min(max, v))
}
// 上游 shared/image-math.js 的 fitRect:内容最长边 = min(boxW, boxH) * ratio,等比缩放并居中(不裁剪)
function fitRect(srcW, srcH, boxW, boxH, ratio) {
if (!(srcW > 0) || !(srcH > 0) || !(boxW > 0) || !(boxH > 0)) {
return { x: 0, y: 0, w: 0, h: 0, scale: 0 }
}
var r = Math.max(0.01, Math.min(1, ratio))
var maxLen = Math.min(boxW, boxH) * r
var scale = Math.min(maxLen / srcW, maxLen / srcH)
var w = srcW * scale
var h = srcH * scale
return { x: (boxW - w) / 2, y: (boxH - h) / 2, w: w, h: h, scale: scale }
}
function loadImage(src) {
return new Promise(function (resolve, reject) {
var img = new Image()
img.onload = function () { resolve(img) }
img.onerror = function () { reject(new Error('图片解码失败')) }
img.src = src
})
}
// ---------- 编码 ----------
// png 无损(无质量参数);jpeg/webp 有损且有质量参数;webp 另外保留 alpha。
var FORMATS = {
png: { mime: 'image/png', ext: 'png', lossy: false, alpha: true },
jpeg: { mime: 'image/jpeg', ext: 'jpg', lossy: true, alpha: false },
webp: { mime: 'image/webp', ext: 'webp', lossy: true, alpha: true },
}
// toBlob 的 blob.type 才是真实产出格式(浏览器不支持 webp 时会静默回退 png),命名按它走。
var TYPE_EXT = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' }
// 双版本固定产出:透明 PNG(无损、保 alpha)+ 白底 JPG(有损、体积可控)—— 电商平台两种图都要。
// png 那种允许超上限(透明图是必需产物,PNG 无压缩参数,压不下去只能照常输出并记日志)。
var DUAL_TARGETS = [
{ format: 'png', transparent: true, allowOversize: true },
{ format: 'jpeg', transparent: false, allowOversize: false },
]
// 导出格式设置是 text 输入框(宿主设置面板只有 text/number/boolean),这里做容错归一化。
function normalizeFormat(raw) {
var s = String(raw === undefined || raw === null ? '' : raw).trim().toLowerCase().replace(/^\./, '')
if (s === 'jpg' || s === 'jpeg' || s === 'jpe') return 'jpeg'
if (s === 'png' || s === 'webp') return s
return ''
}
// dataURL 的字节数(仅在 canvas.toBlob 缺失时的退路;正常路径用 blob.size,精确且无 base64 开销)
function dataUrlBytes(url) {
var s = String(url || '')
var comma = s.indexOf(',')
if (comma < 0) return 0
var body = s.length - comma - 1
var pad = s.charAt(s.length - 1) === '=' ? (s.charAt(s.length - 2) === '=' ? 2 : 1) : 0
return Math.max(0, Math.floor(body * 3 / 4) - pad)
}
function blobToDataUrl(blob) {
return new Promise(function (resolve, reject) {
var reader = new FileReader()
reader.onload = function () { resolve(String(reader.result || '')) }
reader.onerror = function () { reject(reader.error || new Error('读取编码结果失败')) }
reader.readAsDataURL(blob)
})
}
// 编码一次,产出 { dataUrl, size, type }
function encodeOnce(canvas, mime, quality) {
return new Promise(function (resolve, reject) {
if (typeof canvas.toBlob !== 'function') {
var url = canvas.toDataURL(mime, quality)
resolve({ dataUrl: url, size: dataUrlBytes(url), type: mime })
return
}
try {
canvas.toBlob(function (blob) {
if (!blob) { reject(new Error('图片编码失败')); return }
blobToDataUrl(blob).then(function (dataUrl) {
resolve({ dataUrl: dataUrl, size: blob.size, type: String(blob.type || mime) })
}, reject)
}, mime, quality)
} catch (error) {
reject(error)
}
})
}
function kb(bytes) {
return (Math.round(bytes / 1024 * 10) / 10) + 'KB'
}
// 体积上限:先按用户质量编码;超限就有损格式向下二分找「能进上限的最高质量」。
// 有损质量下限固定 0.2:再低画质不可用,此时报错而不是偷偷改边长(800×800 是硬规范)。
var MIN_QUALITY = 0.2
async function encodeWithLimit(canvas, format, quality, maxBytes) {
var spec = FORMATS[format]
var first = await encodeOnce(canvas, spec.mime, quality)
if (!maxBytes || first.size <= maxBytes) return first
if (!spec.lossy) {
throw new Error(
'PNG 体积 ' + kb(first.size) + ' 超过上限 ' + kb(maxBytes) +
':浏览器导出 PNG 无法调压缩级别 —— 请把「导出格式」改成 jpeg / webp,或调大「体积上限」'
)
}
var floor = await encodeOnce(canvas, spec.mime, MIN_QUALITY)
if (floor.size > maxBytes) {
throw new Error(
'已压到质量 20 仍有 ' + kb(floor.size) + ',超过上限 ' + kb(maxBytes) +
':请调小「大图边长」或调大「体积上限」'
)
}
var lo = MIN_QUALITY
var hi = quality
var pick = floor
for (var i = 0; i < 6 && hi - lo > 0.01; i++) {
var mid = (lo + hi) / 2
var cur = await encodeOnce(canvas, spec.mime, mid)
if (cur.size <= maxBytes) {
pick = cur
lo = mid
} else {
hi = mid
}
}
return pick
}
global.IWBPluginHost.register({
id: 'white-bg-800',
name: '白底图',
version: '1.2.1',
apiVersion: 1,
capabilities: ['commands', 'canvas', 'canvasWrite', 'nodeActions'],
settings: {
bgSize: { type: 'number', label: '大图边长(像素)', desc: '默认 800;允许 64–4096,越界自动夹取。', default: 800 },
ratioPct: { type: 'number', label: '内容占比(%)', desc: '内容等比缩放后占边长的百分比,默认 80(=640/800,电商主图规范);允许 10–100。', default: 80 },
dual: { type: 'boolean', label: '双版本(透明 PNG + 白底 JPG)', desc: '开启=一次生成两个节点:透明底 PNG + 白底 JPG,各一份。此时「导出格式」「透明底」不生效,「覆盖原节点」被忽略(双版本总是新建)。', default: false },
format: { type: 'text', label: '导出格式(单版本)', desc: '填 png / jpeg / webp(jpg 也认),默认 jpeg。png 无损但无压缩参数,体积可能超限。双版本开启时此项不生效。', default: 'jpeg' },
quality: { type: 'number', label: '压缩质量(1–100)', desc: '仅 jpeg / webp 生效,默认 82;超过体积上限时自动向下调(最低 20)。', default: 82 },
maxKB: { type: 'number', label: '体积上限(KB)', desc: '默认 500;填 0 或负数=不限制。按编码后的文件字节数判定。', default: 500 },
transparent: { type: 'boolean', label: '透明底(单版本)', desc: '关闭(默认)=填白底;开启=保留透明通道(jpeg 不支持,会自动改填白底)。双版本开启时此项不生效。', default: false },
replace: { type: 'boolean', label: '覆盖原节点', desc: '关闭(默认)=新建参考图节点;开启=覆盖当前节点。双版本开启时忽略此项。', default: false },
},
}, function (ctx) {
const NO_IMAGE = '该节点没有可编码的图片(请选中带图的参考图或输出节点)'
const REMOTE_FAIL = '远程图片无法读取(可能被跨域限制):请先转存为本地位图'
// 取图:dataUrl 直接赋给 img.src(img-src 放行 data:,不污染画布);
// 绝不对 data: URL 发网络请求 —— 宿主 CSP connect-src 不含 data:,必被拦(姊妹插件 image-annotate 踩过并修掉的坑)。
// 远程 url 才走 fetch,转成 blob: URL 再解码(blob: 同样不污染画布)。
async function resolveImage(nodeId) {
const image = await ctx.canvas.getNodeImage(nodeId)
if (!image) throw new Error(NO_IMAGE)
if (image.dataUrl) return loadImage(image.dataUrl)
if (!image.url) throw new Error(NO_IMAGE)
let resp
try {
resp = await global.fetch(image.url)
} catch (e) {
throw new Error(REMOTE_FAIL)
}
if (!resp.ok) throw new Error(REMOTE_FAIL)
const objUrl = URL.createObjectURL(await resp.blob())
try {
return await loadImage(objUrl)
} catch (e) {
throw new Error(REMOTE_FAIL)
} finally {
URL.revokeObjectURL(objUrl)
}
}
// 合成(对齐上游 makeWhiteBgImage):正方形画布,白底或透明底,fitRect 等比缩放居中、不裁剪
function composeCanvas(img, size, ratio, transparent) {
const canvas = document.createElement('canvas')
canvas.width = size
canvas.height = size
const ctx2d = canvas.getContext('2d')
if (!transparent) {
ctx2d.fillStyle = '#ffffff'
ctx2d.fillRect(0, 0, size, size)
}
const rect = fitRect(img.naturalWidth || img.width, img.naturalHeight || img.height, size, size, ratio)
ctx2d.drawImage(img, rect.x, rect.y, rect.w, rect.h)
return canvas
}
// allowOversize 只给双版本的透明 PNG 用:透明图是必需产物,PNG 又无压缩参数,
// 超限也只能照常输出(记日志),不能因为一个版本超限就让另一个版本也出不来。
async function encodeTarget(canvas, format, quality, maxBytes, allowOversize) {
if (allowOversize && !FORMATS[format].lossy) {
const res = await encodeOnce(canvas, FORMATS[format].mime, 1)
if (maxBytes && res.size > maxBytes) {
ctx.log('white-bg: 透明 PNG 为 ' + kb(res.size) + ',超过上限 ' + kb(maxBytes) + '(PNG 无压缩参数,已照常输出)')
}
return res
}
return encodeWithLimit(canvas, format, quality, maxBytes)
}
// 命名用真实边长与真实编码格式(上游 autoWhiteBg 分支硬编码 _800x800 是 bug,这里按夹取后的实际边长命名;
// 扩展名同理取 blob.type —— 浏览器不支持 webp 时会回退 png,不能照抄设置值)
function outName(base, size, encoded, format) {
const ext = TYPE_EXT[encoded.type] || FORMATS[format].ext
return base + '_' + size + 'x' + size + '.' + ext
}
function readNumeric(key, fallback, min, max) {
return clamp(Number(ctx.settings.get(key)) || fallback, min, max)
}
async function runOne(nodeId, nodeName) {
const img = await resolveImage(nodeId)
// 宿主可能把数值设置存成字符串,统一强转再夹取
const size = Math.round(readNumeric('bgSize', 800, 64, 4096))
const ratio = readNumeric('ratioPct', 80, 10, 100) / 100
const quality = readNumeric('quality', 82, 1, 100) / 100
const maxKB = Number(ctx.settings.get('maxKB'))
const maxBytes = Number.isFinite(maxKB) && maxKB > 0 ? Math.round(maxKB * 1024) : 0
const dual = Boolean(ctx.settings.get('dual'))
const replace = Boolean(ctx.settings.get('replace'))
const base = String(nodeName || 'image').replace(/\.[^.]+$/, '') || 'image'
let targets
if (dual) {
// 双版本下「覆盖原节点」没意义(两个版本只能覆盖一个位置),按文档忽略并留痕
if (replace) ctx.log('white-bg: 双版本模式总是新建节点,「覆盖原节点」已忽略')
targets = DUAL_TARGETS
} else {
const rawFormat = ctx.settings.get('format')
let format = normalizeFormat(rawFormat)
if (!format) {
ctx.log('white-bg: 未知导出格式 ' + JSON.stringify(String(rawFormat)) + ',回退 jpeg(可选 png / jpeg / webp)')
format = 'jpeg'
}
// 透明底与不支持的格式冲突:jpeg 没有 alpha 通道,用它画透明底会变成黑块 —— 强制填白并留痕。
const wantsTransparent = Boolean(ctx.settings.get('transparent'))
const transparent = wantsTransparent && FORMATS[format].alpha
if (wantsTransparent && !FORMATS[format].alpha) {
ctx.log('white-bg: ' + format + ' 不支持透明通道,已自动改填白底')
}
targets = [{ format: format, transparent: transparent, allowOversize: false }]
}
const made = []
const errors = []
for (const target of targets) {
try {
const canvas = composeCanvas(img, size, ratio, target.transparent)
const encoded = await encodeTarget(canvas, target.format, quality, maxBytes, target.allowOversize)
const name = outName(base, size, encoded, target.format)
if (replace && !dual) {
if (!ctx.canvas.setNodeImage(nodeId, encoded.dataUrl)) throw new Error('写回画布失败')
made.push('覆盖当前节点')
} else {
const created = ctx.canvas.createImageNode({ dataUrl: encoded.dataUrl, name: name })
if (!created) throw new Error('写回画布失败')
made.push(name)
}
ctx.log('white-bg: ' + name + ' ' + kb(encoded.size))
} catch (error) {
errors.push(error && error.message ? error.message : String(error))
}
}
if (!made.length && errors.length) throw new Error(errors[0])
// 部分成功:节点已经建好了,但要把失败原因说清楚(宿主只把 throw 显示成红色提示,这是唯一通道)
if (errors.length) throw new Error(errors.join(';') + '(已生成:' + made.join('、') + ')')
return dual ? made : (replace ? true : made[0])
}
ctx.nodeActions.register({
id: 'white-bg-node',
title: '白底图',
icon: 'vector-square',
appliesTo: function (node) { return Boolean(node) && node.type === 'ref' },
run: function (node) { return runOne(node.id, node.name) },
})
ctx.commands.register({
id: 'white-bg-selected',
title: '白底图:选中节点',
icon: 'vector-square',
run: function () {
const selected = ctx.canvas.getSelectedNode()
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
return runOne(selected.id, selected.name)
},
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
+228
View File
@@ -0,0 +1,228 @@
// 真实站点端到端(开发用,不进 CI)—— white-bg-800「白底图」。
//
// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被
// `connect-src 'self' https: …` 拦掉,因为宿主 CSP 的 `connect-src` 不含 `data:`)
// 在 mock 下永远绿,只有带真实 KV + 浏览器 SRI + 真实 CSP 的真站能抓出来。
// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)校验 + 真实画布桥。
//
// 运行(需要 Playwright):
// node white-bg-800/tools/e2e-site.mjs # 默认测试站
// IWB_BASE_URL=https://iwb.maqiart.eu.org node white-bg-800/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>/white-bg-800/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 white-bg-800/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, 'white-bg-800/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))
// 造一张真实的 96x64 PNG 作为节点图片(故意非正方形,让 800 方画布的等比缩放/居中被真正练到)
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')
})
// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled
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({ 'white-bg-800': { enabled: true, settings: {}, data: {} } }))
}, { cfg: CFG, ws: WS, png: PNG })
// ---------- 1) 站点可达 ----------
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
// ---------- 2) 宿主就绪 + 真实 KV 加载并启用 ----------
const hostReady = await poll(async () => page.evaluate(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true), 30000)
check('window.IWBPluginHost 就绪(initialized)', Boolean(hostReady))
const active = await poll(async () => page.evaluate(() => {
const p = window.IWBPluginHost.list().find((x) => x.id === 'white-bg-800')
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
}))
check('从真实 KV 加载并启用(active)', Boolean(active), JSON.stringify(active))
// ---------- 3) 版本 ----------
check('线上版本 = white-bg-800/package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
// ---------- 4) SRI ----------
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) => /plugin-white-bg-800(\.[0-9a-f]{12})?\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
// ---------- 5) 打开工作区 + 种子节点 ----------
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)
// ---------- 6) 入口:节点漂浮菜单(title 是静态字面量「白底图」;回落右键插件命令)----------
const triggerWhiteBg = 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-ctx-item').filter({ hasText: '白底图:选中节点' }).click()
return '右键命令'
}
const entry = await triggerWhiteBg()
check('节点入口可触发(漂浮菜单或右键命令)', true, entry)
// ---------- 7) 默认「新建」:恰好 2 个节点、新节点为 src_800x800.png ----------
const created = await poll(async () => page.evaluate(() => {
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
const nodes = ws.nodes || []
if (nodes.length !== 2) return false
const n = nodes.find((x) => x.id !== 'r1') || nodes[1]
return { nodes: nodes.length, name: n.data && n.data.name }
}))
const wsNodes = created ? created.nodes : await page.evaluate(() => (JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}').nodes || []).length)
check('默认「新建」:iwb_ws_w1 恰好 2 个节点', wsNodes === 2, 'nodes=' + wsNodes)
check('新节点 data.name = src_800x800.jpg(默认 format=jpeg)', Boolean(created && /^src_800x800\.jpg$/.test(created.name || '')), created && String(created.name))
// ---------- 8) 页内解引用 + 解码新建 JPEG:800x800、左上像素为白色 ----------
// 宿主「C3」引用模型:localStorage 里只存引用,字节在别处 —— 假设 localStorage 里有 base64 是
// 不可能的(by design)。两种引用形态都要认:
// a) { __blob: 'imgblob_<hash>_<len>' } → IndexedDB(src/image-blob-store.js)
// b) { __cache: '<同源 URL>' } → 宿主把大 dataURL 外置成 /__iwb_cache__/xxx(当前线上形态)
// 故在页内经 IWBImageBlobStore 解引用或同源 fetch __cache(CSP connect-src 'self' 放行)。
const resolved = await poll(async () => page.evaluate(async () => {
// 读节点图(按优先级解引用):a) data: 字符串直用 b) {__blob} 引用解引用 c) 其余形态给诊断失败
const resolveNodeDataUrl = async (d) => {
if (typeof d === 'string' && /^data:/.test(d)) return { dataUrl: d, via: 'data:' } // a)
if (d && typeof d === 'object' && typeof d.__cache === 'string' && d.__cache) { // b2) 宿主把大 dataURL 外置成同源缓存引用
const toDataUrl = (blob) => new Promise((res) => {
const fr = new FileReader()
fr.onload = () => res(String(fr.result || ''))
fr.onerror = () => res('')
fr.readAsDataURL(blob)
})
try {
// /__iwb_cache__/<hash> 由 SW 直出;冷启动 SW 未接管时该路径会落到 Pages 404(返回 HTML)。
// 故优先直接读 Cache Storage,读不到再走 fetch(此时 SW 已接管)。
const abs = new URL(d.__cache, location.origin).href
if (typeof caches !== 'undefined') {
const hit = (await caches.match(abs)) || (await caches.match(d.__cache))
if (hit) {
const blob = await hit.blob()
const u = await toDataUrl(blob)
return u ? { dataUrl: u, via: '__cache(CS ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' }
}
}
const resp = await fetch(abs)
const blob = await resp.blob()
const u = await toDataUrl(blob)
return u ? { dataUrl: u, via: '__cache(fetch ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' }
} catch (e) {
return { error: '__cache 抓取抛错: ' + ((e && e.message) || String(e)) }
}
}
if (d && typeof d === 'object' && typeof d.__blob === 'string' && d.__blob) { // b)
const Lib = window.IWBImageBlobStore
if (!Lib) return { error: 'window.IWBImageBlobStore 缺失' }
try {
let u = ''
if (typeof Lib.resolveDataUrl === 'function') {
u = await Lib.resolveDataUrl(d.__blob)
} else if (typeof Lib.create === 'function') {
// 与 app.js:730 同一构造:idb 用宿主同一存储运行时(get 直出 Blob)
const idb = (window.IWBStorageRuntime && window.IWBStorageRuntime.indexedDb) ||
(window.IWBStorageFallbackIndexeddb && window.IWBStorageContract && window.IWBStorageFallbackIndexeddb.create({ contract: window.IWBStorageContract.indexedDb }))
if (!idb || typeof idb.get !== 'function') return { error: '取不到宿主 idb(IWBStorageRuntime.indexedDb)' }
u = await Lib.create({ idb }).resolveDataUrl(d.__blob)
} else {
return { error: 'IWBImageBlobStore 无 resolveDataUrl / create' }
}
return (typeof u === 'string' && u) ? { dataUrl: u, via: '__blob' } : { error: '解引用未返回字节(' + d.__blob + ')' }
} catch (e) {
return { error: '解引用抛错: ' + ((e && e.message) || String(e)) }
}
}
return { error: '未知 data 形态: ' + (d == null ? String(d) : typeof d) + ' keys=' + (d && typeof d === 'object' ? Object.keys(d).join(',') : '-') + ' sample=' + JSON.stringify(d).slice(0, 220) } // c)
}
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
const nodes = ws.nodes || []
const n = nodes.length === 2 ? (nodes.find((x) => x.id !== 'r1') || nodes[1]) : null
if (!n) return false // 新节点未就绪 → 重试
const r = await resolveNodeDataUrl(n.data && n.data.data)
if (r.error) return { error: r.error }
if (!/^data:image\/jpeg;base64,/.test(r.dataUrl)) return { error: '解引用结果不是 JPEG dataURL(via=' + r.via + '): ' + String(r.dataUrl).slice(0, 40) }
const img = new Image()
const ok = await new Promise((res) => { img.onload = () => res(true); img.onerror = () => res(false); img.src = r.dataUrl })
if (!ok) return { dataOk: true, via: r.via, decodeError: 'Image 解码失败' }
const c = document.createElement('canvas')
c.width = img.naturalWidth; c.height = img.naturalHeight
const x = c.getContext('2d')
x.drawImage(img, 0, 0)
const px = x.getImageData(0, 0, 1, 1).data
return { dataOk: true, via: r.via, w: img.naturalWidth, h: img.naturalHeight, px: [px[0], px[1], px[2], px[3]] }
}))
const d = resolved || {}
const dDiag = d.error || d.decodeError || (resolved ? '' : '轮询超时:新节点未出现')
check('新节点 data 为 JPEG 字节(引用已解析)', Boolean(d.dataOk), d.dataOk ? d.via : dDiag)
check('新建 JPEG 解码尺寸 = 800x800', Boolean(d.dataOk && d.w === 800 && d.h === 800), d.dataOk ? d.w + 'x' + d.h : dDiag)
// jpeg 有损:纯白角落允许 ±5 的压缩抖动,但 alpha 必须不透明
check('新建 JPEG 左上像素 ≈ 白色且不透明', Boolean(d.dataOk && d.px && d.px[0] >= 250 && d.px[1] >= 250 && d.px[2] >= 250 && d.px[3] === 255), JSON.stringify(d.px) || dDiag)
// 透明模式(transparent)不在此二次跑(需改设置再整轮重放,易碎)——由 white-bg-800/tools/harness.mjs 覆盖。
// ---------- 9) 无 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(' | '))
// ---------- 10) 无页面级运行时错误 ----------
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+569
View File
@@ -0,0 +1,569 @@
// 白底图插件本地 mock 端到端(开发用,不进 CI)。
//
// 为什么需要它:合成链路(Image 解码 → Canvas 2D drawImage → toDataURL)只有真浏览器有 canvas,
// node 侧测不了;这里用 addInitScript 装一个合成 window.IWBPluginHost(可注入的 ctx),
// 再用 addScriptTag 加载插件源码本体(无构建、无 CSP 依赖),在真实 Chromium 里验证
// manifest / 注册 / appliesTo / 白底与透明底 / fitRect 居中 / 夹取 / 命名 / 写回 / 错误提示。
//
// 运行:
// node white-bg-800/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)) // <repo>/white-bg-800/tools
const REPO = path.resolve(HERE, '../..') // <repo>
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(' npm i -D playwright # 本仓或宿主仓皆可')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node white-bg-800/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 = 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))
}
}
// ---------- 页内环境:合成宿主 + 记录器(__H__)+ 测量器(__M__) ----------
const HOST_SETUP = () => {
const H = {
manifest: null,
nodeActions: [],
commands: [],
calls: { setNodeImage: [], createImageNode: [] },
inject: { image: null, selected: null, settings: {} },
defaults: {},
lastRun: null,
}
H.run = (actionId, node) => {
const a = H.nodeActions.find((x) => x.id === actionId)
if (a) return a.run(node || { id: 'n1', type: 'ref', name: 'photo.png' })
const c = H.commands.find((x) => x.id === actionId)
if (c) return c.run()
return Promise.reject(new Error('unknown action: ' + actionId))
}
// 触发一次 run:清空调用记录,落账后 lastRun = { ok, value } | { ok: false, error }
H.fire = (actionId, node) => {
H.lastRun = null
H.calls.setNodeImage.length = 0
H.calls.createImageNode.length = 0
H.run(actionId, node).then(
(v) => { H.lastRun = { ok: true, value: v } },
(e) => { H.lastRun = { ok: false, error: String(e && e.message) } }
)
return true
}
const ctx = {
nodeActions: { register: (a) => { H.nodeActions.push(a) } },
commands: { register: (c) => { H.commands.push(c) } },
canvas: {
getNodeImage: async () => H.inject.image,
setNodeImage: (id, dataUrl) => { H.calls.setNodeImage.push({ id, dataUrl }); return true },
createImageNode: (opts) => { H.calls.createImageNode.push({ dataUrl: opts && opts.dataUrl, name: opts && opts.name }); return 'new-node-' + (H.calls.createImageNode.length) },
getSelectedNode: () => H.inject.selected,
},
settings: { get: (k) => (Object.prototype.hasOwnProperty.call(H.inject.settings, k) ? H.inject.settings[k] : H.defaults[k]) },
// 真实宿主的 ctx.log 是函数(plugin-host 的 log(...args)),不是对象 —— 早先 mock 成对象,
// 插件一旦用 ctx.log 就炸(透明底+jpeg、未知格式两条用例因此整条失败)。
log: Object.assign(function () {}, { info() {}, warn() {}, error() {} }),
events: { on() {}, off() {}, emit() {} },
storage: { get() { return undefined }, set() {}, remove() {} },
}
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
// 测量:解码输出 → 尺寸 / 四角 / 内容 bbox(白底=非白像素,透明底=alpha>0)
window.__M__ = async (dataUrl, mode, withBbox) => {
const img = await new Promise((resolve, reject) => {
const i = new Image()
i.onload = () => resolve(i)
i.onerror = () => reject(new Error('decode failed'))
i.src = dataUrl
})
const c = document.createElement('canvas')
c.width = img.naturalWidth || img.width
c.height = img.naturalHeight || img.height
const x = c.getContext('2d')
x.drawImage(img, 0, 0)
const d = x.getImageData(0, 0, c.width, c.height).data
const at = (px, py) => { const o = (py * c.width + px) * 4; return [d[o], d[o + 1], d[o + 2], d[o + 3]] }
const corners = [at(0, 0), at(c.width - 1, 0), at(0, c.height - 1), at(c.width - 1, c.height - 1)]
let bbox = null
if (withBbox) {
let minX = Infinity, minY = Infinity, maxX = -1, maxY = -1
for (let py = 0; py < c.height; py++) {
for (let px = 0; px < c.width; px++) {
const [r, g, b, a] = at(px, py)
const isContent = mode === 'transparent' ? a > 0 : !(r === 255 && g === 255 && b === 255)
if (isContent) {
if (px < minX) minX = px
if (px > maxX) maxX = px
if (py < minY) minY = py
if (py > maxY) maxY = py
}
}
}
if (maxX >= 0) bbox = { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 }
}
return { width: c.width, height: c.height, corners, bbox }
}
}
console.log('目标:本地 mock 页(about:blank)+ 插件源码 ' + PLUGIN_ENTRY)
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))
await page.addInitScript(HOST_SETUP)
await page.goto('about:blank')
check('合成宿主已注入(__H__ / IWBPluginHost)', await page.evaluate(() => Boolean(window.__H__ && window.IWBPluginHost)))
await page.addScriptTag({ path: PLUGIN_ENTRY })
check('插件已加载并完成注册', await page.evaluate(() => Boolean(window.__H__ && window.__H__.manifest)))
// ---------- 1) manifest ----------
const m = await page.evaluate(() => window.__H__.manifest)
check('manifest:id = white-bg-800', m.id === 'white-bg-800', String(m.id))
check('manifest:name = 白底图', m.name === '白底图', String(m.name))
check('manifest:version = 1.2.0', m.version === '1.2.0', String(m.version))
check('manifest:apiVersion = 1', m.apiVersion === 1, String(m.apiVersion))
check('manifest:capabilities = [commands, canvas, canvasWrite, nodeActions]',
JSON.stringify(m.capabilities) === JSON.stringify(['commands', 'canvas', 'canvasWrite', 'nodeActions']), JSON.stringify(m.capabilities))
const wantSettings = {
bgSize: { type: 'number', default: 800 },
ratioPct: { type: 'number', default: 80 },
dual: { type: 'boolean', default: false },
format: { type: 'text', default: 'jpeg' },
quality: { type: 'number', default: 82 },
maxKB: { type: 'number', default: 500 },
transparent: { type: 'boolean', default: false },
replace: { type: 'boolean', default: false },
}
check('manifest:settings 恰好 8 键(新增 dual)',
JSON.stringify(Object.keys(m.settings || {}).sort()) === JSON.stringify(Object.keys(wantSettings).sort()),
JSON.stringify(Object.keys(m.settings || {})))
for (const [k, want] of Object.entries(wantSettings)) {
const s = (m.settings || {})[k]
check('manifest:settings.' + k + '(type=' + want.type + ', default=' + want.default + ')',
Boolean(s) && s.type === want.type && s.default === want.default,
s ? (s.type + ' / ' + String(s.default)) : '缺失')
}
// ---------- 2) 注册 ----------
const reg = await page.evaluate(() => ({
nodeActions: window.__H__.nodeActions.map((a) => ({ id: a.id, title: a.title, icon: a.icon })),
commands: window.__H__.commands.map((c) => ({ id: c.id, title: c.title, icon: c.icon })),
}))
check('恰好 1 个 nodeAction:white-bg-node / 白底图 / icon=fit',
reg.nodeActions.length === 1 && reg.nodeActions[0].id === 'white-bg-node' && reg.nodeActions[0].title === '白底图' && reg.nodeActions[0].icon === 'fit',
JSON.stringify(reg.nodeActions))
check('恰好 1 个 command:white-bg-selected',
reg.commands.length === 1 && reg.commands[0].id === 'white-bg-selected',
JSON.stringify(reg.commands))
// ---------- 3) appliesTo ----------
// 2026-10 起图片处理动作只在 ref 节点出现(产图节点一个节点可能有多张结果,getNodeImage 只取 result[0],会误处理)
const applies = await page.evaluate(() => {
const a = window.__H__.nodeActions[0]
return ['ref', 'out', 'gen', 'layer', 'prompt'].map((t) => ({ type: t, ok: a.appliesTo({ id: 'n1', type: t }) }))
})
for (const r of applies) {
const want = r.type === 'ref'
check('appliesTo:type=' + r.type + ' → ' + want, r.ok === want, String(r.ok))
}
// ---------- 源图(纯色 PNG,bbox 即绘制矩形;noise 用于体积上限用例 —— 纯色图压不出差别) ----------
await page.evaluate(() => {
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 makeNoise = (w, h) => {
const c = document.createElement('canvas')
c.width = w; c.height = h
const x = c.getContext('2d')
const img = x.createImageData(w, h)
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')
}
window.__SRC__ = { rect: make(400, 200, '#2f6fed'), square: make(300, 300, '#e8a13c'), noise: makeNoise(800, 800) }
})
// 触发一次 run 并等落账;返回紧凑结果(成功含调用摘要,失败含错误信息)
const fire = async (setup) => {
await page.evaluate(setup)
await poll(() => page.evaluate(() => Boolean(window.__H__.lastRun)))
return page.evaluate(() => {
const H = window.__H__
if (!H.lastRun) return { ok: false, error: '(超时未完成)' }
// 真实产出格式取 dataURL 的 mime —— 浏览器不支持 webp 时会回退 png,不能照抄设置值
const mime = (s) => { const m = /^data:([^;,]+)/.exec(String(s)); return m ? m[1] : '' }
const bytes = (s) => {
const str = String(s || '')
const comma = str.indexOf(',')
if (comma < 0) return 0
const body = str.length - comma - 1
const pad = str.charAt(str.length - 1) === '=' ? (str.charAt(str.length - 2) === '=' ? 2 : 1) : 0
return Math.max(0, Math.floor(body * 3 / 4) - pad)
}
return {
ok: H.lastRun.ok,
error: H.lastRun.ok ? null : H.lastRun.error,
setNodeImage: H.calls.setNodeImage.map((c) => ({ id: c.id, type: mime(c.dataUrl), bytes: bytes(c.dataUrl) })),
createImageNode: H.calls.createImageNode.map((c) => ({ name: c.name, type: mime(c.dataUrl), bytes: bytes(c.dataUrl) })),
}
})
}
// 解码测量第 index 个新建节点的输出
const measure = async (mode, withBbox = true, index = 0) => {
const dataUrl = await page.evaluate((i) => (window.__H__.calls.createImageNode.length > i ? window.__H__.calls.createImageNode[i].dataUrl : null), index)
return dataUrl ? page.evaluate(({ d, md, bb }) => window.__M__(d, md, bb), { d: dataUrl, md: mode, bb: withBbox }) : null
}
// ---------- 4) 白底模式(默认设置) ----------
const r4 = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = {}
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
})
check('白底模式:run 成功、恰好新建 1 个 data:image/jpeg 节点(默认 format=jpeg)',
r4.ok && r4.createImageNode.length === 1 && r4.createImageNode[0].type === 'image/jpeg', r4.ok ? JSON.stringify(r4.createImageNode) : String(r4.error))
const m4 = await measure('white')
check('白底模式:输出 800×800', Boolean(m4) && m4.width === 800 && m4.height === 800, m4 ? (m4.width + '×' + m4.height) : '未取得输出')
check('白底模式:四角 #ffffff',
Boolean(m4) && m4.corners.every((p) => p[0] === 255 && p[1] === 255 && p[2] === 255), m4 ? JSON.stringify(m4.corners) : '')
// 有损格式(jpeg)在白底边缘会产生振铃,bbox 会比真实绘制区大 1–2px —— 几何断言留 ±4 的容差;
// 精确几何改用 format=png 的用例(见 7c/7d),这里只验证「默认设置能跑通 + 大致居中」。
check('白底模式:内容 bbox 640×320 居中(ratioPct 默认 80,±4px 含 jpeg 振铃)',
Boolean(m4) && m4.bbox && Math.abs(m4.bbox.w - 640) <= 4 && Math.abs(m4.bbox.h - 320) <= 4 && Math.abs(m4.bbox.x - 80) <= 4 && Math.abs(m4.bbox.y - 240) <= 4,
m4 && m4.bbox ? JSON.stringify(m4.bbox) : '')
// ---------- 5) 透明底模式(必须 png/webp,jpeg 无 alpha) ----------
const r5 = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { transparent: true, format: 'png' }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
})
check('透明底模式(format=png):run 成功、恰好新建 1 个 png 节点',
r5.ok && r5.createImageNode.length === 1 && r5.createImageNode[0].type === 'image/png', r5.ok ? JSON.stringify(r5.createImageNode) : String(r5.error))
const m5 = await measure('transparent')
check('透明底模式:四角 alpha = 0',
Boolean(m5) && m5.corners.every((p) => p[3] === 0), m5 ? JSON.stringify(m5.corners) : '')
// ---------- 5b) 透明底 + jpeg:不能出黑底,自动改填白 ----------
const r5b = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { transparent: true, format: 'jpeg' }
window.__H__.fire('white-bg-node', { id: 'n1b', type: 'ref', name: 'photo.png' })
})
check('透明底 + jpeg:仍成功、产出 jpeg', r5b.ok && r5b.createImageNode.length === 1 && r5b.createImageNode[0].type === 'image/jpeg',
r5b.ok ? JSON.stringify(r5b.createImageNode) : String(r5b.error))
const m5b = await measure('white', false)
check('透明底 + jpeg:四角为白(未出现黑底)',
Boolean(m5b) && m5b.corners.every((p) => p[0] > 245 && p[1] > 245 && p[2] > 245),
m5b ? JSON.stringify(m5b.corners) : '')
// ---------- 6) 方图 ----------
const r6 = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.square }
window.__H__.inject.settings = {}
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'square.png' })
})
check('方图 300×300:run 成功、恰好新建 1 个节点', r6.ok && r6.createImageNode.length === 1, r6.ok ? '' : String(r6.error))
const m6 = await measure('white')
check('方图 300×300:内容 bbox 640×640 居中(±4px 含 jpeg 振铃)',
Boolean(m6) && m6.bbox && Math.abs(m6.bbox.w - 640) <= 4 && Math.abs(m6.bbox.h - 640) <= 4 && Math.abs(m6.bbox.x - 80) <= 4 && Math.abs(m6.bbox.y - 80) <= 4,
m6 && m6.bbox ? JSON.stringify(m6.bbox) : '')
// ---------- 7) 夹取 ----------
const r7a = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { bgSize: 10 }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'a.png' })
})
const m7a = await measure('white', false)
check('夹取:bgSize=10 → 输出 64×64', r7a.ok && Boolean(m7a) && m7a.width === 64 && m7a.height === 64, m7a ? (m7a.width + '×' + m7a.height) : String(r7a.error))
const r7b = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { bgSize: 99999 }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'b.png' })
})
const m7b = await measure('white', false)
check('夹取:bgSize=99999 → 输出 4096×4096', r7b.ok && Boolean(m7b) && m7b.width === 4096 && m7b.height === 4096, m7b ? (m7b.width + '×' + m7b.height) : String(r7b.error))
const r7c = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { ratioPct: 200, format: 'png' }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'c.png' })
})
const m7c = await measure('white')
check('夹取:ratioPct=200 → 内容 bbox 宽 = 整边(800)',
r7c.ok && Boolean(m7c) && m7c.bbox && m7c.bbox.w === 800, m7c && m7c.bbox ? JSON.stringify(m7c.bbox) : String(r7c.error))
const r7d = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { ratioPct: 1, format: 'png' }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'd.png' })
})
const m7d = await measure('white')
check('夹取:ratioPct=1 → 内容 bbox 宽 = 10% 边长(80)',
r7d.ok && Boolean(m7d) && m7d.bbox && m7d.bbox.w === 80, m7d && m7d.bbox ? JSON.stringify(m7d.bbox) : String(r7d.error))
// ---------- 8) 命名 ----------
const r8a = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = {}
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
})
check('命名:photo.png → photo_800x800.jpg(默认 jpeg 后缀)',
r8a.ok && r8a.createImageNode.length === 1 && r8a.createImageNode[0].name === 'photo_800x800.jpg',
r8a.createImageNode.length ? String(r8a.createImageNode[0].name) : String(r8a.error))
const r8b = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = {}
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: '' })
})
check('命名:空名 → image_800x800.jpg',
r8b.ok && r8b.createImageNode.length === 1 && r8b.createImageNode[0].name === 'image_800x800.jpg',
r8b.createImageNode.length ? String(r8b.createImageNode[0].name) : String(r8b.error))
const r8c = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { format: 'PNG' }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
})
check('命名/格式:format=PNG(大写)→ photo_800x800.png + data:image/png',
r8c.ok && r8c.createImageNode.length === 1 && r8c.createImageNode[0].name === 'photo_800x800.png' && r8c.createImageNode[0].type === 'image/png',
r8c.createImageNode.length ? JSON.stringify(r8c.createImageNode) : String(r8c.error))
const r8d = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { format: ' JPG ' }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
})
check('格式容错:format=" JPG " → 认成 jpeg,后缀 .jpg',
r8d.ok && r8d.createImageNode.length === 1 && r8d.createImageNode[0].name === 'photo_800x800.jpg' && r8d.createImageNode[0].type === 'image/jpeg',
r8d.createImageNode.length ? JSON.stringify(r8d.createImageNode) : String(r8d.error))
const r8e = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { format: 'bmp' }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
})
check('格式容错:format=bmp(未知)→ 回退 jpeg',
r8e.ok && r8e.createImageNode.length === 1 && r8e.createImageNode[0].type === 'image/jpeg',
r8e.createImageNode.length ? JSON.stringify(r8e.createImageNode) : String(r8e.error))
// ---------- 8f) 体积上限(用噪声图:纯色图压不出差别,噪声是最坏情况) ----------
// 噪声 800×800 在 quality=100 下约 1.1MB;设 80KB 上限后应自动降质到 ≤80KB。
const r8f = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.noise }
window.__H__.inject.settings = { quality: 100, maxKB: 80 }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'noise.png' })
})
const size8f = r8f.createImageNode.length ? r8f.createImageNode[0].bytes : 0
check('体积上限:quality=100 + maxKB=80 → 输出 jpeg 且 ≤ 80KB(自动降质)',
r8f.ok && r8f.createImageNode.length === 1 && r8f.createImageNode[0].type === 'image/jpeg' && size8f > 0 && size8f <= 80 * 1024,
r8f.ok ? (size8f + ' bytes = ' + (Math.round(size8f / 1024 * 10) / 10) + 'KB') : String(r8f.error))
// 不限制体积时,质量参数确实影响体积(quality=100 明显大于 quality=10)
const r8g = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.noise }
window.__H__.inject.settings = { quality: 100, maxKB: 0 }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'noise.png' })
})
const lenG = r8g.createImageNode.length ? r8g.createImageNode[0].bytes : 0
const r8h = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.noise }
window.__H__.inject.settings = { quality: 10, maxKB: 0 }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'noise.png' })
})
const lenH = r8h.createImageNode.length ? r8h.createImageNode[0].bytes : 0
check('质量生效:maxKB=0 时 quality=100 体积 > quality=10 的 2 倍',
r8g.ok && r8h.ok && lenG > lenH * 2,
'q100=' + lenG + 'B, q10=' + lenH + 'B')
// PNG 无压缩参数:超限必须报错并给出可执行建议,而不是偷偷缩尺寸
const r8i = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.noise }
window.__H__.inject.settings = { format: 'png', maxKB: 10 }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'noise.png' })
})
check('PNG 超限:拒绝并提示改格式/调体积上限',
!r8i.ok && typeof r8i.error === 'string' && r8i.error.indexOf('PNG 体积') === 0 && r8i.error.indexOf('导出格式') > 0,
String(r8i.error))
// 有损也压不进上限时:报错(不悄悄改边长)
const r8j = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.noise }
window.__H__.inject.settings = { quality: 100, maxKB: 1 }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'noise.png' })
})
check('有损压不进上限:拒绝并提示调边长/调上限',
!r8j.ok && typeof r8j.error === 'string' && r8j.error.indexOf('已压到质量 20') === 0,
String(r8j.error))
// ---------- 8k) 双版本:透明 PNG + 白底 JPG ----------
const r8k = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { dual: true }
window.__H__.fire('white-bg-node', { id: 'n1', type: 'ref', name: 'photo.png' })
})
check('双版本:恰好新建 2 个节点', r8k.ok && r8k.createImageNode.length === 2,
r8k.ok ? JSON.stringify(r8k.createImageNode) : String(r8k.error))
check('双版本:[0] 透明 PNG、[1] 白底 JPG(顺序与命名)',
r8k.createImageNode.length === 2 &&
r8k.createImageNode[0].type === 'image/png' && r8k.createImageNode[0].name === 'photo_800x800.png' &&
r8k.createImageNode[1].type === 'image/jpeg' && r8k.createImageNode[1].name === 'photo_800x800.jpg',
JSON.stringify(r8k.createImageNode))
check('双版本:createImageNode 调用 2 次、setNodeImage 0 次',
r8k.createImageNode.length === 2 && r8k.setNodeImage.length === 0,
JSON.stringify(r8k.setNodeImage))
const mkPng = await measure('transparent', false, 0)
check('双版本:透明版四角 alpha = 0',
Boolean(mkPng) && mkPng.corners.every((p) => p[3] === 0), mkPng ? JSON.stringify(mkPng.corners) : '')
const mkJpg = await measure('white', false, 1)
check('双版本:白底版四角为白',
Boolean(mkJpg) && mkJpg.corners.every((p) => p[0] > 245 && p[1] > 245 && p[2] > 245),
mkJpg ? JSON.stringify(mkJpg.corners) : '')
// 双版本下「覆盖原节点」按文档忽略(两个版本无法覆盖同一个位置)
const r8l = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { dual: true, replace: true }
window.__H__.fire('white-bg-node', { id: 'n8l', type: 'ref', name: 'photo.png' })
})
check('双版本 + replace=true:忽略覆盖,仍新建 2 个节点、setNodeImage 0 次',
r8l.ok && r8l.createImageNode.length === 2 && r8l.setNodeImage.length === 0,
r8l.ok ? JSON.stringify(r8l.createImageNode) : String(r8l.error))
// 双版本部分成功:PNG 超限照常输出(不阻断),JPG 压不进上限 → 报错但要说明已生成什么
const r8m = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.noise }
window.__H__.inject.settings = { dual: true, maxKB: 10 }
window.__H__.fire('white-bg-node', { id: 'n8m', type: 'ref', name: 'noise.png' })
})
check('双版本部分成功:PNG 超限不阻断(照出),JPG 失败时报错并说明已生成的节点',
!r8m.ok && r8m.createImageNode.length === 1 && r8m.createImageNode[0].name === 'noise_800x800.png' &&
typeof r8m.error === 'string' && r8m.error.indexOf('已生成:noise_800x800.png') > 0,
r8m.ok ? JSON.stringify(r8m.createImageNode) : (String(r8m.error) + ' | 节点数=' + r8m.createImageNode.length))
// ---------- 9) replace=true ----------
const r9 = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = { replace: true }
window.__H__.fire('white-bg-node', { id: 'n9', type: 'ref', name: 'photo.png' })
})
check('replace=true:setNodeImage 恰好 1 次、data:image/jpeg、id 正确',
r9.ok && r9.setNodeImage.length === 1 && r9.setNodeImage[0].type === 'image/jpeg' && r9.setNodeImage[0].id === 'n9',
r9.ok ? JSON.stringify(r9.setNodeImage) : String(r9.error))
check('replace=true:createImageNode 未被调用', r9.ok && r9.createImageNode.length === 0, String(r9.createImageNode.length))
// ---------- 10) replace=false ----------
const r10 = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = {}
window.__H__.fire('white-bg-node', { id: 'n10', type: 'ref', name: 'photo.png' })
})
check('replace=false:createImageNode 恰好 1 次(dataUrl + name)',
r10.ok && r10.createImageNode.length === 1 && r10.createImageNode[0].type === 'image/jpeg' && r10.createImageNode[0].name === 'photo_800x800.jpg',
r10.ok ? JSON.stringify(r10.createImageNode) : String(r10.error))
// ---------- 11) 无图 ----------
const r11 = await fire(() => {
window.__H__.inject.image = null
window.__H__.inject.settings = {}
window.__H__.fire('white-bg-node', { id: 'n11', type: 'ref', name: 'photo.png' })
})
check('无图:拒绝「该节点没有可编码的图片(请选中带图的参考图或输出节点)」',
!r11.ok && r11.error === '该节点没有可编码的图片(请选中带图的参考图或输出节点)', String(r11.error))
// ---------- 12) 远程图 fetch 失败 ----------
const r12 = await fire(() => {
window.__H__.inject.image = { url: 'https://example.com/x.png' }
window.__H__.inject.settings = {}
if (!window.__ORIG_FETCH__) window.__ORIG_FETCH__ = window.fetch
window.fetch = function () { return Promise.reject(new Error('blocked')) }
window.__H__.fire('white-bg-node', { id: 'n12', type: 'ref', name: 'photo.png' })
})
await page.evaluate(() => { if (window.__ORIG_FETCH__) { window.fetch = window.__ORIG_FETCH__; window.__ORIG_FETCH__ = null } })
check('远程图 fetch 失败:拒绝「远程图片无法读取(可能被跨域限制):请先转存为本地位图」',
!r12.ok && r12.error === '远程图片无法读取(可能被跨域限制):请先转存为本地位图', String(r12.error))
// ---------- 命令入口(getSelectedNode 注入) ----------
const c1 = await fire(() => {
window.__H__.inject.image = { dataUrl: window.__SRC__.rect }
window.__H__.inject.settings = {}
window.__H__.inject.selected = { id: 'sel1', type: 'ref', name: 'picked.jpg' }
window.__H__.fire('white-bg-selected')
})
check('命令入口:选中 picked.jpg → picked_800x800.jpg',
c1.ok && c1.createImageNode.length === 1 && c1.createImageNode[0].name === 'picked_800x800.jpg',
c1.createImageNode.length ? String(c1.createImageNode[0].name) : String(c1.error))
const c2 = await fire(() => {
window.__H__.inject.selected = null
window.__H__.fire('white-bg-selected')
})
check('命令入口:未选中 → 拒绝「请先选中一个带图的节点」',
!c2.ok && c2.error === '请先选中一个带图的节点', String(c2.error))
// ---------- 13) 静态检查(node 侧读源码) ----------
const offenders = []
for (const [i, line] of readFileSync(PLUGIN_ENTRY, 'utf8').split('\n').entries()) {
const n = i + 1
if (/fetch\(\s*(['"])data:/.test(line)) offenders.push(n + ': fetch(data:) → ' + line.trim())
if (/fetch\(\s*[\w.$]*[Dd]ataUrl\b/.test(line)) offenders.push(n + ': fetch(*dataUrl) → ' + line.trim())
if (/\beval\s*\(/.test(line)) offenders.push(n + ': eval → ' + line.trim())
if (/new\s+Function\s*\(/.test(line)) offenders.push(n + ': new Function → ' + line.trim())
if (/\bimport\b/.test(line)) offenders.push(n + ': import → ' + line.trim())
if (/\brequire\s*\(/.test(line)) offenders.push(n + ': require → ' + line.trim())
}
check('静态检查:无 fetch(data:) / eval / new Function / import / require', offenders.length === 0, offenders.slice(0, 3).join(' | '))
// ---------- 收尾 ----------
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+3 -3
View File
@@ -11,7 +11,7 @@ Content-Type: application/octet-stream # 原始图片字节;无 token、无 JS
比原扩展多做的:**补齐了超时**(`AbortController` + 可配 `timeoutMs`,原版没有任何超时)。
## 入口
- **节点漂浮菜单**「抠图」(选中 ref / out 节点时出现)
- **节点漂浮菜单**「抠图」(**仅 ref 图片输入节点**时出现;产图节点先「复制 / 插入为参考图节点」)
- 右键菜单「插件命令 → 抠图:选中节点」
## 设置
@@ -23,8 +23,8 @@ Content-Type: application/octet-stream # 原始图片字节;无 token、无 JS
## 发布
```bash
cd /Users/qiqi/open/github/iwb-arch
# 必须用 plugins-publish.mjs(会算 SRI integrity);plugins-publish.sh 不产 integrity,会被宿主 fail-closed 拒载
cd /Users/qiqi/open/github/image-workbench-web
# 两个发布器现在都会写 SRI integrity(.mjs 默认 dry-run,--upload 才写 KV)
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
node scripts/plugins-publish.mjs /tmp/plugin-xianyi-cutout.js --upload --version xianyi-cutout=1.0.1
```
+6 -2
View File
@@ -1,7 +1,11 @@
{
"name": "@iwb-plugin/xianyi-cutout",
"private": true,
"version": "1.0.1",
"version": "1.0.3",
"description": "鲜艺抠图:调用本机 30092 的 /rmbg 把节点图抠成透明底",
"ibwPlugin": { "id": "xianyi-cutout", "entry": "src/index.js", "apiVersion": 1 }
"ibwPlugin": {
"id": "xianyi-cutout",
"entry": "src/index.js",
"apiVersion": 1
}
}
+4 -4
View File
@@ -37,7 +37,7 @@
global.IWBPluginHost.register({
id: 'xianyi-cutout',
name: '鲜艺抠图',
version: '1.0.1',
version: '1.0.3',
apiVersion: 1,
capabilities: ['commands', 'canvas', 'canvasWrite', 'nodeActions'],
settings: {
@@ -86,7 +86,7 @@
ctx.commands.register({
id: 'cutout-selected',
title: '抠图:选中节点',
icon: 'ref',
icon: 'scissors',
run: function () {
const selected = ctx.canvas.getSelectedNode()
if (!selected) return Promise.reject(new Error('请先选中一个带图的节点'))
@@ -97,8 +97,8 @@
ctx.nodeActions.register({
id: 'cutout-node',
title: '抠图',
icon: 'ref',
appliesTo: function (node) { return Boolean(node) && (node.type === 'ref' || node.type === 'out') },
icon: 'scissors',
appliesTo: function (node) { return Boolean(node) && node.type === 'ref' },
run: function (node) { return cutoutOne(node.id) },
})