Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b1ad60e39 | ||
|
|
e1120ec52b | ||
|
|
c60ecc7366 | ||
|
|
3c58e2b07f | ||
|
|
1851f6cf04 | ||
|
|
b736389d1c | ||
|
|
9321356f59 | ||
|
|
0d14728224 | ||
|
|
67472f3019 | ||
|
|
0a3c3188fc | ||
|
|
596d5fdf82 | ||
|
|
dc7c1cc65a | ||
|
|
158ce77ad8 | ||
|
|
eca46fee54 | ||
|
|
383b28cc77 | ||
|
|
63a48047a3 | ||
|
|
a3417e9315 | ||
|
|
dce8aac1f3 | ||
|
|
a642e7f286 | ||
|
|
f9c700304b | ||
|
|
e6645f6e29 | ||
|
|
42435a0d39 | ||
|
|
77574b00b9 | ||
|
|
0b7c1b30f0 | ||
|
|
92dad3abad | ||
|
|
48052c96fb | ||
|
|
05dd343155 | ||
|
|
c078626a5c | ||
|
|
69da8059fc | ||
|
|
642a42c242 | ||
|
|
318d320ded | ||
|
|
1961488b57 | ||
|
|
82885a7733 | ||
|
|
a4a899f424 | ||
|
|
9891e819b4 | ||
|
|
017a71f43b | ||
|
|
759e097971 | ||
|
|
a742fea2db | ||
|
|
cad17e0aef | ||
|
|
0bf83c96b2 | ||
|
|
6f3eb0a06c | ||
|
|
1f833c5222 | ||
|
|
f136601869 | ||
|
|
3ecd07ef3c | ||
|
|
3eed42d43d | ||
|
|
dbbd558160 | ||
|
|
eec99144f3 | ||
|
|
3a4ebc2eb3 | ||
|
|
84c2c10c0c | ||
|
|
cb6dcd1813 | ||
|
|
3fcc003738 | ||
|
|
856e34a3f0 | ||
|
|
1a0998b1d4 | ||
|
|
cf93080d17 | ||
|
|
1ffe067e12 | ||
|
|
58d8d9c43a | ||
|
|
0e15e29c18 | ||
|
|
d8c8717826 | ||
|
|
9e400e2348 | ||
|
|
2f9a326159 | ||
|
|
56b5f49646 | ||
|
|
49b419251e | ||
|
|
57fc63dc10 | ||
|
|
36276455ea | ||
|
|
1afd5d7521 | ||
|
|
22ecd268cf | ||
|
|
0c39873a1a | ||
|
|
fa7c866457 | ||
|
|
fc199776d9 | ||
|
|
91ab3511ea | ||
|
|
576d24f163 | ||
|
|
9283e76f1a | ||
|
|
13a34073bd | ||
|
|
aff77cef75 | ||
|
|
ac62c3bfbc | ||
|
|
8e0697d4cd | ||
|
|
2fb9511f8b | ||
|
|
fbdaf48377 | ||
|
|
99480bf9c5 | ||
|
|
2ad699b64d | ||
|
|
fabe8d7aa1 | ||
|
|
2eacf5a81d | ||
|
|
fb20c97996 | ||
|
|
67a46dd03d | ||
|
|
fe4a64f98b | ||
|
|
78f8057384 | ||
|
|
ea5aa77b9c | ||
|
|
f2c634ff38 | ||
|
|
9623d932f7 | ||
|
|
b7eb9f8c28 | ||
|
|
5dba56363a | ||
|
|
d83f7f5eef | ||
|
|
9b24749481 | ||
|
|
371f114d69 | ||
|
|
06d8551107 | ||
|
|
0bc49d4eab | ||
|
|
39d7c9e086 | ||
|
|
5aeb354043 | ||
|
|
9fa45ff7b0 | ||
|
|
1ac0877f30 | ||
|
|
398500b952 | ||
|
|
e2253e56c2 | ||
|
|
67c6128d61 | ||
|
|
3bd6b4d9ff | ||
|
|
56a159486b | ||
|
|
4aa0e6affe | ||
|
|
3f2eb03fe3 | ||
|
|
3bbf1ea85d | ||
|
|
e9a6402373 | ||
|
|
ce575d2640 | ||
|
|
0ec11bfca8 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"nodes": [],
|
||||
"edges": [],
|
||||
"groups": []
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"activeCanvas": "Main"
|
||||
}
|
||||
@@ -447,7 +447,7 @@
|
||||
| 拆 `app.js` 但不处理钉点 | 一次红几百条,无法定位问题 |
|
||||
| 重排 529 个 tag | 代价大、收益小;已用 CHANGELOG 说明缓解 |
|
||||
| 用 `c8` / `nyc` 量本仓覆盖率 | **实测不可用**:src 模块用 `window.eval()` 加载(无脚本名),V8 无从归属。见规则库 §13.42 |
|
||||
| 删除生产 CSP 里的 `127.0.0.1:30092` | **不是残留**,是 2026-10-17 有意为「本地服务插件」做的安全边界调整(`CHANGELOG:226`、事实基线 §265-267) |
|
||||
| 删除生产 CSP 里的 `127.0.0.1:30092` | **不是残留**,是 2026-10-17 有意为「本地服务插件」做的安全边界调整(`CHANGELOG:226`、事实基线 §265-267)。**桌面客户端的 CSP 以 `tauri.conf.json` 为准**(本项目是桌面客户端,`_headers` 属旧网页部署、不约束桌面);v3.25.11 误删导致插件挂,见 `tests/desktop-csp-loopback-test.js` |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -14,6 +14,485 @@
|
||||
> 3. 核验正式地址版本 → 之后才移动 `stable` / `stable-verified-<日期>` 标签、更新本 CHANGELOG、写 GitHub Release(`gh release create`)。
|
||||
> 测试发现问题 → 改 → 再 `deploy:test`,正式环境不受影响。回滚点 `git reset --hard stable`。
|
||||
|
||||
## v3.25.30(2026-11-19)应用内浏览器 1.5.0 配套客户端 + 库面板浮窗可框选
|
||||
|
||||
**客户端(必须先于插件发版)**:插件 1.5.0 依赖本版的两处宿主能力 —— 设置 schema 的 `type:'custom'` 自定义渲染、
|
||||
以及 `canvasWrite.createNode` 支持插件节点变体(让面板「↗」把当前页直接放到画布上)。
|
||||
|
||||
- **库面板开着时画布仍能框选**:v3.25.21 的模态守卫把资源中心浮窗 `.iwb-fullmask` 也当真模态,
|
||||
整体拦掉画布按下 ⇒ 面板一开就无法框选(空格平移也被误拦)。守卫收窄到 `.iwb-modal-mask` /
|
||||
`.iwb-ctxmask`;手势进行中(框选/平移/拖节点/连线/缩放)`pointermove` / `pointerup` 不再按
|
||||
target 断流,避免指针划过浮窗时选择框卡住、松手收不了尾。
|
||||
- **图标**:ICONS 补 `globe`(lucide)——浏览器插件面板 tab 与「网页」节点此前声明了 globe
|
||||
但宿主图标库里没有,渲染成空白。
|
||||
- **右键菜单收二级**:一级只留 添加节点 / 插件节点 / 选中操作▸ / 该节点▸,不再一屏 18 项;
|
||||
插件节点单独成组并用分割线与内置节点隔开。
|
||||
- **插件设置自定义控件**:`type:'custom'` 让插件自己渲染书签管理器(分组、增删改、拖动排序),
|
||||
文本类控件改为说明在上、输入框左对齐。
|
||||
- **画布网页**:面板只 park 与之矩形相交的画布节点(原先「面板可见就整体 park」会让新建节点白屏);
|
||||
子 webview 四角圆角跟随 `--iwb-node-radius`,离屏 5 分钟自动回收进程。
|
||||
- e2e:新增「库面板浮窗开着时画布空白处仍能框选」回归;右键菜单相关三条用例改到「该节点▸」结构。
|
||||
|
||||
## v3.25.29(2026-11-19)画布网页:地址栏被盖住(坐标原点差)、内容跟随画布缩放
|
||||
|
||||
**症状**:网页节点里地址栏、前进/后退/刷新全被网页盖住,只剩左上角一小块按钮露出来;
|
||||
网页内容不跟着画布缩放,缩小画布后它反而按原宽度重排。
|
||||
|
||||
**根因(两个都在坐标换算上,实测拿到硬数据)**:
|
||||
|
||||
1. **坐标原点差**。`add_child` / `set_bounds` 的 LogicalPosition 以**窗口边框**左上角为原点,
|
||||
而 `getBoundingClientRect()` 以**内容视图**左上角为原点 —— macOS 标准标题栏下差 32pt。
|
||||
于是每个画布网页都整体**上浮 32px**,正好压住 34px 高的工具栏。
|
||||
最小工程实测:窗口 frame=1000×760,DOM innerHeight=728;子视图 y 传 200,实际落在 168;
|
||||
手动把 y 改成 232 后红框精确落在内容原点+(300,200)。
|
||||
修法:向 Rust 要窗口边框尺寸(`canvas_webview_metrics`),减去 `window.innerHeight`
|
||||
得到补偿值,推 rect 时加上。全屏时标题栏消失,差值自动回到 0。
|
||||
2. **页面缩放没跟着画布走**。rect 跟着画布缩,但页面 zoom 恒为 1 ⇒ 视口变窄后网页重排,
|
||||
看起来"内容没缩小"。现在 zoom = 画布缩放 × 用户缩放,网页像图片一样跟着画布一起缩放。
|
||||
|
||||
**顺带修的交互细节**:
|
||||
|
||||
- 工具栏重做:← → ⟳(加载中变"停止")、地址栏、`− 100% +` 缩放设定框(可直接输入百分比,
|
||||
双击回 100%)、↗ 独立窗口打开、✕ 关闭网页(节点保留,⟳ 可恢复)
|
||||
- 站内跳转后地址栏跟上真实地址(宿主流 `cwv-page` 事件 → `iwb-cwv-state`)
|
||||
- 新建节点自动用站点名做标题,多个网页节点并排时分得清
|
||||
- 取消"选中时内容内缩 12px":缩放手柄在节点外侧,本来就不用让位;点选不再让网页重排
|
||||
- 原生视图四边裁到节点、上边裁到工具栏底:布局再变也压不住按钮
|
||||
|
||||
版本 3.25.29;插件 browser 需 1.4.0。
|
||||
|
||||
## v3.25.28(2026-11-19)恢复画布内网页节点,修好「一动就白」
|
||||
|
||||
**先纠正 v3.25.27 的判断**:上一版把画布内网页整体撤掉了,理由是"平台限制修不干净"。
|
||||
用户补充的关键现象推翻了那个结论 —— **不动时有内容,移动 / 缩放节点 / 缩放画布之后就没了,
|
||||
只有某个缩放比例下能看**。这不是平台随机失效,而是我们自己两个策略的必然结果:
|
||||
|
||||
1. **「动就藏」**:单帧位移或尺寸变化 > 18px 就判定为"正在拖动",把网页藏起来,停 140ms 再显示。
|
||||
缩放画布、拖缩放手柄恰好都在这个阈值之上 ⇒ 一动就藏。
|
||||
2. **「小于 64×48 就隐藏」**:画布缩小后节点必然变小,交面积小于这个尺寸就整个隐藏
|
||||
⇒ 只有某个缩放比例区间能看见内容(用户说的"某一个画布缩放大小时显示"正是这条)。
|
||||
|
||||
用最小 Tauri 工程逐帧截图确认:子 webview 自己**连续 60 帧改尺寸、1×1 极值、连续移动、
|
||||
移出窗口再移回,全都不白**。平台侧是安全的,问题全在调度策略。
|
||||
|
||||
### 这版怎么改
|
||||
|
||||
- **取消「动就藏」**:移动 / 拖动 / 缩放全程保持可见,最多短暂错位。只有三种情况才隐藏:
|
||||
画布被切走、有模态遮罩、节点与画布的交集小于 2px(完全离开可视区)。
|
||||
- **取消尺寸门槛**:交集 ≥ 2px 就显示,不再有"缩到多小就看不见"的区间。
|
||||
- **一次 `set_bounds` 推位置+尺寸**(替代 `set_size` + `set_position` 两条消息):
|
||||
两条消息之间视图会短暂处于"新尺寸 + 旧位置"的中间态,这是白屏的另一来源。
|
||||
- **仍然永不调用 `show()`/`hide()`**(macOS 上 hide 之后再 show 会静默失效);
|
||||
隐藏 = 把视图停到窗口外(-20000),尺寸保持不变(裁到 1px 会触发 WebKit 重排)。
|
||||
- 推送节奏:位置变化随时跟(节流 40ms,≈25fps);**尺寸变化等静止 120ms 再推**,
|
||||
避免拖动缩放手柄 / 滚轮缩放时让 WebKit 每帧重排。
|
||||
- 保留自诊断:创建失败把 Rust 的 Err 原文写进节点 + 1.5s 重试;15 秒未加载完给提示;
|
||||
全程写 `_cwv.log`(创建 / 每条 bounds 采样 / page 事件)。
|
||||
|
||||
### 实测(本机真实应用,非最小工程)
|
||||
|
||||
- 画布上三个节点(baidu / huaban×2)全部加载出真实页面(花瓣首页搜索框、图片墙可见);
|
||||
- 窗口从 3228×2418 缩到 1180×760,网页仍在,内容按新尺寸重排;
|
||||
- `_cwv.log` 显示 bounds 持续推送、无 create 失败、无异常。
|
||||
|
||||
插件 `browser` 同步回到 **1.3.0**(重新注册节点类型 `web`,旧客户端会提示需要 v3.25.28+)。
|
||||
|
||||
## v3.25.27(2026-11-19)下线「画布内网页节点」
|
||||
|
||||
**结论先说:这条路走不通,功能撤掉,不留半成品。** 独立窗口浏览器(资源中心 →「浏览器」)不受影响,继续用。
|
||||
|
||||
为什么放弃:原生子 webview(`Window::add_child`)本质上是"贴在窗口上的一块外来图层",
|
||||
它不受画布 `overflow:hidden` 约束、不能被 DOM 遮挡、位置要每帧从 `getBoundingClientRect()` 反推。
|
||||
为了让它在画布里看起来像个节点,连续踩到三个 Tauri/macOS 的平台坑:
|
||||
|
||||
1. `hide()` → `show()` 静默失效(都返回 `Ok`,网页永久不再绘制);
|
||||
2. `get_webview_window("main")` 在出现任何子 webview 后**永久返回 `None`**;
|
||||
3. 子 webview 抢走指针事件 ⇒ 拖动必须用标题栏,缩放要内缩露出句柄。
|
||||
|
||||
第 1、2 条修完仍然只能做到"大体能用":换工作区、LOD 降级、快速拖拽、节点被遮挡这些
|
||||
日常操作都要靠"挪出窗口 / 延迟 900ms 再关 / 每帧推 bounds"这些脆弱补偿去兜。
|
||||
收益(在画布里看网页)远小于维护成本与不可控风险 ⇒ **下线**。
|
||||
|
||||
删掉的东西:
|
||||
|
||||
- Rust:`canvas_webview_ensure / bounds / navigate / action / state / close_all` 六个命令(约 250 行)及其诊断日志 `_cwv.log`;
|
||||
- 前端:`src/canvas-webview.js`(463 行位置同步引擎)与 `scripts/build.js` 里的模块登记(88 个模块);
|
||||
- 插件 browser:节点类型 `web`、`nodeTypes` 能力、对应样式与渲染(1.1.1 → **1.2.0**,已重新上架市场)。
|
||||
|
||||
**保留的**(与网页节点无关,都是独立 bug):
|
||||
|
||||
- `get_window` 取代 `get_webview_window`(窗口几何记忆、托盘显示/隐藏、单实例聚焦)——
|
||||
这些调用原先在窗口里有任何子 webview 时会静默失效;
|
||||
- `tauri` 的 `unstable` feature(`Manager::get_window` 也在它门下)。
|
||||
|
||||
画布上残留的「网页」节点不再有类型定义,右键删除即可。
|
||||
|
||||
## v3.25.26(2026-11-19)修第二个网页节点报「主窗口不存在」
|
||||
|
||||
v3.25.25 的节点会直接把这个错误写在界面上,反而一下就定位了:
|
||||
|
||||
- **根因**:`canvas_webview_ensure` 用 `get_webview_window("main")` 取宿主窗口,而 tauri 的这个 API 内部要求 `is_webview_window()` —— 该窗口下**所有** webview 的 label 都必须等于窗口 label。一旦 `add_child` 建出第一个 `cwv-xxx` 子 webview,这个条件立刻为假,`get_webview_window("main")` 就**从此永远返回 `None`**。
|
||||
- 后果:第一个网页节点能建;从第二个节点开始一律报「主窗口不存在」,1.5 秒重试永远失败。
|
||||
- 改用 `get_window("main")`(最小工程实测:建完子 webview 后 `get_webview_window(main)=None` 而 `get_window(main)=Some("main")`)。
|
||||
- **同一个坑还悄悄弄坏了窗口几何记忆**:`save_geom` / `restore_geom` 也用 `get_webview_window`,只要画布上有网页节点,关窗口时尺寸就存不下来。一并改成 `get_window`(托盘「显示主窗口」、单实例聚焦、托盘隐藏同样处理)。
|
||||
- `ensure` 取不到窗口时会写 `_cwv.log`,不再只留一句给用户看的文案。
|
||||
|
||||
## v3.25.25(2026-11-18)修画布内网页「永远是白的」
|
||||
|
||||
v3.25.24 的网页节点建得起来,但**画布一动网页就永久消失**,用户看到的一直是一块空白。这一版把根因堵住,并让以后类似问题能自解释。
|
||||
|
||||
- **根因:macOS 子 webview 的 `hide()` → `show()` 是静默失效的**。两个调用都返回 `Ok`,但网页不会回来(最小工程实测:建好的 example.com 在 hide 后 show,窗口里变回纯空白)。而位置同步引擎在每次快速平移/缩放/拖动时都会先隐藏,停稳再显示 —— 于是用户拖动一次画布,网页就再也回不来。
|
||||
- 改为**把视图挪到窗口外**(`-20000, -20000`)代替隐藏:NSView 在父视图外既不绘制也不接收事件,效果等价,且能移回来(同一最小工程验证有效)。`canvas_webview_bounds` 与 `ensure` 里不再调 `show()`。
|
||||
- **修 ensure 失败后永久卡白**:原实现先把 `open` 置 `true` 再发请求,一次失败就永远停在「已创建」,之后只推 bounds 而 Rust 侧根本没有这个 webview,重启才恢复。现在失败会回滚、1.5 秒后自动重试,`bounds` 返回「找不到 webview」时同样回滚重建。
|
||||
- **让故障自解释**(以前只能靠猜):
|
||||
- 新增 `_cwv.log`(`app_config_dir`)记录 ensure 的入参/结果/错误、bounds 采样、`page:started/finished`;
|
||||
- 创建失败时把 Rust 返回的原因直接写在节点里(红字 + 自动重试);
|
||||
- webview 建起来但 15 秒没收到 `page:finished`,节点提示可能是站点拒绝/证书/网络问题。加载结果由 Rust `emit("cwv-page")` 转给主窗口(子 webview 没有 IPC 权限)。
|
||||
- 模态遮罩检测改为**只认真正可见的遮罩**(尺寸 ≥ 8×8):这类元素关闭后常以 `display:none` 留在 DOM 里,按「存在」判断会让网页永远不显示。
|
||||
|
||||
## v3.25.24(2026-11-18)画布内的网页节点(原生子 webview)
|
||||
|
||||
上一版的应用内浏览器是**独立窗口**,用户要的是「网页长在画布上、能和参考图并排对照」。这一版补的就是这条路径。
|
||||
|
||||
- **`Window::add_child` 子 webview**:`canvas_webview_ensure / bounds / navigate / action / state / close_all` 六个命令,label 为 `cwv-<节点id>`。子 webview 不在 capabilities 里 ⇒ 加载的外部页面拿不到宿主 IPC。
|
||||
- 只有它才能真正嵌进画布:iframe 路线被 `X-Frame-Options` 挡死(实测 GitHub / 站酷 / Figma / Pinterest 全部拒绝),主窗口 CSP 也没有 `frame-src`。
|
||||
- `Cargo.toml` 的 tauri 依赖加 `unstable` feature —— 这是 `add_child` 的唯一入口。
|
||||
- **位置同步引擎 `src/canvas-webview.js`**(新增模块,自启动,app.js 零侵入):
|
||||
- 插件节点在内容区放一个 `data-iwb-cwv` 空锚点,模块扫到后每帧把它的屏幕矩形推给 Rust;亚像素抖动不触发 IPC。
|
||||
- 快速平移/缩放/拖动时先隐藏,停 140ms 后回来 —— 原生层追不上 DOM,不藏就是拖影。
|
||||
- 节点必须**完整落在画布内**才显示:原生层不受 `overflow:hidden` 约束,溢出就会盖住侧边栏并吃掉那边的点击。
|
||||
(实测修正:改成**裁到「节点 ∩ 画布」**——完全隐藏会让「画布不够大」变成一片白,用户以为功能坏了。)
|
||||
- 节点被选中时网页内缩 12px,露出边框和缩放手柄(原生层会盖住节点内部的手柄)。
|
||||
- 锚点消失(删节点/切工作区/LOD 降级)后延迟 900ms 才回收,避免缩放一次就重新加载页面。
|
||||
- **插件 browser 1.1.1**:新增画布节点类型「网页」(520×480,无端口),地址栏 + 后退/前进/刷新/关闭;`ctx.nodes.register` 支持声明初始宽度(`width`),`addPluginNode` 据此建节点。
|
||||
- 节点体检测宿主是否有 `IWBCanvasWebview` 引擎:旧客户端上直接提示「需要 v3.25.24 及以上」,而不是留一块白板(v3.25.24 首发踩到:插件先上架、客户端没升级 ⇒ 用户看到白屏且毫无线索)。
|
||||
- 已知限制(原生层物理属性,非缺陷):网页区域的鼠标事件由网页消费,拖动节点要用标题栏;节点被其他节点压住时网页仍然可见。
|
||||
|
||||
## v3.25.23(2026-11-18)应用内浏览器:独立窗口 + 插件上架市场
|
||||
|
||||
### 新增
|
||||
- **`open_browser_window`**:在应用内开一个独立 WebviewWindow(固定 label `browser`,复用同一个窗口),加载外部网站自己的页面。Tauri 的 CSP 只注入自身 HTML,外部页不受主窗口 `default-src 'self'` 约束 ⇒ 应用内浏览的正解是独立窗口,不是 iframe(iframe 会被 CSP 与站点 `X-Frame-Options` 双重拦死)。
|
||||
- **`browser_control` / `browser_state`**:主窗口发起的后退 / 前进 / 刷新 / 关闭,以及 `{open, url}` 状态查询。浏览器窗口本身不在 `capabilities` 的 `windows` 列表里 ⇒ **无 IPC 权限**,碰不到宿主 API。
|
||||
- **插件 `browser` 1.0.0**:面板 = 地址栏 + 书签,顶部状态行显示当前网址,控制按钮随状态启用;已上架 `market.maqiart.eu.org`(市场 8 个插件)。
|
||||
|
||||
### 修复
|
||||
- **浏览器窗口关不掉**:`on_window_event` 是应用级回调,`CloseRequested` 此前对所有窗口都 `prevent_close` + `hide` ⇒ 浏览器窗口点 ✕ 只是被藏起来,音频 / JS 继续在后台跑,且再也关不掉(只能退整个应用)。现在只有 `main` 收进托盘,其余窗口正常销毁。
|
||||
- **导航不再 eval**:复用窗口改用原生 `navigate()`,不往外部页面上下文注入 `location.href=` 字符串;切站后窗口标题跟着更新。
|
||||
- **面板切 tab 累积监听**:插件每次 `mount` 先解绑上一次 `settings.onChange`,避免监听器与已脱离文档的旧 DOM 树随切换次数增长。
|
||||
|
||||
### 发布链路(这次踩了五个坑,一起收了)
|
||||
- **更新源没跟上**:`latest.json`(客户端"检查更新"真正读的)由 `publish-update.sh` 生成,只跑 `release.sh` 会出现「下载页是 3.25.23、更新源还停在 3.25.22」⇒ 客户端永远升不了。现在两条链一次跑完,`latest.json` 带 `.app.tar.gz` 的 minisign 签名。
|
||||
- **`--notes` 被拆词**:`EXTRA="--notes $NOTES"` 展开按空格分词,说明只剩第一个词。改数组传参。
|
||||
- **首页被下载页顶掉**:两个文件都叫 `index.html`,同目录 `scp` 时后者覆盖前者。下载页单独传到 `$NAS_DIR/download/`。
|
||||
- **首页版本号不更新**:忘了跑 `gen-site.js`。发布时补上,并一起上传首页 / 插件页 / `plugins-index.json`。
|
||||
- **CDN 强缓存导致哈希不符**:Cloudflare 对 `updates/*.dmg` 是 `max-age=14400`,同名文件重传后 4 小时内仍返回旧字节。下载链接改为带内容指纹 `?h=<sha256前12位>`,字节一变 URL 就变;校验也按指纹回读。
|
||||
- **`create-dmg` 在 macOS 26 上必失败**(`bundle_dmg.sh` 的 `grep: bad regex`)⇒ 只让 tauri 打 `.app`(含签名产物),dmg 由 `hdiutil` 封。
|
||||
|
||||
### 调整
|
||||
- 窗口几何按 label 分别存取:主窗口沿用 `window-geom.json`(老用户位置不丢),浏览器窗口用 `browser-geom.json`(下限 800×600;中心点不在任何显示器内时只恢复尺寸)。
|
||||
- `docs/PLUGIN-SDK.md` 补市场发布第 4 步的实际命令(ssh / scp / chmod / 回读核验)与两个坑:NAS 上是只读位需先 `rm`;旧客户端二进制没有新命令时插件降级 `window.open`。
|
||||
|
||||
## v3.25.22(2026-11-18)外观自定义扩展:连线 / 画布 / 节点 / 预设
|
||||
|
||||
### 新增(设置 → 外观)
|
||||
- **连线**:默认色(亮/暗)、粗细 1~4px、线型(实线/虚线/点线)、高亮色(亮/暗,用于选中节点上下游/悬停/临时连线)。
|
||||
|
||||
- **画布**:底色(亮/暗,已有)、网格点颜色(亮/暗)、网格点大小 0.8~2.6px、网格间距 16~40px、网格显示开关。
|
||||
|
||||
- **节点**:底色(亮/暗)、边框色(亮/暗)、圆角 6~20px、选中描边 1~4px。
|
||||
|
||||
- **预设**:内置「默认 / 护眼深色 / 高对比 / 纸质」四套;可「保存当前为预设」(最多 12 个)、导出/导入外观 JSON;每分组与全局都有「恢复默认」。
|
||||
|
||||
### 实现
|
||||
- 全部落到 CSS 变量(`--iwb-edge-w` / `--iwb-edge-dash` / `--iwb-edge-hot` / `--iwb-node-radius` / `--iwb-node-sel-w` / `--iwb-grid-dot` / `--iwb-grid-size` / `--iwb-grid-gap` / `--iwb-grid-on`),
|
||||
|
||||
由 `src/ui-appearance.js` 的 `apply()` 按当前主题挑「亮/暗」那一套写入 `:root`,不涉及渲染逻辑变更。
|
||||
|
||||
- 不开放界面背景 / 面板底色 / 文字颜色(被大量 `color-mix` 派生,开放后易不可读)。
|
||||
|
||||
## v3.25.21(2026-11-18)自动下载文件名改回 gen_<时间戳>_<随机>.png
|
||||
|
||||
### 调整
|
||||
- 自动下载的文件名沿用图库既有约定 `gen_<毫秒时间戳>_<随机6位>.png`(不掺节点标题,避免不可读字符与同名冲突)。
|
||||
|
||||
- 同名仍然**不覆盖**:落盘前经 `uniqueName` 检测,已存在则自动加 `-1`/`-2` 后缀(已实测三次同名 → `-1` / `-2`)。
|
||||
- **设置面板操作不再穿透到画布**:打开设置/备份等模态层时,画布的指针按下直接忽略(此前在面板里拖动会被当成框选,松手把框内节点选中甚至移动)。
|
||||
|
||||
## v3.25.20(2026-11-18)图片导出目录:三态逻辑重做 + 取色器按钮修复
|
||||
|
||||
### 变更(工单:导出目录逻辑)
|
||||
- **「自动下载」改为真正的自动保存**:勾选后**出图完成即写入导出目录**;此前它只是「点下载不弹框」的开关,
|
||||
自动保存函数写好却从未被调用。实现落在新模块 `src/runtime-download-auto.js`,挂在结果归档的单一漏斗上(单节点/批量/输出面板全覆盖)。
|
||||
|
||||
- **点下载是否弹框,只由「有没有目录」决定**:设了目录 → 直接落盘;没设目录 → 弹选择框。不再看开关。
|
||||
|
||||
- **复选框无目录时灰掉**(必须先选目录),清空目录会同时关闭自动下载。
|
||||
|
||||
- **文件名 `gen_<时间戳>.png`**;同批次内自动加 `-2/-3` 序号,跨批次同名由 `uniqueName` 加后缀,**绝不覆盖**已有文件。
|
||||
|
||||
### 修复
|
||||
- 外观取色器底部「完成」按钮被十六进制输入框挤成两行:输入框改 `flex:1 1 0; min-width:0`,按钮 `flex:0 0 auto`。
|
||||
|
||||
## v3.25.19(2026-11-18)图库顶部两个下拉框紧凑化
|
||||
|
||||
### 优化
|
||||
- 图库顶栏的「插入尺寸」与「时间范围」下拉改为紧凑样式(`iwb-select-compact`):去掉「插入」前缀、
|
||||
选项文案缩短(全部/今天/7 天/30 天),宽度压到 62~84px,字号降到 `--fs-sm`;
|
||||
|
||||
顶栏按钮左右内边距同步收紧、`flex-wrap: nowrap`,窄面板下一行放得下。
|
||||
|
||||
### 说明
|
||||
- 仅样式与选项文案,行为与存储键(`iwb.insertSizeK`)不变。
|
||||
|
||||
## v3.25.18(2026-11-18)工单 #3:连线配色 / 备份瘦身 / 下载统一 / 图库插入尺寸档
|
||||
|
||||
### 修复与调整
|
||||
- **连线默认改灰色**(工单 ①):`--iwb-edge` 默认取 `--iwb-border2`(亮暗自适应);主题色只用于按钮、
|
||||
选中框、端口与「选中节点的上下游高亮连线」。外观应用时不再把连线强写成主题色。
|
||||
|
||||
- **备份页瘦身**(工单 ②):桌面版移除「清理本地数据」(它只清 localStorage,删不到资料目录,还会被启动自愈救回,
|
||||
属误导功能)与「本地自动备份」区块(桌面数据在资料目录,localStorage 快照价值近零)。网页版行为不变。
|
||||
|
||||
- **下载语义统一**(工单 ③):开关改名为「自动下载」并重写说明;新增**重名保护**(同名自动加 -1/-2 后缀,
|
||||
批量下载不再互相覆盖);文案明确设了目录 + 开启后所有下载入口都直接落盘。
|
||||
|
||||
- **主题选择迁入外观 tab**(工单 ④):通用页的「外观」子块与配色下拉迁到「设置 → 外观」作为第一项。
|
||||
|
||||
- **图库插入尺寸档**(工单 ⑤):图库顶部新增下拉(原图 / 2K / 1K / 0.5K,默认 1K,记忆上次选择),
|
||||
插入画布时按档位等比压缩(`src/image-compress.js` 新增 `toMaxEdge`),避免把 4K 原图塞进画布。
|
||||
|
||||
- **输出节点下载走本地**(工单 ⑥):输出结果的单图「下载」改为从资料目录的本地归档取图(原图优先),
|
||||
远端 URL 只作兜底;与图库下载、大图预览下载行为一致。
|
||||
|
||||
## v3.25.17(2026-11-18)图标细节:去掉系统灰底 + 新托盘符号
|
||||
|
||||
### 修复
|
||||
- **macOS Dock/启动台的灰色底衬**:macOS 26 对「带透明圆角」的旧式 .icns 会把图形缩进到系统底衬里,
|
||||
表现为黑图标外面套一圈浅灰。改为**不透明满幅**源图(黑底铺满整张 1024)后,系统直接把自己的圆角遮罩
|
||||
套上去 ⇒ 图标变成纯黑到边,灰圈消失。
|
||||
- **托盘图标换成新 IW 符号**:白底版的 IW 做**挖空**处理(圆角方块填充、W 镂空),符合 macOS 模板图规范
|
||||
(纯黑 + alpha,系统自动明暗反转)。
|
||||
|
||||
### 说明
|
||||
- `icon.icns` / 各尺寸 PNG 取自不透明满幅;`icon.ico` 仍取透明圆角版(Windows 侧圆角更好看)。
|
||||
- 仅图标资源变更,无功能改动。
|
||||
|
||||
## v3.25.16(2026-11-18)更换应用图标
|
||||
|
||||
### 变更
|
||||
- 应用图标换成新版(黑底圆角 + 白色 W),覆盖 macOS `.icns` / Windows `.ico` / 各尺寸 PNG 与 Store Logo。
|
||||
- 图标源为 1024px,内容满幅(不留内边距);托盘图标(`tray-template.png`)保持不变。
|
||||
- 随 `npx tauri icon` 一并清理了用不到的 `android/`、`ios/` 目录。
|
||||
|
||||
### 说明
|
||||
- 仅图标变更,无功能改动;mac 已发布,Windows 包在下次构建时自带新图标。
|
||||
|
||||
## v3.25.15(2026-11-18)彻底转桌面客户端:删除网页版部署面
|
||||
|
||||
### 变更
|
||||
- **删除网页版部署产物**:`_headers`、`functions/`(`api/img.js`、`plugins/[[path]].js`)、`wrangler.toml`,
|
||||
以及只测它们的 `tests/iwb-csp-gate.spec.js`、`tests/iwb-functions-headers.spec.js`、`tests/functions-api-test.js`、`tests/iwb-v32-web-test.js`。
|
||||
- **`scripts/serve-test.js` 退化为纯静态服务器**:不再解析 `_headers`、不再模拟 Pages Functions。
|
||||
- **`app.js` 清除网页代理分支**:图床下载 ③ 兜底、缩略图兜底、预览派生 `viaUrl`、显示缩略图 4 处 `/api/img` 全部删除,桌面端只走原生 HTTP。
|
||||
- **更新清单平台解耦**:`tauri.windows.conf.json` 的 updater 指向 `updates/latest-windows.json`;
|
||||
`publish-windows-update.sh` 改写独立清单,mac 发版不再丢弃 Windows 条目。
|
||||
- **README / docs/RELEASES.md** 改为桌面客户端口径。
|
||||
|
||||
### 说明
|
||||
- Windows 客户端 **需要在 3.25.15 手动装一次**(旧版的 updater 仍指向 `latest.json`),之后自动更新走独立清单。
|
||||
|
||||
## v3.25.14(2026-11-18)桌面 CSP 回归修复(鲜艺抠图)+ 外观 tab
|
||||
|
||||
### 修复
|
||||
- **桌面版 CSP 重新放行本地服务**:v3.25.11 的「CSP 清理」把 `http://127.0.0.1:30092` /
|
||||
`http://localhost:30092` 当遗留端口删掉,但它是 2026-10-17 有意为「本地服务插件」放宽的边界。
|
||||
后果:桌面版鲜艺抠图插件与批量导出的「走本地抠图」报 `Failed to fetch`,网页版正常(两份 CSP 互不相干)。
|
||||
|
||||
- **补门禁**:新增 `tests/desktop-csp-loopback-test.js`(运行时值断言,避开源码钉点棘轮),
|
||||
钉住「桌面 CSP 必须放行 30092」与「两份 CSP 的 loopback 例外不得漂移」。
|
||||
|
||||
### 新增
|
||||
- **设置 → 外观**:画布底色(亮/暗两套)+ 主题色(两套共用),取色器仿 Obsidian(SVH 方块 + 色相条 + RGB + 十六进制)。
|
||||
连线、端口、主按钮、选中框、进度动画统一吃 `--iwb-brand`;连线单独 `--iwb-edge`。
|
||||
实现落在 `src/ui-appearance.js`,`makeSave` 白名单已同步(否则保存即丢)。
|
||||
|
||||
## v3.25.13(2026-11-18)启动兜底:工作子目录缺失时自动补齐
|
||||
|
||||
### 修复
|
||||
- 启动时 `ensureDirs()` 补齐 `canvases/`、`library/`、`plugins/`、`trash/` 与
|
||||
`images/{canvas,gallery,thumbs,legacy}`(幂等)。
|
||||
- 为什么需要:Windows 全新安装缺 `images/canvas` 导致写图失败;目录被手工删掉时
|
||||
启动阶段读目录抛错会让首屏白屏(实测遇到过一次)。
|
||||
|
||||
### 验证
|
||||
把 `images/` 与 `library/` 整个删掉再启动 → 目录全部自动重建、应用正常渲染。
|
||||
|
||||
## v3.25.12(2026-11-18)Windows 丢图根因:images/canvas 目录不存在
|
||||
|
||||
### 根因
|
||||
Windows 全新安装的资料目录里 `images/` 只有 `thumbs/`(缩略图 writer 会自己 mkdir),
|
||||
**没有 `canvas/` 与 `gallery/`**。`kv.put` 写 blob 前不建目录 ⇒ `writeFile` 失败 ⇒
|
||||
blob 写入被判失败 ⇒ 退化到 Cache Storage(`{__cache}`)⇒ WebView2 重启后解析不到 ⇒ 图没了。
|
||||
mac 上之所以正常:老数据里 `images/canvas` 早就被迁移脚本建好了。
|
||||
|
||||
### 修复
|
||||
- `kv.put` 的 blob / dataURL 两条分支写盘前 `mkdir(images/<cat>, {recursive:true})`(幂等)。
|
||||
- 桌面端**不再回退 Cache Storage**:失败就让调用方把字节内联进画布,宁可画布变大也不丢图。
|
||||
|
||||
### 验证
|
||||
把 mac 上的 `images/canvas` 整个移走模拟全新安装 → 粘贴一张图:
|
||||
修前:目录不重建、assets 不变;修后:目录自动重建、`assets 52→53`、目录里出现 1 个文件。
|
||||
|
||||
## v3.25.11(2026-11-18)桌面迁移体检:单实例 / 外链 / 原生通知 / 窗口下限
|
||||
|
||||
### 修复
|
||||
- **单实例**:加 `tauri-plugin-single-instance`,第二次启动只聚焦已有窗口。
|
||||
多实例同时写同一个资料目录会把 data.json 与 canvases 写成不一致状态(这两天查的图片丢失就是这类)。
|
||||
- **外链不再把应用导航走**:捕获阶段拦截 `a[href^=http]`(含中键)+ `window.open` 兜底改走
|
||||
`open_external_url` 命令,由系统浏览器打开(新模块 `src/ui-desktop-shell.js`)。
|
||||
- **桌面原生通知**:WKWebView 不支持 Web Notification,出图完成提醒改走 `notify_desktop`。
|
||||
- **窗口尺寸下限**:恢复几何时 clamp 到 1024×640(与 minWidth/minHeight 对齐);
|
||||
实测过 1051×488 的窗口,该尺寸下画布渲染空白。
|
||||
- **按平台产物**:新增 `tauri.macos.conf.json`(app+dmg)与 `tauri.windows.conf.json`(nsis),
|
||||
Windows 不再顺带构建不受更新器支持的 msi。
|
||||
- **CSP 清理**:移除遗留的开发端口(30092 / 3425)。
|
||||
|
||||
## v3.25.10(2026-11-18)图片粘贴后重启丢失:根因是 blob 存储绑定错运行时
|
||||
|
||||
### 修复
|
||||
- **ImageBlobStore 惰性绑定**:原来在模块初始化时就 `create({ idb: IDB })`,那一刻资料目录尚未就绪,
|
||||
绑到的是浏览器/空实现运行时 ⇒ 图片字节写进了不会落盘的地方,画布里只留 `{__blob}` 引用,
|
||||
重启后解析不到 → 节点变占位图。现在按当前 runtime 懒绑定并按实例缓存。
|
||||
- **kv.put 失败可识别**:资料目录未就绪时返回裸 `false`,调用方用 `r.ok === false` 判断,
|
||||
`false.ok` 是 undefined ⇒ 被当成成功,产出指向空文件的引用。现在返回 `{ ok: false, error }`。
|
||||
|
||||
### 验证(实测)
|
||||
- 修复前:粘贴一张图 → `assets` 47→47、`images/canvas` 26→26(字节没落盘)
|
||||
- 修复后:粘贴一张图 → `assets` 47→48、`images/canvas` 26→27,节点为 `{__blob}`
|
||||
- 重启应用后:同一节点仍在、图片正常显示
|
||||
|
||||
## v3.25.9(2026-11-18)P0:图片登记表不再落后于画布 + 清理前交代清楚
|
||||
|
||||
### 修复
|
||||
- **登记表立即落盘**:图片写入 `images/` 后,`assets` 登记(在 data.json 里)原来是 800ms debounce,
|
||||
进程被强杀/崩溃时登记丢掉、画布引用还在 ⇒ GC 会把在用图片当孤儿。现在登记后立刻 `flush()`。
|
||||
- **清理确认弹窗报数**:除了「N 个未被引用」,还会显示「其中 M 张因画布引用自动保留」与
|
||||
「另有 K 处引用已缺图」,避免用户在不了解后果的情况下按确认。
|
||||
|
||||
### 新增
|
||||
- 单测 `tests/storage-gc-canvas-refs-test.js`:钉住「GC 必须扫画布引用并并入 used 集合」与「登记后必须 flush」。
|
||||
|
||||
## v3.25.8(2026-11-18)拖入同图被拦 + 图片节点变占位图
|
||||
|
||||
### 修复
|
||||
- **拖入同一张图被去重拦掉**:命中旧节点后不写 blob、只选中它,于是「图片数据缺失 → 重新拖入」
|
||||
这条唯一自愈路径被堵死。现在拖入一律新建节点并重写 blob,旧节点也会跟着恢复。
|
||||
- **图片清理误删在用图片**:`gcImages` 只信 `assets` 登记表;登记表落后于画布时,
|
||||
画布仍在引用的图片会被当孤儿挪进 trash/,节点随即变成占位图。现在把 `canvases/*.json`
|
||||
里的 `{__blob}` 也计入在用集合。
|
||||
|
||||
## v3.25.7(2026-11-18)剪贴板体检:大图卡顿、路径误判、粘贴落点
|
||||
|
||||
### 修复
|
||||
- **大图剪贴板卡顿**:原先 IPC 传裸 RGBA(12MP 照片 46MB → base64 62MB)。
|
||||
改为传 PNG:读方向由 Rust 编码,写方向直接把 Blob 的 PNG 字节发过去,体积降到几 MB。
|
||||
- **Finder「复制图片」被当成文本粘贴**:macOS 复制图片时常同时给 file:// 文本,
|
||||
classify 会落进文本分支贴出「路径提示词节点」。现在路径样式的文本先问原生剪贴板要图片。
|
||||
- **原生读图一直失效**:Rust 结构体字段是 `png_base64`,前端读的是 `pngBase64`,取不到值。
|
||||
结构体加 `#[serde(rename_all = "camelCase")]`,前端两种写法都兼容。
|
||||
- **节点组粘贴落点**:Ctrl+V 贴节点/节点组也走 `safeSeed`,面板打开时不会被遮住。
|
||||
|
||||
### 清理
|
||||
- 删除已废弃的 `rejectDup` 与 `pasteCtx.closeLibrary`(粘贴不再关闭库面板)。
|
||||
|
||||
## v3.25.6(2026-11-18)粘贴语义修正:不关库面板、贴鼠标处、允许同图重复
|
||||
|
||||
### 变更
|
||||
- 库面板(资源抽屉 / 资源中心)打开时**不再关闭它**,粘贴照常生效。
|
||||
- 落点:指针在画布可见区 → 贴指针位置;指针压在面板上 → 自动挪到面板旁,不再出现「贴了但被遮住」。
|
||||
- 同一张图**允许重复粘贴**(粘贴是显式动作,被同图去重挡掉像「按键没反应」)。
|
||||
同图去重仍保留给拖拽/批量导入等被动路径。
|
||||
|
||||
## v3.25.5(2026-11-18)库面板打开时粘贴失效
|
||||
|
||||
### 修复
|
||||
- 打开左侧资源抽屉 / 资源中心后,Ctrl+V 完全不响应:`overlayOpen()` 把库面板当成模态浮层,
|
||||
在 paste 入口直接 return。
|
||||
- 现在拆成两层判断:**真模态**(设置/帮助/右键菜单/连接菜单/放大编辑)仍不接管;
|
||||
**库面板**改为「先关面板再粘贴」(`pasteCtx.closeLibrary`),落点可见、不再出现「贴了但看不见」。
|
||||
- 库面板无法关闭时(老调用方)退回旧行为,不会静默吞掉粘贴。
|
||||
- 快捷键兜底也补上模态判断,设置面板打开时不会偷贴图片。
|
||||
|
||||
## v3.25.4(2026-11-18)复制节点贴不回来:剪贴板兜底修复
|
||||
|
||||
### 修复
|
||||
- **WKWebView 没有 `navigator.clipboard.write`** 时,`clipboard-graph.write()` 直接 return false,
|
||||
等于什么都没写进系统剪贴板 → Ctrl+C 之后 Ctrl+V 只能贴出「剪贴板里没有可粘贴的内容」。
|
||||
现在:写不了富文本就写**纯文本摘要**(navigator.writeText → 再退 Rust arboard),
|
||||
同时记住「这份摘要属于哪个 clip」;粘贴时按摘要**精确匹配**,命中就贴回节点组。
|
||||
- 新增 Rust 命令 `clipboard_write_text` / `clipboard_read_text`(arboard),Windows 同样可用。
|
||||
|
||||
### 验证
|
||||
- 单测 `tests/clipboard-graph-fallback-test.js`:无 `clipboard.write` 场景下能写原生文本且能匹配回 clip。
|
||||
|
||||
## v3.25.3(2026-11-17)桌面端剪贴板修复:复制/粘贴图片、粘贴文本为节点
|
||||
|
||||
> **状态:✅ 已发布** macOS 双架构 + Windows。
|
||||
|
||||
### 修复
|
||||
- **Cmd+C/Cmd+V 完全失效**:macOS 上 Tauri 应用没有应用菜单时,系统快捷键不会进入 WebView。
|
||||
现在补上 `Menu::default`(撤销/剪切/复制/粘贴/全选),文本粘贴为节点恢复正常。
|
||||
- **粘贴图片(Finder / 网页)**:WKWebView 的 paste 事件拿不到 Finder 复制的图片。
|
||||
新增 Rust 命令 `clipboard_read_image`(arboard),paste 无图时主动读系统剪贴板;
|
||||
另加 160ms 兜底:快捷键按下后没有 paste 事件也会尝试读图。
|
||||
- **复制图片到系统剪贴板**:`navigator.clipboard.write` / `ClipboardItem` 在 WKWebView 常不可用,
|
||||
新增 `clipboard_write_image` 原生兜底,预览复制与图库复制都走它。
|
||||
|
||||
### 新增模块
|
||||
- `src/clipboard-native.js`:RGBA ⇄ PNG Blob 转换与原生剪贴板调用(网页版自动不可用)。
|
||||
|
||||
## v3.25.2(2026-11-17)在线更新上线:应用内「检查更新 → 立即更新 → 自动重启」
|
||||
|
||||
> **状态:✅ 已发布** 双架构签名产物 + `latest.json` 更新源。
|
||||
|
||||
### 新增
|
||||
- **Tauri Updater 接入**:`tauri-plugin-updater` + `check_update`/`install_update` 两条 Rust 命令;
|
||||
设置 → 通用 → 版本与更新 里可检查、下载、安装并自动重启。
|
||||
- **签名发布**:`bundle.createUpdaterArtifacts` + minisign 密钥;`.app.tar.gz` 与 `.sig` 由
|
||||
`scripts/publish-update.sh` 一键产出并上传,同时生成双平台 `latest.json`。
|
||||
- **文档**:`docs/DESKTOP_UPDATE.md`(发布流程、密钥管理、故障排查)。
|
||||
|
||||
### 修复
|
||||
- 标注插件 v1.20.2:丢失 `mouseup` 后自动收笔 + 失焦/指针取消复位,修「画一次后画布不响应」。
|
||||
|
||||
## v3.25.1(2026-11-17)性能与数据卫生:回收 20.2MB 垃圾图片 + 图库清单去 base64(223 倍)+ 备份含插件
|
||||
|
||||
> **状态:代码已合并** 分支 `main`。Windows 安装包基于本版本构建。
|
||||
|
||||
### 性能 / 体积
|
||||
|
||||
- **图库清单去 base64**:`library/gallery/index.json` 367,887 → **1,646 字节**(只留 `thumbHash`,缩略图按需从 `images/thumbs/` 读)。
|
||||
- **画布显示缩略图落盘**:768px 派生结果写 `images/thumbs/<sha16>_768.jpg`,启动预读命中,省掉重复 4K 解码。
|
||||
- **`gcImages` 递归子目录**:此前只扫 `images/` 根目录,`canvas/gallery/thumbs/legacy` 里的孤儿永远清不掉。本机首跑回收 **20.2 MB**(21 个无引用文件)。
|
||||
- **`trash/` 30 天轮转**:清理只是移进 trash,现在超过 30 天自动删除。
|
||||
|
||||
### 数据卫生
|
||||
|
||||
- 清除 7 个坏画布文件(早期文件名少 2 字符的残留:`active.json` / `wsve.json` 等),画布 49 → 42(1341 节点完好)。
|
||||
- `assets` ↔ 文件一致性校验:0 缺失。
|
||||
|
||||
### 备份 / 结构
|
||||
|
||||
- **备份包含插件**:导出带 `items.plugins`(清单 + 源码),恢复写回 `<资料目录>/plugins/` 并合并清单 —— 换机不再丢插件。
|
||||
- **app.js 瘦身**:插件加载 / 市场 / 备份抽成 `src/runtime-plugin-loader.js`、`runtime-plugin-market.js`、`runtime-plugin-backup.js`。
|
||||
- **`_boot.log` 轮转**:超过 256KB 只保留最后 64KB。
|
||||
|
||||
### 已验证
|
||||
|
||||
- `verify:ci` exit 0(658 通过 / 0 新增失败)
|
||||
- 真实启动:5 个外部插件全部 `loaded`
|
||||
- 图库 7/7 条目可解析到缩略图文件,清单 `data` 字段全空
|
||||
|
||||
## v3.25.0(2026-11-17)桌面版:应用不再内置插件 + 插件市场 + 页内确认(替代原生 confirm)
|
||||
|
||||
> **状态:✅ 已出 macOS 安装包(dmg)** 分支 `main`,bump 提交 `9d0e57c`。
|
||||
|
||||
@@ -41,7 +41,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序
|
||||
node --check app.js 与 dist/app.js 语法
|
||||
check-dist.js 产物体检
|
||||
lint ESLint(src/ + app.js,正确性规则)
|
||||
test:unit 100 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
|
||||
test:unit 101 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
|
||||
test relay-task-graph-fixture + iwb-v32-web-test
|
||||
test:facts 事实基线守门(见 §5)
|
||||
typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js)
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
# 🎨 生图工作台 Web 版(Cloudflare Pages 免费部署)
|
||||
# 🎨 生图工作台(桌面客户端)
|
||||
|
||||
**在线访问:https://iwb.maqiart.eu.org**(自定义域名,Cloudflare 免费 HTTPS)
|
||||
|
||||
|
||||
基于 **OpenAI 兼容生图 API** 的节点式图形化生图工作台,纯前端实现(Cloudflare Pages 免费托管)。
|
||||
基于 **OpenAI 兼容生图 API** 的节点式图形化生图工作台。**Tauri v2 桌面客户端**(macOS / Windows),数据全部落在本机资料目录。
|
||||
|
||||
- **零后端**:数据保存在浏览器(localStorage + IndexedDB),图片生成直连兼容 API;Tuzi 生图固定使用 generations、要求 URL 响应,参考图允许公网 URL 与本地 Base64,且不自动重试
|
||||
- 与独立版功能一致:无限画布、节点连线、文生图/图生图、参数设置(比例/分辨率对齐接口)、提示词库、节点组收藏、图库、右键菜单、双击聚焦/适应视图、标注节点等
|
||||
@@ -13,7 +10,7 @@
|
||||
- 稳定性边界:保存失败会保留恢复快照并支持重试,离页前执行本地兜底;启动时检查 localStorage/IndexedDB 可用性并显示异常。
|
||||
- 构建:`npm run build` 用 **esbuild 压缩打包**(单 `dist/app.js` = `src/` 模块按序拼接 + `app.js`,另有压缩 `style.css`;`dist/` 不再有 `src/`),并生成带 Git commit 元数据的 `dist/version.json`。
|
||||
- 测试:`npm test` 运行 jsdom 契约测试,`npm run test:e2e` 构建后启动本地静态服务器并运行 Playwright Chromium 测试;`npm run verify` 执行完整验证。
|
||||
- 发布:`npm run deploy` 仅在完整验证通过后,将 `dist/` 上传到 Cloudflare Pages。
|
||||
- 发布:`./scripts/publish-update.sh <版本>` 构建 macOS 双架构并写更新清单;Windows 用 `./scripts/publish-windows-update.sh <setup.exe>` 重签并写独立清单(`latest-windows.json`)。
|
||||
|
||||
## 第三方许可
|
||||
|
||||
@@ -29,27 +26,24 @@
|
||||
|
||||
**想知道「这个项目还有什么待办」** → [`BACKLOG.md`](BACKLOG.md)(唯一入口:优先级 + 证据链接 + 明确不做的项)。
|
||||
|
||||
## 部署到 Cloudflare Pages(免费)
|
||||
## 构建与发布(桌面客户端)
|
||||
|
||||
### 本地手动发布(本仓库方式)
|
||||
> 已从网页版迁移为桌面客户端,**不再部署 Cloudflare Pages**(`_headers` / `functions/` / `wrangler.toml` 已删除)。
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run deploy # 正式站(--branch main)
|
||||
npm run deploy:test # 测试站(--branch test)
|
||||
npm run build # 前端产物 dist/(esbuild 压缩)
|
||||
npx tauri build # 桌面安装包(macOS: .app + dmg / Windows: nsis)
|
||||
```
|
||||
|
||||
`npm run deploy` 会先跑完整 `verify`,通过后再把 `dist/` 上传到 Cloudflare Pages。
|
||||
| 平台 | 命令 | 产物 |
|
||||
| --- | --- | --- |
|
||||
| macOS | `./scripts/publish-update.sh <版本>` | `updates/latest.json` + 双架构 dmg / app.tar.gz |
|
||||
| Windows | `./scripts/publish-windows-update.sh <setup.exe>` | `updates/latest-windows.json`(平台独立) |
|
||||
|
||||
### CI(只验证,不部署)
|
||||
两个平台的更新清单**完全解耦**:mac 发版不影响 Windows 版本号,反之亦然。
|
||||
|
||||
`.github/workflows/verify.yml` 在**推送到 `main` 与向 `main` 开 PR** 时执行验证门禁,分两个 job:`gate`(`npm ci` + `npm run verify:ci` = 构建 + 校验 + lint + 单测 + 事实守卫)与 `e2e`(Playwright + `npm run test:e2e`),**不自动部署**。
|
||||
|
||||
发布配置位于 `wrangler.toml`,Cloudflare Pages 输出目录固定为 `dist/`。部署前生成的 `version.json` 可用于确认线上版本和 Git commit。
|
||||
|
||||
### 绑定自定义域名(可选)
|
||||
|
||||
Pages 项目 → **Custom domains** → 添加域名(免费 HTTPS 自动签发)。
|
||||
CI:`.github/workflows/verify.yml` 在推送 `main` 与向 `main` 开 PR 时执行 `npm run verify:ci`。
|
||||
|
||||
## 使用前配置
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
/*
|
||||
X-Content-Type-Options: nosniff
|
||||
Referrer-Policy: no-referrer
|
||||
Permissions-Policy: camera=(), microphone=(), geolocation=()
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self'; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' https: data: blob:; connect-src 'self' https: http://127.0.0.1:30092 http://localhost:30092 http://127.0.0.1:3425 http://localhost:3425; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
|
||||
|
||||
/sw.js
|
||||
Cache-Control: no-cache, no-store, must-revalidate
|
||||
Service-Worker-Allowed: /
|
||||
@@ -50,16 +50,23 @@
|
||||
// 桌面端默认「点下载 = 直接写进下载目录,不弹窗」;只有写失败(目录被删/无权限)才退回对话框
|
||||
const wSilentSave = () => { try { const v = lsGet('iwb.silentSave', true); return v !== false } catch (e) { return true } }
|
||||
const wSetSilentSave = (v) => { try { lsSet('iwb.silentSave', !!v) } catch (e) { /* ignore */ } }
|
||||
// 自动下载(v3.25.20 用户裁定):勾选后「出图完成」自动存到导出目录;与「点下载是否弹框」解耦
|
||||
const wAutoDownload = () => { try { return lsGet('iwb.autoDownload', false) === true } catch (e) { return false } }
|
||||
const wSetAutoDownload = (v) => { try { lsSet('iwb.autoDownload', !!v) } catch (e) { /* ignore */ } }
|
||||
// 把 Blob 写进指定目录(不弹框)。目录必须此前由 dialog 选过:tauri-plugin-dialog 会把该目录
|
||||
// 递归加进 fs scope;scope 是「本次运行」的,重启后首次写入会失败 ⇒ 调用方回退到对话框。
|
||||
const wWriteBlobToDir = async (dir, name, blob) => {
|
||||
const join = wTauri && wTauri.path && wTauri.path.join
|
||||
const target = join ? await join(dir, name) : (dir.replace(/[\\/]+$/, '') + '/' + name)
|
||||
let finalName = name // 重名保护见 src/image-format.js 的 uniqueName(v3.25.18)
|
||||
try {
|
||||
const U = (typeof window !== 'undefined' && window.IWBImageFormat && window.IWBImageFormat.uniqueName) ? window.IWBImageFormat.uniqueName : null
|
||||
if (U) finalName = await U(dir, name, join, wTauri && wTauri.fs && wTauri.fs.exists)
|
||||
} catch (e) { /* 探测失败按原名写 */ }
|
||||
const target = join ? await join(dir, finalName) : (dir.replace(/[\\/]+$/, '') + '/' + finalName)
|
||||
await wTauri.fs.writeFile(target, new Uint8Array(await blob.arrayBuffer()))
|
||||
return true
|
||||
}
|
||||
// 桌面端「自动保存生成的图片」:没有 File System Access API ⇒ 写进默认下载文件夹。
|
||||
// 取字节走 plugin-http(不受图床 CORS 限制);失败只返回 false,不影响生图本身。
|
||||
// 桌面端自动保存生成图:写默认下载文件夹,取字节走 plugin-http(不受图床 CORS 限制),失败只返回 false
|
||||
const wSaveGenImageToDir = async (item) => {
|
||||
try {
|
||||
const dir = wDownloadDir()
|
||||
@@ -72,6 +79,16 @@
|
||||
return await wWriteBlobToDir(dir, name, blob)
|
||||
} catch (e) { return false }
|
||||
}
|
||||
// 出图自动下载:三态逻辑在 src/download-auto.js;这里只装配依赖
|
||||
const wAutoSaver = (typeof window !== 'undefined' && window.IWBDownloadAuto)
|
||||
? window.IWBDownloadAuto.create({
|
||||
getDir: wDownloadDir,
|
||||
isOn: wAutoDownload,
|
||||
resolveSrc: (item) => wResolveOutputSrc(item, true),
|
||||
write: wWriteBlobToDir,
|
||||
toast: (msg, type) => { try { const f = (typeof window !== 'undefined') ? window.__iwbAutoToast__ : null; if (typeof f === 'function') f(msg, type) } catch (e) { /* 组件外调用时忽略 */ } },
|
||||
})
|
||||
: null
|
||||
// 设置里的「打开数据目录」(走一个极小的 Rust 命令,见 src-tauri/src/lib.rs)
|
||||
const wOpenDataDir = async () => {
|
||||
const invoke = wTauri && wTauri.core && wTauri.core.invoke
|
||||
@@ -89,7 +106,8 @@
|
||||
// 路径来自 save() 的返回值:tauri-plugin-dialog 会把该路径动态加入 fs scope,
|
||||
// 因此 capabilities 里不需要静态放开任何目录(不放开 $HOME 这类宽权限)。
|
||||
// 「不再逐个询问」:设了默认目录就直接落盘;写失败(如重启后授权失效)自动退回对话框
|
||||
if (wSilentSave() && wDownloadDir()) {
|
||||
// 有目录就直接落盘,没有才弹框(v3.25.20:是否弹框由「有没有目录」决定,不再看开关)
|
||||
if (wDownloadDir()) {
|
||||
try { await wWriteBlobToDir(wDownloadDir(), fileName, blob); return true } catch (e) { /* 回退对话框 */ }
|
||||
}
|
||||
// 初始路径 = 默认下载文件夹 + 文件名(没设置则只给文件名,跟随系统上次位置)
|
||||
@@ -118,6 +136,8 @@
|
||||
return Promise.resolve(window.confirm(String(text)))
|
||||
}
|
||||
|
||||
// 桌面壳适配(外链 / 原生通知 / 链接拦截)落在 src/ui-desktop-shell.js
|
||||
try { if (window.IWBUIShell) window.IWBUIShell.installLinkGuard(wIsTauri) } catch (e) { /* ignore */ }
|
||||
if (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.configure) {
|
||||
window.IWBDesktop.configure({
|
||||
isTauri: wIsTauri,
|
||||
@@ -127,11 +147,15 @@
|
||||
pickDownloadDir: wPickDownloadDir,
|
||||
getSilentSave: wSilentSave,
|
||||
setSilentSave: wSetSilentSave,
|
||||
getAutoDownload: wAutoDownload,
|
||||
setAutoDownload: wSetAutoDownload,
|
||||
openDataDir: wOpenDataDir,
|
||||
marketList: wMarketList,
|
||||
marketInstalled: wMarketInstalled,
|
||||
marketInstall: wMarketInstall,
|
||||
marketUninstall: wMarketUninstall,
|
||||
clipboardReadImage: (window.IWBNativeClipboard || {}).readImage,
|
||||
clipboardWriteImage: (window.IWBNativeClipboard || {}).writeImage,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -317,11 +341,14 @@
|
||||
// 浏览器总通知:权限只在用户点击生图后的首次运行时请求;不支持/拒绝权限时静默降级。
|
||||
let browserNotificationPermissionPromise = null
|
||||
function prepareBrowserNotifications() {
|
||||
if (wIsTauri()) return // 桌面端用原生通知,不需要网页权限
|
||||
const N = typeof window !== 'undefined' && window.Notification
|
||||
if (!N || typeof N.requestPermission !== 'function' || N.permission !== 'default' || browserNotificationPermissionPromise) return
|
||||
try { browserNotificationPermissionPromise = N.requestPermission().catch(() => 'denied') } catch (e) { browserNotificationPermissionPromise = Promise.resolve('denied') }
|
||||
}
|
||||
function notifyBrowserGenerationDone(info) {
|
||||
// 桌面端没有 Web Notification:交给桌面壳模块发原生通知
|
||||
try { if (window.IWBUIShell && window.IWBUIShell.notifyGenerationDone(info)) return } catch (e) { /* ignore */ }
|
||||
const N = typeof window !== 'undefined' && window.Notification
|
||||
if (!N) return
|
||||
const emit = () => {
|
||||
@@ -374,7 +401,9 @@
|
||||
compression: { enabled: true, maxMB: 8, maxEdge: 2048, quality: 0.9, format: 'keep' },
|
||||
}
|
||||
const W_DEF_RETENTION = { enabled: true, maxFiles: 500, maxDays: 15 }
|
||||
const W_DEF_CANVAS = { generationConcurrency: 4, taskStallEndMs: 300000, autoSaveImages: true, backupOriginals: true }
|
||||
// 默认外观在 src/ui-appearance.js(DEFAULTS);这里只放引用,避免两处默认值漂移
|
||||
const W_DEF_APPEARANCE = (window.IWBUIApearance && window.IWBUIApearance.DEFAULTS) || { canvasBgLight: '#d9dbde', canvasBgDark: '#6f6f6f', accent: '#6b7280' }
|
||||
const W_DEF_CANVAS = { generationConcurrency: 4, taskStallEndMs: 300000, autoSaveImages: true, backupOriginals: true, appearance: W_DEF_APPEARANCE }
|
||||
// 任务条「结束」按钮出现的阈值:默认 5 分钟。判据是「该任务距上一次进展的时长」,
|
||||
// 而不是任务总时长 —— 多个变体(如 3 张)正常跑 6 分钟也不会误报"卡住"。
|
||||
const TASK_STALL_END_MIN = 60000
|
||||
@@ -817,16 +846,28 @@
|
||||
// objectURL **单一归属**:一律由 wRegisterBlobUrl 创建并登记(拿得回原 Blob,绕开 CSP 对 fetch(blob:) 的拦截),
|
||||
// 由 wImgUrlByRef 台账回收;**不调用** ImageBlobStore.resolveUrl/revokeAll —— 否则同一张图会有两套 URL
|
||||
// 与两套回收时机(§8.2「不要两套并用」)。实例只在顶层创建一次,绝不在渲染路径里重复 create。
|
||||
const ImageBlobStore = (function () {
|
||||
/* v3.25.10:**惰性绑定**运行时。
|
||||
* 原来在模块初始化时就 create({ idb: IDB }):那一刻资料目录可能还没就绪,
|
||||
* IDB 拿到的是浏览器/空实现运行时,于是图片字节写进了「不会落盘」的地方 ——
|
||||
* 画布里留下 {__blob} 引用,images/ 里没有文件、data.json 里没有登记;
|
||||
* 重启后引用解析不到 → 图片节点变占位图(用户实测)。现在按当前 runtime 懒绑定并按实例缓存。 */
|
||||
let wImageBlobStoreCache = null
|
||||
let wImageBlobStoreRuntime = null
|
||||
function wImageBlobStore() {
|
||||
try {
|
||||
if (typeof window === 'undefined') return null
|
||||
const Lib = window.IWBImageBlobStore
|
||||
if (!Lib || typeof Lib.create !== 'function') return null
|
||||
if (!IDB || typeof IDB.put !== 'function' || typeof IDB.get !== 'function') return null
|
||||
return Lib.create({ idb: IDB })
|
||||
const rt = storageRuntime()
|
||||
const idb = rt && rt.indexedDb
|
||||
if (!idb || typeof idb.put !== 'function') return null
|
||||
if (wImageBlobStoreCache && wImageBlobStoreRuntime === idb) return wImageBlobStoreCache
|
||||
wImageBlobStoreCache = Lib.create({ idb: idb })
|
||||
wImageBlobStoreRuntime = idb
|
||||
return wImageBlobStoreCache
|
||||
} catch (e) { return null }
|
||||
})()
|
||||
const IMG_BLOB_PREFIX = (ImageBlobStore && ImageBlobStore.PREFIX) ? String(ImageBlobStore.PREFIX) : 'imgblob_'
|
||||
}
|
||||
const IMG_BLOB_PREFIX = (function () { try { const S = wImageBlobStore(); return (S && S.PREFIX) ? String(S.PREFIX) : 'imgblob_' } catch (e) { return 'imgblob_' } })()
|
||||
const wImgUrlByRef = new Map() // 引用键('b:'+blobKey / 'c:'+cacheUrl)→ objectURL
|
||||
const wImgRefByUrl = new Map() // objectURL → 原引用对象(wBlobRefCache 被 FIFO 驱逐后仍能取回字节)
|
||||
const wImgUrlPending = new Set() // 正在解析的引用键(幂等:渲染路径会反复调用)
|
||||
@@ -870,7 +911,7 @@
|
||||
if (wImgUrlByRef.has(key) || wImgUrlPending.has(key) || wImgUrlFailed.has(key)) return
|
||||
wImgUrlPending.add(key)
|
||||
const job = wIsBlobRef(v)
|
||||
? (ImageBlobStore ? ImageBlobStore.getBlob(v.__blob) : Promise.resolve(null))
|
||||
? (wImageBlobStore() ? wImageBlobStore().getBlob(v.__blob) : Promise.resolve(null))
|
||||
: iwbCacheBlob(v.__cache)
|
||||
// 解析 Promise 存进 wImgUrlPendingPromise ⇒ 供 wResolveImgAsync 等待(预览类操作需要 URL 字符串)
|
||||
const p = Promise.resolve(job).then((blob) => {
|
||||
@@ -939,8 +980,8 @@
|
||||
async function wImgRefDataUrl(v) {
|
||||
if (typeof v === 'string') return v
|
||||
if (wIsBlobRef(v)) {
|
||||
if (!ImageBlobStore) return ''
|
||||
try { return await ImageBlobStore.resolveDataUrl(v.__blob) } catch (e) { return '' }
|
||||
if (!wImageBlobStore()) return ''
|
||||
try { return await wImageBlobStore().resolveDataUrl(v.__blob) } catch (e) { return '' }
|
||||
}
|
||||
if (wIsCacheRef(v)) { try { return (await iwbCacheRead(v.__cache)) || '' } catch (e) { return '' } }
|
||||
return ''
|
||||
@@ -1654,7 +1695,7 @@
|
||||
const RuntimeConstants = (typeof window !== 'undefined' && window.IWBRuntimeConstants) || { outputLimit: 10000, galleryRanges: {} }
|
||||
const GalleryHydration = typeof window !== 'undefined' && window.IWBGalleryHydration
|
||||
const galleryHydrator = GalleryHydration && typeof GalleryHydration.create === 'function'
|
||||
? GalleryHydration.create({ get: (key) => IDB.get(key) })
|
||||
? GalleryHydration.create({ get: (key) => IDB.get(key), thumb: (hash) => { const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null; return (F && typeof F.galleryThumb === 'function') ? F.galleryThumb(hash) : Promise.resolve('') } })
|
||||
: null
|
||||
const ModularOutputStore = typeof window !== 'undefined' && window.IWBStorageOutputs && ModularLocalStore && ModularIndexedStore
|
||||
? window.IWBStorageOutputs.create({ local: ModularLocalStore, indexedDb: ModularIndexedStore, key: OUT_KEY, prefix: 'out_', limit: RuntimeConstants.outputLimit, hydrate: galleryHydrator && ((items) => galleryHydrator.hydrate(items)) })
|
||||
@@ -1796,10 +1837,9 @@
|
||||
if (fkEarly && /^https:/i.test(fkEarly) && !wThumbProxyTried.has(fkEarly)) {
|
||||
wThumbProxyTried.add(fkEarly)
|
||||
try {
|
||||
// 桌面端没有 /api/img 代理(无服务端)⇒ 用 plugin-http 直取字节(Rust 侧请求,不受 CORS 限制)
|
||||
const pr = wIsTauri()
|
||||
? await wTauri.http.fetch(fkEarly)
|
||||
: await fetch('/api/img?url=' + encodeURIComponent(fkEarly), { mode: 'cors' })
|
||||
// 桌面客户端:用 plugin-http 直取字节(Rust 侧请求,不受 CORS 限制)
|
||||
if (!wIsTauri()) { if (fkEarly) wThumbFail.add(fkEarly); return null }
|
||||
const pr = await wTauri.http.fetch(fkEarly)
|
||||
// v3.87.52(丙方案 C5):交给 wRegisterBlobUrl(入参是 Blob,内部创建并登记 objectURL),
|
||||
// 避免此前的"创建了 blob URL 却不登记、不回收"✗
|
||||
if (pr.ok) return storeOutputThumb(Object.assign({}, item, { url: wRegisterBlobUrl(await pr.blob()) }))
|
||||
@@ -2287,14 +2327,28 @@
|
||||
// 图片引用化**唯一入口**:wSanitizeWs(画布保存)与 wRefValueAsync(收藏快照 / LRU 反 hydrate)都只经这里产出引用。
|
||||
// 失败回退链:{__blob}(IDB Blob 主通道)→ {__cache}(Cache Storage 兜底)→ null(调用方自行兜底,绝不抛错打断保存)。
|
||||
// 只有 ImageBlobStore.put 明确 r.ok===true 且带 key 才返回 {__blob},绝不产出「引用指向不存在的字节」。
|
||||
// 存储自检(桌面迁移排查用):把“字节到底能不能落盘”变成可复制的事实
|
||||
function wStorageSelfCheck() {
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
const st = (F && typeof F.stats === 'function') ? F.stats() : null
|
||||
return {
|
||||
tauri: wIsTauri(), fileEnabled: wFileStoreOn(), dir: (st && st.dir) || '',
|
||||
assets: (st && st.images) || 0, memKeys: (st && st.keys) || 0,
|
||||
blobStore: !!wImageBlobStore(), cryptoSubtle: !!(typeof crypto !== 'undefined' && crypto.subtle),
|
||||
caches: (typeof caches !== 'undefined'),
|
||||
}
|
||||
}
|
||||
async function wImgRefWrite(dataUrl) {
|
||||
if (W_IMG_BLOB_PRIMARY && ImageBlobStore) {
|
||||
if (W_IMG_BLOB_PRIMARY && wImageBlobStore()) {
|
||||
try {
|
||||
const r = await ImageBlobStore.put(dataUrl)
|
||||
const r = await wImageBlobStore().put(dataUrl)
|
||||
if (r && r.ok && r.key) return { __blob: String(r.key) }
|
||||
if (r && r.ok === false) swallow('image', new Error(r.error || 'blob-put-failed'))
|
||||
} catch (e) { swallow('image', e) } // 落 Blob 失败(配额/环境不支持)→ 回退 Cache,但计数留痕
|
||||
}
|
||||
// 桌面端不回退 Cache Storage:WebView2 重启后 {__cache} 解析不到(mac 上正常),
|
||||
// 回退等于“写成功但图没了”。失败就让调用方把字节内联进画布。
|
||||
if (wIsTauri()) return null
|
||||
const c = await iwbCacheWrite(dataUrl)
|
||||
return (c && c.__cache) ? c : null
|
||||
}
|
||||
@@ -2400,10 +2454,10 @@
|
||||
let raw = null
|
||||
try { raw = await IDB.get(key) } catch (e) { raw = null }
|
||||
if (!raw || typeof raw !== 'string' || raw.indexOf('data:') !== 0) return ref
|
||||
if (ImageBlobStore) {
|
||||
if (wImageBlobStore()) {
|
||||
try {
|
||||
const r = await ImageBlobStore.put(raw)
|
||||
if (r && r.ok && r.key) { const out = ImageBlobStore.refOf(r.key); wEnsureImgUrl(out); return out }
|
||||
const r = await wImageBlobStore().put(raw)
|
||||
if (r && r.ok && r.key) { const out = wImageBlobStore().refOf(r.key); wEnsureImgUrl(out); return out }
|
||||
} catch (e) { /* 落 BlobStore 失败 → 退回 Cache 引用 */ }
|
||||
}
|
||||
try { const c = await iwbCacheWrite(raw); if (c && c.__cache) { wEnsureImgUrl(c); return c } } catch (e) { /* ignore */ }
|
||||
@@ -2622,7 +2676,7 @@
|
||||
if (k.indexOf(IMG_BLOB_PREFIX) === 0) {
|
||||
if (!keep.has(k)) {
|
||||
wReleaseImgUrls(['b:' + k])
|
||||
try { if (ImageBlobStore) { const okDel = await ImageBlobStore.del(k); if (okDel === false) swallow('image', new Error('blob-del-failed')) } else await IDB.del(k) } catch (e) { swallow('image', e) }
|
||||
try { if (wImageBlobStore()) { const okDel = await wImageBlobStore().del(k); if (okDel === false) swallow('image', new Error('blob-del-failed')) } else await IDB.del(k) } catch (e) { swallow('image', e) }
|
||||
}
|
||||
continue
|
||||
}
|
||||
@@ -3271,6 +3325,8 @@
|
||||
// 钢笔笔头(lucide pen-tool):位图转矢量插件的专属图标。
|
||||
// 别与 white-bg-800 的 'vector-square' 共用 —— 两个插件同屏时图标一样,认不出谁是谁。
|
||||
'pen-tool': '<path d="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z"/><path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18"/><path d="m2.3 2.3 7.286 7.286"/><circle cx="11" cy="11" r="2"/>',
|
||||
// 地球(lucide globe):浏览器插件面板/网页节点的专属图标;此前插件声明 'globe' 但库里没有,tab 上渲染成空白
|
||||
globe: '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
|
||||
maximize: '<path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M21 8V5a2 2 0 0 0-2-2h-3"/><path d="M3 16v3a2 2 0 0 0 2 2h3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/>',
|
||||
// 底栏缩放(v3.24.83):放大镜 + / −。别用裸 plus/minus(那是「新建」的语义,跟缩放认不出来)
|
||||
'zoom-in': '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/><path d="M11 8v6M8 11h6"/>',
|
||||
@@ -3310,6 +3366,11 @@
|
||||
function wPrefersDark() {
|
||||
try { return !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) } catch (e) { return false }
|
||||
}
|
||||
// 外观(画布底色 + 主题色)实现在 src/ui-appearance.js:默认值/归一化/写 CSS 变量/对比度提示都在那边。
|
||||
// 这里只做装配(app.js 有行数棘轮,不再堆细节)。
|
||||
function applyAppearance(cfg) {
|
||||
try { const A = window.IWBUIApearance; if (A) A.apply(cfg, document.documentElement.classList.contains('theme-dark')) } catch (e) { /* ignore */ }
|
||||
}
|
||||
function applyTheme(t) {
|
||||
// 'system' 只是存下来的偏好值,真正落地成 dark/light 看系统当前外观
|
||||
const mode = (t === 'system') ? (wPrefersDark() ? 'dark' : 'light') : (t === 'dark' ? 'dark' : 'light')
|
||||
@@ -3443,8 +3504,6 @@
|
||||
// 组合/任务文本排序(方案1):relay 透明穿透,按「真实文本源节点」坐标统一排序。
|
||||
// 返回 [{ n: 真实文本源节点, text }];ref/停用节点跳过;batch 整块归到 batch 名下(保持既有 batch 语义,不改变其块位置)。
|
||||
// 方案1 组合排序:按每个 combine 入边展开为 (真实文本源, 文本),relay 透明穿透;batch 只取该边 batchSrcId 指定来源。
|
||||
|
||||
|
||||
function relayCompatTasks(ps, nodes, edges) {
|
||||
const r = resolveTaskGraph(ps, nodes, edges)
|
||||
const refs = (r.refs || []).flatMap(refArgsOf)
|
||||
@@ -3488,9 +3547,16 @@
|
||||
// 为空 = 跟随上游,节点体把上游文本显示出来(改一个字就落进自己的 data.text)。
|
||||
function nodeInheritOf(node, nodesArr, edgesArr) {
|
||||
const own = String((node && node.data && node.data.text) || '').trim()
|
||||
if (own) return { text: '', sourceNodeId: '', more: 0, own: true }
|
||||
const info = inheritedTextOf(node && node.id, nodesArr, edgesArr)
|
||||
return { text: String(info.text || ''), sourceNodeId: String(info.sourceNodeId || ''), more: Number(info.more) || 0, own: false }
|
||||
// 关键:先查上游。没有上游就根本没有「继承/已固定」这回事(用户是纯手写)
|
||||
const info = inheritedTextOf(node && node.id, nodesArr, edgesArr) || {}
|
||||
const hasUpstream = !!(info.sourceNodeId || String(info.text || '').trim())
|
||||
const base = {
|
||||
sourceNodeId: String(info.sourceNodeId || ''),
|
||||
more: Number(info.more) || 0,
|
||||
hasUpstream: hasUpstream,
|
||||
}
|
||||
if (own) return Object.assign({ text: '', own: true }, base)
|
||||
return Object.assign({ text: String(info.text || ''), own: false }, base)
|
||||
}
|
||||
|
||||
// 纯任务构建器:只根据节点图构造 prompt/参考图任务,不修改 state、不发送请求。
|
||||
@@ -3570,6 +3636,8 @@
|
||||
Promise.resolve().then(() => wAddOutputs(results)).then(() => {
|
||||
if (typeof refresh === 'function') return refresh()
|
||||
}).catch(() => { /* 图库缓存失败不影响画布结果 */ })
|
||||
// 出图自动下载(勾选且设了目录才生效;失败只提示,不影响生图)
|
||||
try { if (wAutoSaver) Promise.resolve().then(() => wAutoSaver.saveResults(results)).catch(() => {}) } catch (e) { /* ignore */ }
|
||||
return Promise.resolve(results)
|
||||
}
|
||||
|
||||
@@ -4076,6 +4144,12 @@
|
||||
async function copyImageToClipboard(srcOrBlob) {
|
||||
if (!srcOrBlob) throw wCopyError('format', W_COPY_HINT.format)
|
||||
if (!navigator.clipboard || typeof navigator.clipboard.write !== 'function' || typeof ClipboardItem === 'undefined') {
|
||||
// 桌面端兜底:WKWebView 里 ClipboardItem 常不可用,改走原生 arboard 写图片
|
||||
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
|
||||
if (D && D.clipboardWriteImage) {
|
||||
const okNative = await D.clipboardWriteImage(srcOrBlob)
|
||||
if (okNative) return srcOrBlob
|
||||
}
|
||||
throw wCopyError('unsupported', W_COPY_HINT.unsupported)
|
||||
}
|
||||
// 先转 PNG 再写剪贴板(任何输入都产出 image/png)
|
||||
@@ -4083,6 +4157,11 @@
|
||||
try {
|
||||
await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
|
||||
} catch (err) {
|
||||
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
|
||||
if (D && D.clipboardWriteImage) {
|
||||
const okNative = await D.clipboardWriteImage(png)
|
||||
if (okNative) return png
|
||||
}
|
||||
const msg = String((err && err.message) || err)
|
||||
// 没有写权限(页面失焦/未授权)也归为「浏览器不支持剪贴板图片」一类,附浏览器原文便于排查
|
||||
throw wCopyError('unsupported', W_COPY_HINT.unsupported + '(' + msg + ')')
|
||||
@@ -4304,17 +4383,17 @@
|
||||
}
|
||||
}
|
||||
} catch (e) { /* 继续兜底 */ }
|
||||
// ③ **本站同源代理**兜底(functions/api/img.js;跨域图床专用。不经任何第三方)
|
||||
// ③ 原生 HTTP 兜底(Rust 侧请求,不受 CORS 限制)
|
||||
// 本项目是桌面客户端,没有服务端同源代理(旧的 functions/api/img.js 已随网页版删除)
|
||||
try {
|
||||
// 桌面端没有同源代理:改用 plugin-http 直连(Rust 侧请求,不受 CORS 限制)
|
||||
const r2 = wIsTauri()
|
||||
? await wTauri.http.fetch(su)
|
||||
: await fetch('/api/img?url=' + encodeURIComponent(su), { mode: 'cors' })
|
||||
if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast(wIsTauri() ? '已通过原生 HTTP 取图保存' : '该图床不支持直连下载,已通过本站代理保存'); return }
|
||||
if (wIsTauri()) {
|
||||
const r2 = await wTauri.http.fetch(su)
|
||||
if (r2.ok) { downloadBlob(await r2.blob()); wDownloadToast('已通过原生 HTTP 取图保存'); return }
|
||||
}
|
||||
} catch (e) { /* 继续兜底 */ }
|
||||
// ④ 最后兜底:新标签打开(右键/长按另存)——绝不静默失败
|
||||
try {
|
||||
window.open(su, '_blank', 'noopener')
|
||||
try { window.IWBUIShell ? window.IWBUIShell.openExternal(su) : window.open(su, '_blank', 'noopener') } catch (e) { /* ignore */ }
|
||||
wDownloadToast('该图床不支持直接下载,已在新标签打开图片:请右键「图片另存为」')
|
||||
} catch (e) {
|
||||
wDownloadToast('下载失败:' + ((e && e.message) || '未知原因'))
|
||||
@@ -4569,7 +4648,7 @@ const tbCenterSeed = (type, refs) => {
|
||||
el('div', { className: 'iwb-crash-actions' },
|
||||
el('button', { className: 'iwb-btn iwb-btn-primary', onClick: this.retry }, '尝试恢复'),
|
||||
el('button', { className: 'iwb-btn', onClick: () => { try { location.reload() } catch (e) { /* ignore */ } } }, '重新加载页面'),
|
||||
el('button', { className: 'iwb-btn', title: '复制错误记录与内存采样(不含 Key、提示词和图片)', onClick: (ev) => { let t = '{}'; try { t = CrashLog ? JSON.stringify(CrashLog.report({ version: APP_VERSION }), null, 2) : '{}' } catch (e) { /* ignore */ } const cp = (typeof window !== 'undefined' && window.IWBClipboardCopy) || null; if (cp) cp.copyWithButton(t, ev && ev.currentTarget); else { try { navigator.clipboard.writeText(t) } catch (e) { /* ignore */ } } } }, '复制诊断信息'),
|
||||
el('button', { className: 'iwb-btn', title: '复制错误记录与内存采样(不含 Key、提示词和图片)', onClick: (ev) => { let t = '{}'; try { const rep = CrashLog ? CrashLog.report({ version: APP_VERSION }) : {}; try { rep.storageSelfCheck = wStorageSelfCheck() } catch (e) { rep.storageSelfCheck = { error: String((e && e.message) || e) } } t = JSON.stringify(rep, null, 2) } catch (e) { /* ignore */ } const cp = (typeof window !== 'undefined' && window.IWBClipboardCopy) || null; if (cp) cp.copyWithButton(t, ev && ev.currentTarget); else { try { navigator.clipboard.writeText(t) } catch (e) { /* ignore */ } } } }, '复制诊断信息'),
|
||||
),
|
||||
el('div', { className: 'iwb-hint' }, '完整记录在「设置 → 诊断」里,可导出 JSON'),
|
||||
),
|
||||
@@ -4621,10 +4700,9 @@ const tbCenterSeed = (type, refs) => {
|
||||
const Derive = (typeof window !== 'undefined') ? window.IWBImagePreviewDerive : null
|
||||
if (!Derive || typeof Derive.create !== 'function' || typeof document === 'undefined') return v
|
||||
previewPending.add(key)
|
||||
// 跨域图必须走同源代理(否则 fetch 必失败 ⇒ 负缓存后等于没做 ✗,见 §8.3 坑 2)
|
||||
// 桌面端没有 /api/img 代理:不给 viaUrl,让派生器直连(失败即负缓存并回退原图,不影响显示)
|
||||
const viaUrl = (/^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0) && !wIsTauri())
|
||||
? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : undefined
|
||||
// 桌面客户端没有同源代理(旧的 functions/api/img.js 已随网页版删除)⇒ 派生器直连;
|
||||
// 跨域失败即负缓存并回退原图,不影响显示。
|
||||
const viaUrl = undefined
|
||||
let inst = null
|
||||
try { inst = Derive.create({ maxEdge: PREVIEW_MAX_EDGE, quality: 0.82 }) } catch (e) { inst = null }
|
||||
if (!inst || typeof inst.deriveUrl !== 'function') { previewPending.delete(key); wPreviewPick(key, v); return v }
|
||||
@@ -4643,6 +4721,48 @@ const tbCenterSeed = (type, refs) => {
|
||||
previewUrls.clear(); previewPending.clear()
|
||||
}
|
||||
|
||||
// 显示缩略图落盘(768px):下次启动直接读文件,不用再解码原图
|
||||
const DISPLAY_THUMB_HASH_MAX = 512
|
||||
const displayThumbSaved = new Set()
|
||||
function wStoreMod () {
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
return (F && typeof F.readDisplayThumb === 'function') ? F : null
|
||||
}
|
||||
function wSaveDisplayThumb (key, dataUrl) {
|
||||
const F = wStoreMod()
|
||||
if (!F || !key || !dataUrl) return
|
||||
if (displayThumbSaved.has(key) || displayThumbSaved.size > 2000) return
|
||||
displayThumbSaved.add(key)
|
||||
wSha256(String(key)).then(function (hex) {
|
||||
try { F.writeDisplayThumb(hex.slice(0, 16), dataUrl) } catch (e) { /* ignore */ }
|
||||
}).catch(function () { /* ignore */ })
|
||||
}
|
||||
async function wPreloadDisplayThumbs (nodes) {
|
||||
const F = wStoreMod()
|
||||
if (!F || !Array.isArray(nodes) || !nodes.length) return 0
|
||||
const keys = []
|
||||
for (const n of nodes) {
|
||||
const d = n && n.data
|
||||
if (!d) continue
|
||||
const v = wResolveImg(d.data) || d.url
|
||||
if (!v || typeof v !== 'string' || v.indexOf('data:') === 0) continue
|
||||
const key = wDisplayThumbKey(v)
|
||||
if (!key || displayThumbs.has(key) || keys.indexOf(key) >= 0) continue
|
||||
keys.push(key)
|
||||
if (keys.length >= DISPLAY_THUMB_HASH_MAX) break
|
||||
}
|
||||
let n = 0
|
||||
for (const key of keys) {
|
||||
try {
|
||||
const hex = await wSha256(String(key))
|
||||
const dataUrl = await F.readDisplayThumb(hex.slice(0, 16))
|
||||
if (dataUrl) { displayThumbs.set(key, dataUrl); displayThumbSaved.add(key); n++ }
|
||||
} catch (e) { /* 单张失败忽略 */ }
|
||||
}
|
||||
if (n && typeof wThumbBump === 'function') { try { wThumbBump() } catch (e) { /* ignore */ } }
|
||||
return n
|
||||
}
|
||||
|
||||
function wDisplayThumbOf(v) {
|
||||
// C3:结果项 / 图片节点的 data 可能是引用对象(hydrate 直出)→ 先解析成显示 URL
|
||||
if (v && typeof v === 'object') v = wResolveImg(v)
|
||||
@@ -4663,10 +4783,8 @@ const tbCenterSeed = (type, refs) => {
|
||||
if (displayThumbs.size >= DISPLAY_THUMB_CACHE_MAX) { const first = displayThumbs.keys().next().value; if (first !== undefined) displayThumbs.delete(first) }
|
||||
displayThumbs.set(key, val)
|
||||
}
|
||||
const isRemoteHttp = /^https?:\/\//i.test(v) && (typeof location === 'undefined' || v.indexOf(location.origin + '/') !== 0)
|
||||
// 桌面端没有代理:直接给原地址(<img> 不受 CORS 限制,能正常显示;canvas 降采样失败会回退原图)
|
||||
img.src = (isRemoteHttp && wIsTauri()) ? v
|
||||
: (isRemoteHttp ? (location.origin + '/api/img?url=' + encodeURIComponent(v)) : v)
|
||||
// 桌面客户端没有同源代理:直接给原地址(<img> 不受 CORS 限制,能正常显示;canvas 降采样失败会回退原图)
|
||||
img.src = v
|
||||
img.onload = () => {
|
||||
try {
|
||||
const iw = img.naturalWidth || 0, ih = img.naturalHeight || 0
|
||||
@@ -4679,6 +4797,7 @@ const tbCenterSeed = (type, refs) => {
|
||||
const small = cv.toDataURL('image/jpeg', 0.78)
|
||||
if (displayThumbs.size >= DISPLAY_THUMB_CACHE_MAX) { const first = displayThumbs.keys().next().value; if (first !== undefined) displayThumbs.delete(first) }
|
||||
wRememberThumb(small)
|
||||
try { wSaveDisplayThumb(key, small) } catch (e) { /* ignore */ }
|
||||
displayThumbPending.delete(key)
|
||||
if (typeof wThumbBump === 'function') { try { wThumbBump() } catch (e) { /* ignore */ } }
|
||||
} catch (e) { displayThumbPending.delete(key); wRememberThumb(v) } // 失败也记下:不再每次渲染重复解码整图
|
||||
@@ -4945,7 +5064,7 @@ const tbCenterSeed = (type, refs) => {
|
||||
try {
|
||||
IWNodeBodies.inject({ el, I, LocalTextField, autoGrow, nodePreviewRefsV2, nodeInheritOf, combineSourcePairs, isPluginTypeId,
|
||||
orderedUniqueRefNodes, uploadRefToImageHost, wDisplayThumbOf, wImportImage, wPreviewUrlOf, wRawCfg, wResolveImg,
|
||||
wThumbSrc, downloadUrl, isImageProducer, outProgUI, outThumbCache,
|
||||
wThumbSrc, downloadUrl, wResolveOutputSrc, isImageProducer, outProgUI, outThumbCache,
|
||||
wPluginNodeVariants, wPluginVariantMeta, isBatchSrc, batchSrcText, compareCanvasTextOrder,
|
||||
GenParams, RATIOS, RES_KEYS, RES_MAP, cachedGenerationTasks, classifyErr, fmtDur, presetDisplayName,
|
||||
ratioOfSize, resOfSize, taskStallEndMs, wDedupeTaskIds, React, ReactDOM })
|
||||
@@ -5377,7 +5496,7 @@ const tbCenterSeed = (type, refs) => {
|
||||
W_KEEP,
|
||||
IDB,
|
||||
IMG_BLOB_PREFIX,
|
||||
ImageBlobStore,
|
||||
get ImageBlobStore() { return wImageBlobStore() },
|
||||
ModularBackupStore,
|
||||
SchemaVersions,
|
||||
StorageContract,
|
||||
@@ -5548,7 +5667,8 @@ const tbCenterSeed = (type, refs) => {
|
||||
return null
|
||||
},
|
||||
createNode: (type, x, y, data) => {
|
||||
if (!NODE_TYPES.has(type)) return null
|
||||
// 插件节点传的是变体 id(web/style…):不在 NODE_TYPES 里,交给 addPluginNode 拼出 plugin:<插件>:<变体>
|
||||
if (!NODE_TYPES.has(type)) return addPluginNode(type, x, y, data) || null
|
||||
const spot = (CanvasGeometry && CanvasGeometry.wantsDefaultSpot(x, y)) ? findSpot(type) : placeAtDrop(type, x, y)
|
||||
const node = { id: uid('n'), type, x: spot.x, y: spot.y, data: Object.assign({}, cloneNodeDefaults(type), data || {}) }
|
||||
commitCanvas(refs.nodes.concat([node]), undefined, undefined)
|
||||
@@ -5604,6 +5724,15 @@ const tbCenterSeed = (type, refs) => {
|
||||
const td = useTextDialog()
|
||||
const outputRequestSeq = useRef(0)
|
||||
const [histSel, setHistSel] = useState([])
|
||||
// 图库插入尺寸档(v3.25.18 工单 ⑤):原图 / 2k / 1k / 0.5k,记忆上次选择
|
||||
const INSERT_K = { orig: 0, '2k': 2048, '1k': 1024, '0.5k': 512 }
|
||||
const [insertK, setInsertK] = useState(() => { try { const v = lsGet('iwb.insertSizeK', '1k'); return INSERT_K[v] === undefined ? '1k' : v } catch (e) { return '1k' } })
|
||||
const setInsertKPersist = (v) => { setInsertK(v); try { lsSet('iwb.insertSizeK', v) } catch (e) { /* ignore */ } }
|
||||
// 按选中档位压缩插入图(算法在 src/image-compress.js 的 toMaxEdge)
|
||||
const shrinkForInsert = (dataUrl) => {
|
||||
if (insertK === 'orig') return Promise.resolve(dataUrl)
|
||||
try { return _imgCompressFn('toMaxEdge')(dataUrl, INSERT_K[insertK], 0.9).catch(() => dataUrl) } catch (e) { return Promise.resolve(dataUrl) }
|
||||
}
|
||||
const selectAllHistory = () => setHistSel(histFiltered.map((f) => f.name))
|
||||
const invertHistorySelection = () => setHistSel(histFiltered.filter((f) => !histSel.includes(f.name)).map((f) => f.name))
|
||||
// 下载选中的图片:逐个取本地原图/缩略图并触发下载(间隔 220ms 防浏览器连续下载拦截)
|
||||
@@ -5915,7 +6044,12 @@ const tbCenterSeed = (type, refs) => {
|
||||
// 视口持久化 hooks(阶段二 2026-11-07):从 Workbench 抽到 src/ui-workbench-hooks.js
|
||||
// 变量名保持不变 ⇒ 下游 viewportRef / activeWsRef / flushViewport 的调用点零改动
|
||||
const { viewportRef, activeWsRef, flushViewport } = IWWorkbenchHooks.useViewportPersistence(activeWsId, viewport)
|
||||
// 自动下载的提示回调(模块级装配拿不到组件闭包,这里挂到全局槽)
|
||||
try { window.__iwbAutoToast__ = (msg, type) => setNotice({ type: type === 'err' ? 'err' : 'ok', text: msg }) } catch (e) { /* ignore */ }
|
||||
refs.config = config
|
||||
// 外观:配置到位/切换主题时把画布底色与主题色写到 :root(放在 config 同步之后,
|
||||
// 否则首屏拿不到配置,改完颜色要重启才生效)
|
||||
useEffect(() => { try { applyAppearance(config) } catch (e) { /* ignore */ } }, [config, theme])
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
// 启动时一次性迁移历史 localStorage 里的 base64 大图到 IndexedDB(释放空间,治撑爆)
|
||||
@@ -6173,6 +6307,8 @@ const tbCenterSeed = (type, refs) => {
|
||||
refs.syncing = true // 切换/同步载入不触发自动保存(避免轮询-保存死循环)
|
||||
setSel([]); setSelEdge(null)
|
||||
openSession(id) // S3:先激活 session,再从它加载历史(session 化)
|
||||
// 显示缩略图预热(768px 文件已存在就直接命中,省掉一次 4K 解码)
|
||||
try { setTimeout(function () { wPreloadDisplayThumbs(ns).catch(function () { /* ignore */ }) }, 0) } catch (e) { /* ignore */ }
|
||||
const sess = sessionsStore.get(id)
|
||||
if (sess) { sess.nodes = ns; sess.edges = es; sess.groups = gs; sess.dirty = false } // S6:装载即同步 session 并清脏(装载不算本地编辑)
|
||||
refs.history = (sess && sess.history) ? sess.history : { stack: [], idx: -1 } // S3:历史随 session(不再全局清空)
|
||||
@@ -6777,7 +6913,7 @@ const tbCenterSeed = (type, refs) => {
|
||||
}
|
||||
const onMove = (e) => {
|
||||
const target = e && e.target
|
||||
if (target && target.closest && target.closest('.iwb-fullmask, .iwb-lib, .iwb-lib-embedded, .iwb-drawer, .iwb-toolbar, .iwb-rightrail, .iwb-wsrail, .iwb-statusbar, .iwb-minimap, .iwb-hint-bottom, .iwb-modal-mask, .iwb-ctxmask')) return
|
||||
if (!(refs.box || refs.pan || refs.drag || refs.resize || refs.groupResize || refs.connFrom) && target && target.closest && target.closest('.iwb-fullmask, .iwb-lib, .iwb-lib-embedded, .iwb-drawer, .iwb-toolbar, .iwb-rightrail, .iwb-wsrail, .iwb-statusbar, .iwb-minimap, .iwb-hint-bottom, .iwb-modal-mask, .iwb-ctxmask')) return // 手势进行中(框选/平移/拖节点/连线/缩放)不按 target 断流:否则指针划过库面板,框选卡住、松手收不了尾
|
||||
const vp = refs.viewport
|
||||
if (!vp) return
|
||||
// UI 缩放(zoom)下 pointer 坐标是视觉物理像素;画布坐标是布局像素 → 统一除以 uiZoom 对齐
|
||||
@@ -6953,7 +7089,7 @@ const tbCenterSeed = (type, refs) => {
|
||||
}
|
||||
const onUp = (e) => {
|
||||
const target = e && e.target
|
||||
if (target && target.closest && target.closest('.iwb-fullmask')) return
|
||||
if (!(refs.box || refs.pan || refs.drag) && target && target.closest && target.closest('.iwb-fullmask')) return // 手势中(框选/平移/拖节点)不拦松手:否则指针落在面板上松手,选择框残留、拖动卡死
|
||||
// 节点体纯点击(未超过拖动态阈值):只保持选择,不进入 drag 处理(不污染撤销历史)
|
||||
if (refs.bodyDown && !refs.bodyDown.active) { refs.bodyDown = null; }
|
||||
// 节点组纯点击(未超过阈值):同上,只保留「框内单击=选中整组」的选择结果
|
||||
@@ -7136,6 +7272,8 @@ const tbCenterSeed = (type, refs) => {
|
||||
wsId: activeWsId, activeWsId: () => activeWsIdRef.current || activeWsId, nodes: () => refs.nodes,
|
||||
uid, findSpot, nodeW: (ty) => nodeWidth({ type: ty }), nodeH: (ty) => nodeTypeH(ty),
|
||||
pushHistory, commitCanvas, setSel, setNotice, importImage: wImportImage,
|
||||
readNativeImage: (typeof window !== 'undefined' && window.IWBDesktop && window.IWBDesktop.clipboardReadImage) ? () => window.IWBDesktop.clipboardReadImage() : null,
|
||||
closeLibrary: () => { setDrawerOpen(false) },
|
||||
})
|
||||
const onKey = (e) => {
|
||||
const t = e.target, C = window.IWBClipboardCopy, hasTxt = C && C.hasTextSelection
|
||||
@@ -7228,11 +7366,14 @@ const tbCenterSeed = (type, refs) => {
|
||||
const onPaste = (e) => {
|
||||
const t = e.target, editable = !!(t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable))
|
||||
refs.pasteProbe = 0 // 收到真实 paste → 取消「系统剪贴板为空」的提示
|
||||
refs.pasteStamp = (refs.pasteStamp || 0) + 1
|
||||
const mod = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null
|
||||
if (mod) mod.handle(e, pasteCtx(), editable)
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
window.addEventListener('keyup', onKeyUp)
|
||||
const pasteModEarly = (typeof window !== 'undefined' && window.IWBClipboardPaste) || null
|
||||
if (pasteModEarly && pasteModEarly.bindHotkeyFallback) pasteModEarly.bindHotkeyFallback(pasteCtx)
|
||||
window.addEventListener('paste', onPaste)
|
||||
window.addEventListener('blur', onBlur)
|
||||
return () => {
|
||||
@@ -8126,8 +8267,10 @@ const tbCenterSeed = (type, refs) => {
|
||||
}
|
||||
if (e.button !== 0) return
|
||||
// 工具栏 / 侧栏 / 面板 / 小地图上的交互不触发画布空白行为(否则点击面板按钮会关掉面板)
|
||||
// 真模态(设置/备份/确认/右键遮罩)才整体拦画布;库面板 .iwb-fullmask 是可拖可连的浮窗,画布露在它外面仍要能框选(面板内起手由下面 target 判定兜住)
|
||||
if (typeof document !== 'undefined' && document.querySelector && document.querySelector('.iwb-modal-mask, .iwb-ctxmask')) return
|
||||
const t0 = e.target
|
||||
if (t0 && t0.closest && (t0.closest('.iwb-toolbar') || t0.closest('.iwb-lib') || t0.closest('.iwb-lib-embedded') || t0.closest('.iwb-drawer') || t0.closest('.iwb-history') || t0.closest('.iwb-history-embedded') || t0.closest('.iwb-rightrail') || t0.closest('.iwb-fullmask') || t0.closest('.iwb-fullpanel') || t0.closest('.iwb-minimap') || t0.closest('.iwb-wsrail') || t0.closest('.iwb-statusbar') || t0.closest('.iwb-hint-bottom'))) return
|
||||
if (t0 && t0.closest && (t0.closest('.iwb-toolbar') || t0.closest('.iwb-lib') || t0.closest('.iwb-lib-embedded') || t0.closest('.iwb-drawer') || t0.closest('.iwb-history') || t0.closest('.iwb-history-embedded') || t0.closest('.iwb-rightrail') || t0.closest('.iwb-fullmask') || t0.closest('.iwb-fullpanel') || t0.closest('.iwb-minimap') || t0.closest('.iwb-wsrail') || t0.closest('.iwb-statusbar') || t0.closest('.iwb-hint-bottom') || t0.closest('.iwb-modal-mask') || t0.closest('.iwb-modal') || t0.closest('.iwb-cpick-pop'))) return
|
||||
// 平移画布:按住空格(临时)或选中抓手工具(持续);默认 = 框选节点
|
||||
if (refs.spaceDown || tool === 'pan') {
|
||||
refs.pan = { sx: e.clientX / uiZoom(), sy: e.clientY / uiZoom(), vx: viewport.x, vy: viewport.y }
|
||||
@@ -8292,8 +8435,12 @@ const tbCenterSeed = (type, refs) => {
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', title: '下载选中的图片到本地', onClick: downloadHistorySelected }, '下载'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', title: '清除选择', onClick: () => setHistSel([]) }, '清除'),
|
||||
) : null,
|
||||
el('select', { className: 'iwb-input', style: { maxWidth: 130 }, value: histRange, onChange: (e) => setHistRange(e.target.value), title: '时间范围' },
|
||||
[['', '全部时间'], ['today', '今天'], ['7d', '近 7 天'], ['30d', '近 30 天']].map(([v, l]) => el('option', { key: v, value: v }, l)),
|
||||
// 紧凑版(v3.25.19):只显示档位值,前缀「插入」放进 title 与标签里,省横向空间
|
||||
el('select', { className: 'iwb-input iwb-select-compact', value: insertK, onChange: (e) => setInsertKPersist(e.target.value), title: '插入画布时的图片尺寸:原图最清晰但最大;2K/1K/0.5K 会等比压到对应边长' },
|
||||
[['orig', '原图'], ['2k', '2K'], ['1k', '1K'], ['0.5k', '0.5K']].map(([v, l]) => el('option', { key: v, value: v }, l)),
|
||||
),
|
||||
el('select', { className: 'iwb-input iwb-select-compact', value: histRange, onChange: (e) => setHistRange(e.target.value), title: '按时间筛选图库' },
|
||||
[['', '全部'], ['today', '今天'], ['7d', '7 天'], ['30d', '30 天']].map(([v, l]) => el('option', { key: v, value: v }, l)),
|
||||
),
|
||||
),
|
||||
el('div', { className: 'iwb-history-grid', ref: (el0) => { histGridRef.el = el0 } },
|
||||
@@ -8302,7 +8449,7 @@ const tbCenterSeed = (type, refs) => {
|
||||
((f.data || f.url)) ? el('img', { src: wDisplayThumbOf((f.data || f.url) || ''), loading: 'lazy', style: { aspectRatio: (f.w && f.h) ? String(f.w) + ' / ' + String(f.h) : '1 / 1' }, title: f.name + '(单击单选 · Shift+单击多选 · 双击放大 · 拖到画布=参考图节点)', draggable: true, onDragStart: (e) => { try { e.dataTransfer.setData('application/x-iwb-localref', (f.data || f.url) || f.name); e.dataTransfer.setData('application/x-iwb-gallery-orig', f.name); e.dataTransfer.effectAllowed = 'copy' } catch (err) { /* ignore */ } }, onClick: (e) => { if (e && e.shiftKey) setHistSel((prev) => prev.includes(f.name) ? prev.filter((n) => n !== f.name) : [...prev, f.name]); else setHistSel([f.name]) }, onDoubleClick: () => { setPreview({ list: outputs.map((x) => ({ __gallery: true, name: x.name, origIdb: x.origIdb, idb: x.idb, url: x.url, thumb: x.data || null })), idx: Math.max(0, outputs.findIndex((x) => x.name === f.name)) }) } }) : el('div', { className: 'iwb-history-missing' }, '图片已丢失'),
|
||||
null,
|
||||
el('div', { className: 'iwb-history-actions' },
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', title: '插入到画布(参考图节点)', onClick: async (e) => { e.stopPropagation(); const src0 = await wbCmd().refSrcOf(await wResolveOutputSrc(f), (msg) => showToast(msg, 'err')); const spot = findSpot('ref'); const id = uid('n'); // 2026-10-20(审计 N1):插入时**立即引用化**,不要把整张图 base64 塞进画布。
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', title: '插入到画布(参考图节点)', onClick: async (e) => { e.stopPropagation(); let src0 = await wbCmd().refSrcOf(await wResolveOutputSrc(f), (msg) => showToast(msg, 'err')); if (typeof src0 === 'string' && src0.indexOf('data:') === 0) src0 = await shrinkForInsert(src0); const spot = findSpot('ref'); const id = uid('n'); // 2026-10-20(审计 N1):插入时**立即引用化**,不要把整张图 base64 塞进画布。
|
||||
// 原症状:插入时 data.url = 完整 base64(4K 约 10MB)⇒ 画布内存里多一份整图;
|
||||
// 刷新后又被 wSanitizeWs 换成 {__blob} 引用(用户看到的「状态变了」),
|
||||
// 且刷新时还要把 base64 再转回 Blob(内存数倍占用、过一会儿才回落)。
|
||||
@@ -8392,26 +8539,24 @@ const tbCenterSeed = (type, refs) => {
|
||||
// 自定义右键菜单(屏蔽浏览器默认菜单)
|
||||
connMenu && ConnectMenu ? el(ConnectMenu, { direction: connMenu.direction, options: connMenu.options, sx: connMenu.sx, sy: connMenu.sy, renderIcon: (t) => I(nodeTypeIcon(t) || 'star'), onPick: (type) => { const pm = connMenu; setConnMenu(null); ConnectMenuMod.pick({ direction: pm.direction, type, wx: pm.wx, wy: pm.wy, fromId: pm.fromId, toId: pm.toId, batchSrcId: pm.batchSrcId, defaults: DEFAULTS, uid, createNode: (t, sp, d, u) => CanvasNodeFactory.createNode(t, sp, d, u), nodes: refs.nodes, edges: refs.edges, pushHistory, commitCanvas, setSel, saveNow }) }, onClose: () => setConnMenu(null) }) : null,
|
||||
ctxMenu ? el('div', { className: 'iwb-ctxmask', onPointerDown: (e) => { if (e.target === e.currentTarget) setCtxMenu(null) }, onContextMenu: (e) => { e.preventDefault(); setCtxMenu(null) } },
|
||||
el('div', { className: 'iwb-ctxmenu', ref: ctxMenuRef, style: { left: Math.min(ctxMenu.x, (window.innerWidth || 1200) - 210), top: Math.min(ctxMenu.y, (window.innerHeight || 800) - 320) }, onPointerDown: (e) => e.stopPropagation(), onContextMenu: (e) => e.stopPropagation() },
|
||||
el('div', { className: 'iwb-ctxmenu iwb-ctx-noclip', ref: ctxMenuRef, style: { left: Math.min(ctxMenu.x, (window.innerWidth || 1200) - 210), top: Math.min(ctxMenu.y, (window.innerHeight || 800) - 320) }, onPointerDown: (e) => e.stopPropagation(), onContextMenu: (e) => e.stopPropagation() },
|
||||
el('div', { className: 'iwb-ctx-title' }, '添加节点'),
|
||||
[['prompt', '提示词', I('file-text')], ['ref', '图片', I('ref')], ['textout', '文本', I('textout')], ['combine', '组合', I('server-plus')], ['batch', '连接', I('batch')], ['relay', '中继', I('circle-dot')], ['gen', '配置', I('gen')], ...(wPrivateToolsOn ? [['llm', '润色', I('llm')], ['layer', '分层', I('layer')]] : []), ['out', '输出', I('presentation')]].map(([t, label, ic]) => el('button', { key: t, className: 'iwb-ctx-item', onClick: () => { addNode(t, Math.round(ctxMenu.wx - NODE_W / 2), Math.round(ctxMenu.wy - 20)); setCtxMenu(null) } }, ic, el('span', { className: 'iwb-btn-text' }, label))),
|
||||
...pluginNodeVariants.map((v) => el('button', { key: 'plugin-node-' + v.id, className: 'iwb-ctx-item', onClick: () => { addPluginNode(v.id, Math.round(ctxMenu.wx - NODE_W / 2), Math.round(ctxMenu.wy - 20)); setCtxMenu(null) } }, I('run'), el('span', { className: 'iwb-btn-text' }, '插件:' + String(v.title || v.id)))),
|
||||
// 插件节点单独成组(2026-11-19 用户要求):与内置节点之间加分割线 + 组标题,
|
||||
// 不再挤在「输出」后面让用户以为也是内置类型。插件停用/未装时整组(含分隔线)不渲染。
|
||||
...(pluginNodeVariants.length ? [el('div', { key: 'plug-sep', className: 'iwb-ctx-sep' }, null), el('div', { key: 'plug-title', className: 'iwb-ctx-title' }, '插件节点'), ...pluginNodeVariants.map((v) => el('button', { key: 'plugin-node-' + v.id, className: 'iwb-ctx-item', onClick: () => { addPluginNode(v.id, Math.round(ctxMenu.wx - NODE_W / 2), Math.round(ctxMenu.wy - 20)); setCtxMenu(null) } }, I('run'), el('span', { className: 'iwb-btn-text' }, String(v.title || v.id))))] : []),
|
||||
el('div', { className: 'iwb-ctx-sep' }, null),
|
||||
el('div', { className: 'iwb-ctx-title' }, '选中操作'),
|
||||
el('button', { className: 'iwb-ctx-item', disabled: !sel.length, onClick: () => { duplicateNodes(sel); setCtxMenu(null) } }, I('copy'), el('span', { className: 'iwb-btn-text' }, '复制选中(⌘D)')),
|
||||
el('button', { className: 'iwb-ctx-item', disabled: !sel.length, onClick: () => { exportSelectedGroup(); setCtxMenu(null) } }, I('upload'), el('span', { className: 'iwb-btn-text' }, '导出选中节点组')),
|
||||
el('button', { className: 'iwb-ctx-item', disabled: !(sel.length === 1 && refs.nodes.some((n) => n.id === sel[0] && n.type === 'prompt' && (n.data.text || '').trim())), onClick: () => { addPromptToLibrary(sel[0]); setCtxMenu(null) } }, I('star'), el('span', { className: 'iwb-btn-text' }, '添加到提示词库')),
|
||||
el('button', { className: 'iwb-ctx-item', disabled: !groups.some((x) => x.memberIds.length && x.memberIds.every((id) => sel.includes(id))), onClick: () => { const gg = groups.find((x) => x.memberIds.length && x.memberIds.every((id) => sel.includes(id))); if (gg) saveGroupSnapshot(gg); setCtxMenu(null) } }, I('star'), el('span', { className: 'iwb-btn-text' }, '收藏节点组')),
|
||||
el('button', { className: 'iwb-ctx-item', disabled: !sel.length, onClick: () => { const ttlD = sel.map((id) => refs.nodes.find((n) => n.id === id)).filter((n) => n && n.data && n.data.title && String(n.data.title).trim()).map((n) => n.data.title)[0]; setCtxMenu(null); td.open({ title: '收藏选中节点为节点组', value: ttlD || ('节点组 ' + (savedGroups.length + 1)), onSubmit: (nm) => saveSelectionAsGroup(sel, nm) }) } }, I('star'), el('span', { className: 'iwb-btn-text' }, '收藏选中节点')),
|
||||
el('button', { className: 'iwb-ctx-item iwb-ctx-danger', disabled: !sel.length, onClick: () => { deleteNodes(sel); setCtxMenu(null) } }, I('x'), el('span', { className: 'iwb-btn-text' }, '删除选中(Delete)')),
|
||||
// v3.24.67:这两个按钮原来各调一次 readClipboardGraph() → 打开一次菜单 = 4 次 getItem + 4 次 JSON.parse。
|
||||
// 收成一次求值(菜单打开时才读,render 期间不读)。
|
||||
...(() => { const canPaste = !!readClipboardGraph(); return [
|
||||
el('button', { className: 'iwb-ctx-item', disabled: !canPaste, onClick: () => { pasteCopiedNodes(); setCtxMenu(null) } }, I('paste'), el('span', { className: 'iwb-btn-text' }, '粘贴节点组')),
|
||||
el('button', { className: 'iwb-ctx-item', disabled: !canPaste, onClick: () => { clearClipboard(); setCtxMenu(null) } }, I('x'), el('span', { className: 'iwb-btn-text' }, '清空剪贴板')),
|
||||
] })(),
|
||||
ctxMenu.targetId && refs.nodes.find((n) => n.id === ctxMenu.targetId) ? el('div', { className: 'iwb-ctx-sep' }, null) : null,
|
||||
ctxMenu.targetId && refs.nodes.find((n) => n.id === ctxMenu.targetId) ? el('div', { className: 'iwb-ctx-title' }, '该节点') : null,
|
||||
// 两组收进二级菜单(2026-11-19 用户要求:一级 18 项太长)。入口是普通 button:
|
||||
// hover / 键盘 Tab / 点击获得焦点都会用 :focus-within 展开,条目与原来完全一致。
|
||||
(() => { const canPaste = !!readClipboardGraph(); return el('div', { className: 'iwb-ctx-subwrap' }, el('button', { className: 'iwb-ctx-item' }, I('copy'), el('span', { className: 'iwb-btn-text' }, sel.length ? '选中操作' : '画布操作'), el('i', { className: 'iwb-ctx-arrow' }, '▸')),
|
||||
el('div', { className: 'iwb-ctxmenu iwb-ctx-sub' },
|
||||
sel.length ? el('button', { className: 'iwb-ctx-item', onClick: () => { duplicateNodes(sel); setCtxMenu(null) } }, I('copy'), el('span', { className: 'iwb-btn-text' }, '复制选中(⌘D)')) : null, sel.length ? el('button', { className: 'iwb-ctx-item', onClick: () => { exportSelectedGroup(); setCtxMenu(null) } }, I('upload'), el('span', { className: 'iwb-btn-text' }, '导出选中节点组')) : null,
|
||||
(sel.length === 1 && refs.nodes.some((n) => n.id === sel[0] && n.type === 'prompt' && (n.data.text || '').trim())) ? el('button', { className: 'iwb-ctx-item', onClick: () => { addPromptToLibrary(sel[0]); setCtxMenu(null) } }, I('star'), el('span', { className: 'iwb-btn-text' }, '添加到提示词库')) : null,
|
||||
(sel.length && groups.some((x) => x.memberIds.length && x.memberIds.every((id) => sel.includes(id)))) ? el('button', { className: 'iwb-ctx-item', onClick: () => { const gg = groups.find((x) => x.memberIds.length && x.memberIds.every((id) => sel.includes(id))); if (gg) saveGroupSnapshot(gg); setCtxMenu(null) } }, I('star'), el('span', { className: 'iwb-btn-text' }, '收藏节点组')) : null, sel.length ? el('button', { className: 'iwb-ctx-item', onClick: () => { const ttlD = sel.map((id) => refs.nodes.find((n) => n.id === id)).filter((n) => n && n.data && n.data.title && String(n.data.title).trim()).map((n) => n.data.title)[0]; setCtxMenu(null); td.open({ title: '收藏选中节点为节点组', value: ttlD || ('节点组 ' + (savedGroups.length + 1)), onSubmit: (nm) => saveSelectionAsGroup(sel, nm) }) } }, I('star'), el('span', { className: 'iwb-btn-text' }, '收藏选中节点')) : null,
|
||||
sel.length ? el('button', { className: 'iwb-ctx-item iwb-ctx-danger', onClick: () => { deleteNodes(sel); setCtxMenu(null) } }, I('x'), el('span', { className: 'iwb-btn-text' }, '删除选中(Delete)')) : null,
|
||||
el('div', { className: 'iwb-ctx-sep' }, null),
|
||||
el('button', { className: 'iwb-ctx-item', disabled: !canPaste, onClick: () => { pasteCopiedNodes(); setCtxMenu(null) } }, I('paste'), el('span', { className: 'iwb-btn-text' }, '粘贴节点组')), el('button', { className: 'iwb-ctx-item', disabled: !canPaste, onClick: () => { clearClipboard(); setCtxMenu(null) } }, I('x'), el('span', { className: 'iwb-btn-text' }, '清空剪贴板')),
|
||||
)) })(),
|
||||
(() => {
|
||||
const tgt = ctxMenu.targetId ? refs.nodes.find((n) => n.id === ctxMenu.targetId) : null
|
||||
if (!tgt) return null
|
||||
@@ -8420,7 +8565,8 @@ const tbCenterSeed = (type, refs) => {
|
||||
if (tgt.type === 'llm') items.push(el('button', { key: 'pol', className: 'iwb-ctx-item', onClick: () => { runLLM(tgt.id); setCtxMenu(null) } }, I('llm'), el('span', { className: 'iwb-btn-text' }, '▶ 润色')))
|
||||
if (tgt.type === 'prompt' && (tgt.data.text || '').trim()) items.push(el('button', { key: 'fav', className: 'iwb-ctx-item', onClick: () => { addPromptToLibrary(tgt.id); setCtxMenu(null) } }, I('star'), el('span', { className: 'iwb-btn-text' }, '添加该提示词')))
|
||||
items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) => { const rc = e && e.currentTarget ? e.currentTarget.getBoundingClientRect() : null; setCtxMenu(null); if (UiGenCfgModule && UiGenCfgModule.openNodeBgPalette) UiGenCfgModule.openNodeBgPalette({ current: (tgt.data && tgt.data.bg) || '', anchorRect: rc, onPreview: (bg) => previewNodeBg([tgt.id], bg), onPreviewEnd: endNodeBgPreview, onPick: (bg) => updateNode(tgt.id, { bg }) }) } }, I('palette'), el('span', { className: 'iwb-btn-text' }, '背景色')), el('button', { key: 'ren', className: 'iwb-ctx-item', onClick: () => { setCtxMenu(null); wRenameNodeDialog(tgt, td, updateNode) } }, I('edit'), el('span', { className: 'iwb-btn-text' }, '重命名节点')), el('button', { key: 'del', className: 'iwb-ctx-item iwb-ctx-danger', onClick: () => { deleteNodes([tgt.id]); setCtxMenu(null) } }, I('x'), el('span', { className: 'iwb-btn-text' }, '删除该节点')))
|
||||
return items
|
||||
// 子菜单默认向上展开(底对齐入口):两组入口都在一级菜单下半区,向下会顶出视口
|
||||
return el('div', { className: 'iwb-ctx-subwrap' }, el('button', { className: 'iwb-ctx-item' }, I('edit'), el('span', { className: 'iwb-btn-text' }, '该节点'), el('i', { className: 'iwb-ctx-arrow' }, '▸')), el('div', { className: 'iwb-ctxmenu iwb-ctx-sub' }, items))
|
||||
})(),
|
||||
el('div', { className: 'iwb-ctx-sep' }, null),
|
||||
),
|
||||
@@ -8458,156 +8604,40 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
|
||||
// 插件自我注册。同源脚本本就被 CSP script-src 'self' 允许 ⇒ 不放宽 CSP、不重编译主包。
|
||||
// 按需下载:启动只下载「已启用」的远程插件;未启用的记为 idle、不下载,等用户在插件管理里勾选时再加载。
|
||||
// 单条远程插件的下载+激活(启动批量加载与按需加载共用):注入脚本(SRI 强制校验)→ 自我注册 → 持久化开关已开则激活。
|
||||
async function wLoadPluginEntry(record) {
|
||||
record.status = 'loading'
|
||||
const integrity = record.integrity
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script')
|
||||
script.src = '/plugins/' + record.file
|
||||
script.async = false
|
||||
if (integrity) { script.integrity = integrity; script.crossOrigin = 'anonymous' }
|
||||
script.onload = () => resolve()
|
||||
script.onerror = () => reject(new Error(integrity ? '脚本完整性校验失败(integrity 不符或加载失败)' : '脚本加载失败'))
|
||||
document.head.appendChild(script)
|
||||
})
|
||||
const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id)
|
||||
record.status = registered ? 'loaded' : 'not-registered'
|
||||
if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true)
|
||||
return record.status === 'loaded'
|
||||
} catch (err) {
|
||||
record.status = 'error'
|
||||
record.error = String((err && err.message) || err)
|
||||
return false
|
||||
}
|
||||
// 加载实现已抽到 src/runtime-plugin-loader.js(app.js 只做装配)
|
||||
function wPluginLoader () {
|
||||
return (typeof window !== 'undefined') ? window.IWBRuntimePluginLoader : null
|
||||
}
|
||||
// 外部插件(P1):代码在 <资料目录>/plugins/ 下,不经 HTTP。
|
||||
// 读文本 → 用 WebCrypto 校验清单里的 sha256 → 通过后才用 blob URL 注入(CSP 已放行 blob:)。
|
||||
function wPluginSource() {
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
return (F && F.plugins && typeof F.plugins.read === 'function') ? F.plugins : null
|
||||
function wPluginSource () {
|
||||
const L = wPluginLoader()
|
||||
return (L && typeof L.source === 'function') ? L.source() : null
|
||||
}
|
||||
async function wVerifyPluginCode(code, integrity) {
|
||||
if (!integrity) return false
|
||||
const expect = String(integrity).replace(/^sha256-/, '')
|
||||
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(code))
|
||||
let bin = ''
|
||||
const u8 = new Uint8Array(buf)
|
||||
for (let i = 0; i < u8.length; i++) bin += String.fromCharCode(u8[i])
|
||||
return btoa(bin) === expect
|
||||
// 市场实现已抽到 src/runtime-plugin-market.js
|
||||
function wMarketMod () {
|
||||
return (typeof window !== 'undefined') ? window.IWBRuntimePluginMarket : null
|
||||
}
|
||||
async function wLoadExternalPluginEntry(record) {
|
||||
record.status = 'loading'
|
||||
const src = wPluginSource()
|
||||
if (!src) { record.status = 'error'; record.error = '外部插件不可用'; return false }
|
||||
try {
|
||||
const code = await src.read(record.file)
|
||||
if (record.integrity) {
|
||||
const okHash = await wVerifyPluginCode(code, record.integrity)
|
||||
if (!okHash) throw new Error('完整性校验失败(外部插件)')
|
||||
}
|
||||
const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }))
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script')
|
||||
script.src = url
|
||||
script.async = false
|
||||
script.onload = () => resolve()
|
||||
script.onerror = () => reject(new Error('外部插件脚本执行失败'))
|
||||
document.head.appendChild(script)
|
||||
})
|
||||
} finally { setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000) }
|
||||
const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id)
|
||||
record.status = registered ? 'loaded' : 'not-registered'
|
||||
if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true)
|
||||
return record.status === 'loaded'
|
||||
} catch (err) {
|
||||
record.status = 'error'
|
||||
record.error = String((err && err.message) || err)
|
||||
return false
|
||||
}
|
||||
async function wMarketList () { const M = wMarketMod(); return M ? M.list() : [] }
|
||||
async function wMarketInstalled () { const M = wMarketMod(); return M ? M.installed() : [] }
|
||||
async function wMarketInstall (id) { const M = wMarketMod(); return M ? M.install(id) : { ok: false, error: '市场模块未就绪' } }
|
||||
async function wMarketUninstall (id) { const M = wMarketMod(); return M ? M.uninstall(id) : { ok: false, error: '市场模块未就绪' } }
|
||||
async function wVerifyPluginCode (code, integrity) {
|
||||
const L = wPluginLoader()
|
||||
return (L && typeof L.verifyCode === 'function') ? L.verifyCode(code, integrity) : false
|
||||
}
|
||||
|
||||
// ---- 插件市场(P2):静态索引 market.maqiart.eu.org/index.json → 下载 → sha256 校验 → 写入 plugins/ ----
|
||||
const W_MARKET_URL = 'https://market.maqiart.eu.org/index.json'
|
||||
// 桌面端优先用 Tauri 的原生 HTTP(Rust 侧):WKWebView 在代理/fake-IP 环境下直连会 Load failed
|
||||
function wMarketFetch(url) {
|
||||
const T = (typeof window !== 'undefined' && window.__TAURI__ && window.__TAURI__.http) ? window.__TAURI__.http : null
|
||||
if (T && typeof T.fetch === 'function') return T.fetch(url)
|
||||
return fetch(url, { cache: 'no-store' })
|
||||
async function wLoadPluginEntry (record) {
|
||||
const L = wPluginLoader()
|
||||
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
|
||||
return L.loadBuiltin(record)
|
||||
}
|
||||
async function wMarketList() {
|
||||
const resp = await wMarketFetch(W_MARKET_URL)
|
||||
if (!resp.ok) throw new Error('市场不可达:HTTP ' + resp.status)
|
||||
const j = await resp.json()
|
||||
return Array.isArray(j && j.plugins) ? j.plugins : []
|
||||
async function wLoadExternalPluginEntry (record) {
|
||||
const L = wPluginLoader()
|
||||
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
|
||||
return L.loadExternal(record)
|
||||
}
|
||||
async function wMarketInstalled() {
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
if (!F || !F.plugins) return []
|
||||
return await F.plugins.manifest()
|
||||
}
|
||||
async function wMarketInstall(id) {
|
||||
try {
|
||||
const list = await wMarketList()
|
||||
const item = list.find((p) => p && p.id === id)
|
||||
if (!item) return { ok: false, error: '市场里没有这个插件' }
|
||||
const base = W_MARKET_URL.replace(/index\.json$/, '')
|
||||
const resp = await wMarketFetch(base + item.file)
|
||||
if (!resp.ok) throw new Error('下载失败:HTTP ' + resp.status)
|
||||
const text = await resp.text()
|
||||
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
|
||||
const hex = Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, '0')).join('')
|
||||
if (item.sha256 && hex !== item.sha256) return { ok: false, error: '校验失败(sha256 不符)' }
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
if (!F || !F.plugins) return { ok: false, error: '外部插件目录不可用' }
|
||||
const file = String(item.file).split('/').pop()
|
||||
await F.plugins.write(file, text)
|
||||
const cur = await F.plugins.manifest()
|
||||
const next = cur.filter((p) => p && p.id !== id).concat([{ id: id, file: file, version: item.version, integrity: item.integrity }])
|
||||
await F.plugins.write('index.json', JSON.stringify(next, null, 2) + '\n')
|
||||
return { ok: true, restart: true, file: file }
|
||||
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
|
||||
}
|
||||
async function wMarketUninstall(id) {
|
||||
try {
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
if (!F || !F.plugins) return { ok: false, error: '外部插件目录不可用' }
|
||||
const cur = await F.plugins.manifest()
|
||||
const hit = cur.find((p) => p && p.id === id)
|
||||
const next = cur.filter((p) => p && p.id !== id)
|
||||
await F.plugins.write('index.json', JSON.stringify(next, null, 2) + '\n')
|
||||
if (hit && hit.file) await F.plugins.remove(hit.file)
|
||||
return { ok: true, restart: true }
|
||||
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
|
||||
}
|
||||
|
||||
// 开发者模式插件(plugins/local/<id>/plugin.js):未签名,仅在设置里打开开关时加载
|
||||
async function wLoadLocalPluginEntry(record) {
|
||||
record.status = 'loading'
|
||||
try {
|
||||
const code = String(record.code || '')
|
||||
if (!code) throw new Error('插件源码为空')
|
||||
const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }))
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script')
|
||||
script.src = url
|
||||
script.async = false
|
||||
script.onload = () => resolve()
|
||||
script.onerror = () => reject(new Error('本地插件脚本执行失败'))
|
||||
document.head.appendChild(script)
|
||||
})
|
||||
} finally { setTimeout(() => { try { URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000) }
|
||||
const registered = PluginHost && typeof PluginHost.list === 'function' && PluginHost.list().some((p) => p.id === record.id)
|
||||
record.status = registered ? 'loaded' : 'not-registered'
|
||||
if (registered && typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(record.id)) PluginHost.setEnabled(record.id, true)
|
||||
return record.status === 'loaded'
|
||||
} catch (err) {
|
||||
record.status = 'error'
|
||||
record.error = String((err && err.message) || err)
|
||||
return false
|
||||
}
|
||||
async function wLoadLocalPluginEntry (record) {
|
||||
const L = wPluginLoader()
|
||||
if (!L) { record.status = 'error'; record.error = '插件加载器未就绪'; return false }
|
||||
return L.loadLocal(record)
|
||||
}
|
||||
|
||||
// 按需加载(插件管理里勾选 idle 行):下载脚本 → 注册 → 显式启用;失败时返回错误供 UI 回滚勾选并提示。
|
||||
@@ -8621,6 +8651,15 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
|
||||
const r = PluginHost && typeof PluginHost.setEnabled === 'function' ? PluginHost.setEnabled(id, true) : null
|
||||
return r && r.ok ? { ok: true } : { ok: false, error: (r && r.error) || '启用失败' }
|
||||
}
|
||||
// 后台预热市场索引:设置页打开时直接命中缓存(网络慢也不影响首屏)
|
||||
function wWarmMarketCache() {
|
||||
try {
|
||||
setTimeout(function () {
|
||||
try { const p = wMarketList(); if (p && typeof p.catch === 'function') p.catch(function () { /* 离线也正常 */ }) } catch (e) { /* ignore */ }
|
||||
}, 2500)
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
async function wLoadRuntimePlugins() {
|
||||
if (typeof fetch !== 'function' || typeof document === 'undefined') return
|
||||
// 内置清单(随包)先读;外部清单(<资料目录>/plugins/)只覆盖同 id 的条目 —— 合并而非替换
|
||||
@@ -8650,6 +8689,14 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
|
||||
}
|
||||
} catch (e) { /* 开发者模式读取失败不影响启动 */ }
|
||||
for (const e of ext) { const id = String((e && e.id) || ''); if (id) byId.set(id, Object.assign({}, e, { source: 'external' })) }
|
||||
// 关键:加载前先快照「用户关掉过哪些插件」,加载过程绝不能覆盖这个状态
|
||||
let persistedState = {}
|
||||
try {
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
if (F && typeof F.ready === 'function') { try { await F.ready({ wizard: false }) } catch (e) { /* 已就绪 */ } }
|
||||
const v = lsGet('iwb_plugins', {})
|
||||
persistedState = (v && typeof v === 'object') ? v : {}
|
||||
} catch (e) { persistedState = {} }
|
||||
const manifest = Array.from(byId.values())
|
||||
if (!manifest.length) return
|
||||
const list = Array.isArray(manifest) ? manifest : (manifest && Array.isArray(manifest.plugins) ? manifest.plugins : [])
|
||||
@@ -8671,10 +8718,28 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
|
||||
// 只下载已启用的;未启用记 idle(不注入脚本),插件管理里勾选时经 wEnsurePluginLoaded 按需下载
|
||||
// 收进 pending 而非逐个 await:wLoadPluginEntry 在首个 await 前已 append ⇒ 并发抓取;async=false 保证执行顺序不变(冷启动 3 RTT → 1)
|
||||
// 本地开发插件默认启用(没有持久化状态,不应被当作已关闭的插件)
|
||||
if (PluginHost && typeof PluginHost.isEnabled === 'function' && (isLocalEntry || PluginHost.isEnabled(id))) pending.push(isLocalEntry ? wLoadLocalPluginEntry(record) : (isExt ? wLoadExternalPluginEntry(record) : wLoadPluginEntry(record)))
|
||||
// 一律加载脚本(注册 ≠ 启用):脚本注册后才能被开关随时启停;
|
||||
// 之前按 enabled 预筛,导致状态里残留 false 的插件永远进不了注册表,开关也打不开。
|
||||
if (PluginHost) pending.push(isLocalEntry ? wLoadLocalPluginEntry(record) : (isExt ? wLoadExternalPluginEntry(record) : wLoadPluginEntry(record)))
|
||||
else record.status = 'idle'
|
||||
}
|
||||
await Promise.all(pending)
|
||||
// 脚本都注册了:把持久化里明确关掉的插件停用(其余保持启用)
|
||||
try {
|
||||
const st = persistedState || {}
|
||||
for (const r of (wRuntimePlugins || [])) {
|
||||
if (!r || r.status !== 'loaded') continue
|
||||
const rec = st[r.id]
|
||||
if (!rec) continue
|
||||
const want = rec.enabled !== false
|
||||
if (!PluginHost || typeof PluginHost.setEnabled !== 'function') continue
|
||||
// 注意:插件是在 init() 之后才注册的,init 的"激活已启用项"覆盖不到它们。
|
||||
// 所以这里对 want=true 一律再 setEnabled(true)(activate 幂等:已激活会返回 already),
|
||||
// 否则会出现"开关显示已启用、实际没跑工厂函数"的假启用状态。
|
||||
if (want) PluginHost.setEnabled(r.id, true)
|
||||
else if (typeof PluginHost.isEnabled === 'function' && PluginHost.isEnabled(r.id)) PluginHost.setEnabled(r.id, false)
|
||||
}
|
||||
} catch (e) { /* 状态应用失败不影响加载 */ }
|
||||
try { lsSet('iwb_plugin_load_status', JSON.stringify(wRuntimePlugins.map((r) => ({ id: r.id, status: r.status, source: r.source, error: r.error || '' })))) } catch (e2) { /* probe */ }
|
||||
try { if (PluginHost && typeof PluginHost.emit === 'function') PluginHost.emit('runtime-plugins-loaded') } catch (e) { /* 通知失败不影响启动 */ }
|
||||
}
|
||||
@@ -8718,7 +8783,7 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
|
||||
: { in: true, out: true }
|
||||
const height = Number.isFinite(variant.height) ? variant.height : 200
|
||||
const color = (typeof variant.color === 'string' && variant.color) ? variant.color : '#969696'
|
||||
const entry = { id: String(variant.id), title: String(variant.title), defaults: variant.defaults || {}, run: typeof variant.run === 'function' ? variant.run : null, pluginId: ctx.id }
|
||||
const entry = { id: String(variant.id), title: String(variant.title), defaults: variant.defaults || {}, run: typeof variant.run === 'function' ? variant.run : null, pluginId: ctx.id, w: Number.isFinite(variant.width) ? variant.width : undefined }
|
||||
wPluginNodeVariants.push(entry)
|
||||
owned.push(entry)
|
||||
wPluginVariantMeta.set(entry.id, { id: entry.id, title: entry.title, defaults: entry.defaults, pluginId: ctx.id, ports: ports, height: height })
|
||||
@@ -8861,6 +8926,7 @@ items.push(el('button', { key: 'bgc', className: 'iwb-ctx-item', onClick: (e) =>
|
||||
}
|
||||
} catch (e) { /* 预注册失败不影响启动 */ }
|
||||
wLoadRuntimePlugins()
|
||||
wWarmMarketCache()
|
||||
}
|
||||
// 桌面端关闭图库定时清理(设置里已去掉该项):0 = 不限,避免老图被静默删掉
|
||||
try {
|
||||
|
||||
@@ -1,82 +1,66 @@
|
||||
# 桌面版在线更新:方案与落地清单(2026-11-17)
|
||||
# 在线更新(Tauri Updater)
|
||||
|
||||
> 现状:设置 → 通用 已有「版本与更新」区块(版本号 + 「检查更新」按钮)。
|
||||
> 按钮会检测 `window.__TAURI__.updater`;插件装上并配好更新源后自动生效,现在点它只会提示"尚未启用"。
|
||||
> 目标:用户装过一次之后,以后新版本在应用内点「检查更新」即可升级,不用再手动下载 dmg。
|
||||
|
||||
## 一、三种方案
|
||||
## 一、已经配好的东西
|
||||
|
||||
| 方案 | 用户体验 | 需要什么 | 适合 |
|
||||
|---|---|---|---|
|
||||
| **A. Tauri 官方 updater** | 应用内检查→下载→自动替换→重启 | 更新源(HTTPS 静态) + 一对签名密钥 + 发布流程 | 要发给别人 |
|
||||
| B. 手动下载 | 去网盘/Release 下新包替换 | 一个能放包的地方 | 自用、低频 |
|
||||
| C. 只提示(自研检查) | 提示"有新版本"+下载链接,不自动装 | 一个 version.json | 轻量折中 |
|
||||
| 组件 | 位置 | 说明 |
|
||||
|---|---|---|
|
||||
| 更新插件 | `src-tauri/Cargo.toml` → `tauri-plugin-updater` | Rust 侧用 `UpdaterExt` |
|
||||
| 更新源 | `src-tauri/tauri.conf.json` → `plugins.updater.endpoints` | `https://download.maqiart.eu.org/updates/latest.json` |
|
||||
| 签名公钥 | 同上 `plugins.updater.pubkey` | 私钥在 `~/.config/iwb-updater.key`(**务必备份**) |
|
||||
| 产物开关 | `bundle.createUpdaterArtifacts: true` | 构建 app 时额外产出 `.app.tar.gz` + `.sig` |
|
||||
| Rust 命令 | `check_update` / `install_update` | 前端通过 `__TAURI__.core.invoke` 调用 |
|
||||
| 前端入口 | 设置 → 通用 → 版本与更新 | 「检查更新」→「立即更新」→ 自动重启 |
|
||||
|
||||
**建议**:现在自用 → 先做 **C**(零密钥、能及时知道);要发给别人再升 A。
|
||||
## 二、发新版本(一条命令)
|
||||
|
||||
## 二、A 方案要素
|
||||
|
||||
### 1. 依赖
|
||||
```bash
|
||||
# Cargo.toml: tauri-plugin-updater = "2"
|
||||
npm i @tauri-apps/plugin-updater
|
||||
./scripts/publish-update.sh 3.25.3 # 改版本 + 双架构签名构建 + 上传 + 生成 latest.json
|
||||
```
|
||||
lib.rs: `.plugin(tauri_plugin_updater::Builder::new().build())`;capabilities 加 `"updater:default"`
|
||||
|
||||
### 2. 签名密钥(一次生成,永久保管)
|
||||
```bash
|
||||
npx tauri signer generate -w ~/.tauri/image-workbench.key
|
||||
```
|
||||
私钥绝不进仓库;公钥写进 `plugins.updater.pubkey`。
|
||||
**丢了私钥 = 老用户永远收不到更新。**
|
||||
脚本会做四件事:
|
||||
|
||||
1. `npx tauri build --bundles app,dmg`(arm64,带签名)
|
||||
2. `npx tauri build --target x86_64-apple-darwin --bundles app,dmg`(Intel,带签名)
|
||||
3. 上传 `*.app.tar.gz` / `.sig` / `.dmg` 到 NAS `updates/darwin-{aarch64,x86_64}/`
|
||||
4. 生成并上传 `updates/latest.json`(两个平台各自带 signature + url)
|
||||
|
||||
## 三、latest.json 格式(脚本自动生成)
|
||||
|
||||
### 3. 配置
|
||||
```json
|
||||
{
|
||||
"plugins": { "updater": {
|
||||
"pubkey": "<公钥>",
|
||||
"endpoints": ["https://<域名>/image-workbench/latest.json"]
|
||||
} },
|
||||
"bundle": { "createUpdaterArtifacts": true }
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 清单 latest.json
|
||||
```json
|
||||
{
|
||||
"version": "3.25.0",
|
||||
"notes": "…",
|
||||
"pub_date": "2026-11-17T10:00:00Z",
|
||||
"version": "3.25.2",
|
||||
"notes": "更新说明",
|
||||
"pub_date": "2026-11-17T09:43:08.117Z",
|
||||
"platforms": {
|
||||
"darwin-aarch64": { "signature": "<sig>", "url": "…app.tar.gz" },
|
||||
"windows-x86_64": { "signature": "<sig>", "url": "…nsis.zip" }
|
||||
"darwin-aarch64": { "signature": "<.sig 内容>", "url": "https://.../image-workbench_3.25.2_aarch64.app.tar.gz" },
|
||||
"darwin-x86_64": { "signature": "<.sig 内容>", "url": "https://.../image-workbench_3.25.2_x64.app.tar.gz" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. 构建带签名
|
||||
```bash
|
||||
TAURI_SIGNING_PRIVATE_KEY=... TAURI_SIGNING_PRIVATE_KEY_PASSWORD=... npm run app:build
|
||||
```
|
||||
产出 `*.app.tar.gz(.sig)` / `*.nsis.zip(.sig)`,与清单一起上传。
|
||||
⚠️ **两个平台都要有**:缺哪个平台,那个平台的用户就永远「已是最新」。
|
||||
|
||||
### 6. 托管选择
|
||||
| 位置 | 可行 | 注意 |
|
||||
|---|---|---|
|
||||
| GitHub Releases | ✅ | 私有库资产需匿名可读 |
|
||||
| Cloudflare R2/Pages | ✅ | 公开读 + HTTPS |
|
||||
| 飞牛 NAS / Gitea | ⚠️ | 必须公网 HTTPS 且免鉴权;私有库要 token ⇒ 不可用 |
|
||||
## 四、用户侧流程
|
||||
|
||||
## 三、现在就该定的事
|
||||
1. 版本号三处一致(tauri.conf / Cargo / package.json),每次发布递增
|
||||
2. macOS 要出 aarch64 + x64 两套;Windows 出 x64
|
||||
3. 私钥本机签还是 CI 签
|
||||
1. 装过任一 3.25.2+ 版本(这是第一个带更新器的版本)
|
||||
2. 设置 → 通用 → 版本与更新 → **检查更新**
|
||||
3. 有新版本 → 显示版本号与说明 → 点「立即更新」
|
||||
4. 自动下载、校验签名、替换、重启(数据目录不受影响)
|
||||
|
||||
## 四、C 方案(建议先做)
|
||||
1. 静态放 `version.json`:`{version, notes, url}`
|
||||
2. 「检查更新」改成 HTTP GET 比对版本,有新版给下载链接
|
||||
3. 零密钥、零签名、不影响安装包
|
||||
## 五、注意
|
||||
|
||||
## 五、现状
|
||||
- ✅ 通用页已显示版本号 + 检查更新按钮
|
||||
- ⬜ 待你定:A 还是 C
|
||||
- 提醒:未签名的 macOS 应用即使更新成功,首次打开仍有 Gatekeeper 提示;要消除需 Apple Developer ID($99/年),不影响自用。
|
||||
- **私钥丢了就不能再发更新**(签名对不上,所有旧客户端会拒绝安装)。备份 `~/.config/iwb-updater.key`
|
||||
- 公钥写在 `tauri.conf.json` 里进了仓库;私钥**绝不能**进仓库
|
||||
- macOS 未做 notarization:更新替换后仍是未签名 app,首次打开可能仍要右键→打开
|
||||
- Windows 将来出包时,在 latest.json 里加 `windows-x86_64`,并在 `bundle.targets` 里用 `nsis`(msi 不支持 updater)
|
||||
- Cloudflare 会缓存 404:新文件名第一次访问可能短暂 404,换文件名(内容变即哈希变)即可绕过
|
||||
|
||||
## 六、首次接入清单(已完成 2026-11-17)
|
||||
|
||||
- [x] 生成密钥对(`tauri signer generate`),公钥进 config,私钥留本机
|
||||
- [x] 加 `tauri-plugin-updater`,注册 `check_update` / `install_update`
|
||||
- [x] `createUpdaterArtifacts: true`
|
||||
- [x] 构建 3.25.2(arm + Intel)并发布 latest.json
|
||||
- [ ] 用户实测:装 3.25.2 后,3.25.3 发布时能一键更新(待验证)
|
||||
@@ -1,5 +1,11 @@
|
||||
# Windows 出包步骤(手把手)
|
||||
|
||||
> **本版要打的版本:3.25.1**(仓库里已经是这个号,直接构建,不要再改)
|
||||
>
|
||||
> 确认命令:node -e "console.log(require('./package.json').version)" → 应输出 3.25.1
|
||||
>
|
||||
> 产物名:image-workbench_3.25.1_x64-setup.exe / image-workbench_3.25.1_x64_en-US.msi
|
||||
|
||||
> 目标:在一台 Windows 机器上,从 Gitea 拉代码 → 打出安装包 → 自测 → 把产物回传到 NAS。
|
||||
|
||||
## 0. 前置检查
|
||||
|
||||
@@ -65,7 +65,23 @@
|
||||
1. 把插件文件放进插件源仓 `iwb-plugins-desktop/<id>/src/index.js`
|
||||
2. 在桌面仓跑同步:`node scripts/sync-plugins-from-repo.js`
|
||||
3. 生成市场:`node scripts/gen-market.js`
|
||||
4. 把 `market/` 上传到 NAS `/vol8/web/iwb-market/`
|
||||
4. 把 `market/` 上传到 NAS `/vol8/web/iwb-market/`(`market.maqiart.eu.org` 的站点根目录)
|
||||
|
||||
```bash
|
||||
# 只有索引和新增的插件文件会变;index.html 是手写页面,没改动就不用传
|
||||
ssh [email protected] "rm -f /vol8/web/iwb-market/index.json"
|
||||
scp market/index.json [email protected]:/vol8/web/iwb-market/index.json
|
||||
scp market/plugins/plugin-<id>.<sha12>.js [email protected]:/vol8/web/iwb-market/plugins/
|
||||
ssh [email protected] "chmod -R a+rX /vol8/web/iwb-market"
|
||||
|
||||
# 回读核验(不能只看命令退出码):索引条数 + 下载字节 sha256 与索引一致
|
||||
curl -s "https://market.maqiart.eu.org/index.json?t=$(date +%s)" | head -c 200
|
||||
```
|
||||
|
||||
> 上传前先 `ls /vol8/web/iwb-market/plugins` 对比本地:内容寻址命名下,同名文件必然同内容,只传新增的那个即可。
|
||||
> NAS 上的文件是只读位(`-r-xr-xr-x`),覆盖前要先 `rm`,否则 `scp` 会报 Permission denied。
|
||||
> **客户端二进制不含新命令时**(旧版本安装包):`open_browser_window` 等命令 invoke 会失败,
|
||||
> 插件降级 `window.open` —— 表现为"点了跳系统浏览器"。新增宿主命令必须重新打包客户端才生效。
|
||||
|
||||
## 6. 注意事项
|
||||
|
||||
|
||||
@@ -1,150 +1,108 @@
|
||||
# 任务:在 Windows 上为 image-workbench-desktop 产出安装包
|
||||
# 任务:在 Windows 上为 image-workbench-desktop 构建 v3.25.15 安装包
|
||||
|
||||
你是这台 Windows 机器上的打包执行者。目标是把已拉取到本地的 Tauri v2 项目**构建出 Windows x64 安装包**,自测通过后交付产物信息。**只做打包相关的事,不改业务代码。**
|
||||
你是这台 Windows 机器上的打包执行者。只做打包与自测,**不改业务代码**。
|
||||
|
||||
## 背景
|
||||
> ⚠️ v3.25.15 起的变化:项目已**彻底转桌面客户端**(`_headers` / `functions/` / `wrangler.toml` 已删除,`npm run deploy` 脚本已移除);
|
||||
> 更新清单**平台解耦**(Windows 用 `updates/latest-windows.json`,**由 Mac 侧用正式私钥生成,你不写**)。
|
||||
|
||||
- 项目:Image Workbench 桌面版(Tauri v2 + 原生 JS,前端产物在 dist/)
|
||||
- 仓库目录:本机已 clone(先自己确认路径,通常在当前目录或其子目录,含 `src-tauri/tauri.conf.json`)
|
||||
- 应用标识:`com.malongan.imageworkbench`
|
||||
- 数据目录(运行时):`%USERPROFILE%\Documents\ImageWorkbench`
|
||||
- 参考文档(仓库内):`docs/DESKTOP_WINDOWS.md`(本次任务的权威说明)
|
||||
## 硬性约束
|
||||
|
||||
## 硬性约束(违反即失败)
|
||||
1. 不改 `app.js` / `src/**` / `src-tauri/src/**` / `style.css` 的业务逻辑
|
||||
2. 不绕过 lint 门禁;报错就停下报告
|
||||
3. 不用 `npm install`,只用 `npm ci`;版本已定 **3.25.15**,不要改
|
||||
4. 不 commit / 不 push / 不打 tag / 不跑任何 `scripts/publish-*.sh`
|
||||
5. 不改 `src-tauri/tauri.windows.conf.json`(产物已锁 `nsis`,不要 msi)
|
||||
|
||||
1. **不修改** `app.js`、`src/**`、`src-tauri/src/**` 的任何业务逻辑
|
||||
2. **不绕过** 构建前的 lint 门禁(`beforeBuildCommand` 已含 `npm run lint`);lint 报错就停下来报告,不要改成跳过
|
||||
3. **不改** `package.json` 里的 scripts 语义;唯一允许改版本号的地方是 `node scripts/set-version.js <版本>`
|
||||
4. 不用 `npm install`,只用 `npm ci`
|
||||
5. 不安装/升级全局工具版本(Node/Rust)除非环境检查明确缺失,且每次安装前先向我确认
|
||||
6. 不把任何密钥、token、代理密码写进文件或提交
|
||||
7. 不提交 git commit、不推送、不打 tag(除非我明确要求)
|
||||
|
||||
## 第一步:环境检查(先做,结果先给我看)
|
||||
## 第零步:拉代码
|
||||
|
||||
```powershell
|
||||
node -v # 期望 v22.x
|
||||
npm -v
|
||||
rustc -V # 必须含 "msvc"
|
||||
rustup show active-toolchain
|
||||
git --version
|
||||
git fetch --all --tags; git checkout main; git pull --ff-only
|
||||
git rev-parse --short HEAD # 必须是 84c2c10 或其后代
|
||||
node -e "console.log(require('./package.json').version)" # 必须 3.25.15
|
||||
```
|
||||
|
||||
然后跑仓库自带检查脚本:
|
||||
## 第一步:环境检查
|
||||
|
||||
```powershell
|
||||
node -v; npm -v; rustc -V; rustup show active-toolchain
|
||||
powershell -ExecutionPolicy Bypass -File scripts\windows-check.ps1
|
||||
```
|
||||
|
||||
**判定**:
|
||||
- 全部 `[OK]` → 继续
|
||||
- 出现 `[缺失]` → 停止,把缺失项和提示原文发我(不要自行安装)
|
||||
全部 `[OK]` 才继续;出现 `[缺失]` 停止报告(不要自行安装)。
|
||||
|
||||
## 第二步:装依赖
|
||||
## 第二步:依赖
|
||||
|
||||
```powershell
|
||||
npm ci
|
||||
```
|
||||
|
||||
- 失败先看是不是网络/代理问题(npm 可临时设 `npm config set proxy http://127.0.0.1:10808`,装完删掉)
|
||||
- 成功后报告:`node_modules` 是否存在、耗时
|
||||
本次新增两个 Rust 插件依赖(single-instance / notification),首次构建会多拉一些 crate。
|
||||
|
||||
## 第三步:定版本号
|
||||
|
||||
先问我这次要发的版本号。若我未指定,用 **3.25.0**。
|
||||
## 第三步:构建(用一次性临时密钥签名)
|
||||
|
||||
```powershell
|
||||
node scripts/set-version.js 3.25.0
|
||||
npx tauri signer generate -w "$env:TEMP\iwb-tmp.key" --password ""
|
||||
$env:TAURI_SIGNING_PRIVATE_KEY = Get-Content "$env:TEMP\iwb-tmp.key" -Raw
|
||||
$env:TAURI_SIGNING_PRIVATE_KEY_PASSWORD = ""
|
||||
npx tauri build
|
||||
Remove-Item "$env:TEMP\iwb-tmp.key" -Force
|
||||
```
|
||||
|
||||
确认三处一致:
|
||||
> 产出的 `.sig` 是临时密钥签的,**我会在 Mac 上用正式私钥重签**,你附上即可。
|
||||
|
||||
## 第四步:确认产物
|
||||
|
||||
```powershell
|
||||
node -e "console.log(require('./package.json').version, require('./src-tauri/tauri.conf.json').version)"
|
||||
Select-String -Path src-tauri\Cargo.toml -Pattern '^version'
|
||||
Get-ChildItem src-tauri\target\release\bundle -Recurse -Include *.exe,*.sig | Select FullName,Length
|
||||
Get-FileHash "src-tauri\target\release\bundle\nsis\image-workbench_3.25.15_x64-setup.exe" -Algorithm SHA256
|
||||
Test-Path dist\plugins # 期望 False
|
||||
Test-Path _headers # 期望 False
|
||||
Test-Path functions # 期望 False
|
||||
```
|
||||
|
||||
## 第四步:构建
|
||||
## 第五步:自测清单(逐条报通过/失败)
|
||||
|
||||
```powershell
|
||||
npm run app:build
|
||||
```
|
||||
**基础**
|
||||
1. 安装并启动;数据目录 `%USERPROFILE%\Documents\ImageWorkbench` 生成 `data.json`/`canvases`/`library`/`images`
|
||||
2. **`images\` 下必须有 `canvas` 文件夹**(v3.25.12 之前只有 `thumbs`,这是丢图根因)
|
||||
3. 设置 → 通用:数据库目录正确;「打开」能弹资源管理器
|
||||
4. 关窗口进程仍在托盘;左键唤出;右键有菜单
|
||||
|
||||
预期内部顺序:`lint → build(含剥离内置插件)→ tauri build`。
|
||||
首次 5~15 分钟(Rust 依赖编译),之后 1~2 分钟。
|
||||
**图片持久化(历史 bug 复现点)**
|
||||
5. `Ctrl+V` 粘贴新图 → 出现图片节点
|
||||
6. **正常退出**(托盘右键退出,非强杀)→ 重开 → 图仍在、显示正常
|
||||
7. 从资源管理器拖图进画布 → 退出重开 → 图还在
|
||||
|
||||
**失败处理**:
|
||||
| 报错 | 处理 |
|
||||
|---|---|
|
||||
| `link.exe not found` / `LNK` | 缺 VS Build Tools C++ 工作负载 → 停止并报告 |
|
||||
| rustc 显示 `gnu` | `rustup default stable-x86_64-pc-windows-msvc`(可自行执行) |
|
||||
| `Windows SDK is not installed` | 停止并报告 |
|
||||
| npm/网络超时 | 检查代理,重试一次;仍失败则报告 |
|
||||
| lint 报错 | **停止**,把报错原文发我 |
|
||||
**桌面壳(本次新增)**
|
||||
8. 单实例:连续双击两次 → 只有一个窗口,第二次聚焦已有
|
||||
9. 外链:点「项目主页」→ 用系统浏览器打开,应用不变(不能被导航成网页)
|
||||
10. 跑一次生图,完成后弹系统通知
|
||||
|
||||
## 第五步:确认产物
|
||||
**插件与 CSP(本次修复)**
|
||||
11. 设置 → 插件:无内置插件;市场能列 7 个;装一个 → 重启后可用
|
||||
12. **鲜艺抠图**:启用后对图片节点执行抠图 → **不应出现 `Failed to fetch`**(3.25.11 回归,3.25.14 已修)
|
||||
13. 若本机有 `XianyiAiRmbg` 监听 `0.0.0.0:30092` → 抠图出透明底;没装则注明跳过
|
||||
|
||||
```powershell
|
||||
Get-ChildItem src-tauri\target\release\bundle -Recurse -Include *.exe,*.msi | Select-Object FullName,Length
|
||||
```
|
||||
**外观(本次新增)**
|
||||
14. 设置 → 外观:改画布底色(亮/暗)与主题色 → 立即生效,重启保持
|
||||
15. 亮暗切换时画布底色分别用两套值
|
||||
|
||||
必须找到(名字里带版本号与 `x64`):
|
||||
任何一条失败:记录现象 + 截图后停止报告,**不要改代码**。
|
||||
|
||||
- `src-tauri\target\release\bundle\nsis\image-workbench_<版本>_x64-setup.exe` ← **主交付物**
|
||||
- `src-tauri\target\release\bundle\msi\image-workbench_<版本>_x64_en-US.msi` ← 有则附带,没有不算失败(WiX 可能被网络挡)
|
||||
|
||||
并计算哈希:
|
||||
|
||||
```powershell
|
||||
Get-FileHash "src-tauri\target\release\bundle\nsis\image-workbench_<版本>_x64-setup.exe" -Algorithm SHA256
|
||||
```
|
||||
|
||||
另外确认**插件没有被塞进包**:
|
||||
|
||||
```powershell
|
||||
Test-Path dist\plugins # 期望 False
|
||||
```
|
||||
|
||||
## 第六步:安装自测(必须做,逐条报告 通过/失败)
|
||||
|
||||
1. 运行 `*-setup.exe` 安装并启动
|
||||
2. 数据目录生成 `%USERPROFILE%\Documents\ImageWorkbench`,内含 `data.json`、`canvases`、`library`、`images`
|
||||
3. 设置 → 通用:「数据库目录」显示上述路径;点「打开」能弹出资源管理器
|
||||
4. 关闭窗口后进程仍在托盘;左键托盘图标能唤出窗口;右键有菜单
|
||||
5. 设置 → 插件:**没有任何内置插件**;「插件市场」能列出 7 个插件;任选一个安装 → 提示重启 → 重启后该插件可用
|
||||
6. 新建画布、拖拽/缩放节点正常;导入一张本地图片正常
|
||||
7. 点一次「下载」:文件直接落到导出目录,**不弹另存为对话框**
|
||||
|
||||
任何一条失败:记录现象 + 截图,然后停下来报告,不要尝试改代码。
|
||||
|
||||
## 第七步:交付
|
||||
|
||||
把下面信息整理成表格发我:
|
||||
|
||||
- 版本号
|
||||
- 安装包绝对路径、文件大小(MB)、SHA256
|
||||
- MSI 是否存在
|
||||
- 环境检查结论(node/rust/VS/WebView2)
|
||||
- 六步自测逐条结果
|
||||
- 构建总耗时
|
||||
|
||||
产物先**留在本机**,等我确认后再决定上传方式(scp 到 NAS `/vol8/web/iwb-download/updates/windows-x86_64/`,或我另行安排)。
|
||||
|
||||
## 停止条件(遇到即停,不要自行发挥)
|
||||
|
||||
- 环境缺件(VS Build Tools / WebView2 / MSVC 工具链)
|
||||
- lint 或构建报错且一次重试无效
|
||||
- 自测有任意一条失败
|
||||
- 需要修改业务代码才能继续
|
||||
|
||||
停止时请给出:**卡在哪一步、完整报错、你已经尝试过什么**。
|
||||
|
||||
## 最终回复格式
|
||||
## 第六步:交付格式
|
||||
|
||||
```
|
||||
结论:成功 / 失败(卡在第 N 步)
|
||||
版本:
|
||||
版本:3.25.15 commit=<sha>
|
||||
安装包:<路径> <大小> SHA256=<hex>
|
||||
自测:1✅ 2✅ 3✅ 4✅ 5✅ 6✅ 7✅(失败的写 ❌ + 现象)
|
||||
备注:
|
||||
环境:node= rust= VS= WebView2=
|
||||
自测:1✅ … 15✅(失败写 ❌ + 现象)
|
||||
耗时:
|
||||
```
|
||||
|
||||
产物留在本机;**不要**上传 NAS、**不要**写 `latest-windows.json`(我在 Mac 侧做)。
|
||||
|
||||
## 停止条件
|
||||
|
||||
commit 不对 / 环境缺件 / 构建报错一次重试无效 / 自测有失败 / 需要改业务代码 —— 遇到即停,
|
||||
报告「卡在哪一步 + 完整报错 + 已尝试过什么」。
|
||||
@@ -278,7 +278,7 @@ npm run deploy # 部署到正式站
|
||||
IWB_VERIFY_STRICT=1 node scripts/verify-release.js
|
||||
```
|
||||
|
||||
> ⚠️ `npm run deploy` = `verify` + `wrangler pages deploy`,**不含 git push**。
|
||||
> ⚠️ 本项目已转桌面客户端:**不再用 `wrangler pages deploy`**,发版走 `./scripts/publish-update.sh`(macOS)/ `./scripts/publish-windows-update.sh`(Windows)。
|
||||
> 回滚时**不要**把旧代码 push 到 main(会污染历史);用 `checkout` 部署即可,
|
||||
> 部署完 `git checkout main` 回到主干。
|
||||
|
||||
@@ -408,7 +408,7 @@ git checkout refactor-step-3
|
||||
git checkout stable-v3.24.5 && npm ci && npm run verify:ci && npm run deploy
|
||||
|
||||
# 层 4:看部署历史,用 dashboard 或 API 切回旧 deployment
|
||||
npx wrangler pages deployment list --project-name image-workbench-web
|
||||
# 桌面端没有「线上部署列表」:版本清单在 NAS 的 /vol8/web/iwb-download/updates/
|
||||
```
|
||||
|
||||
### 7.2 铁律
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# 现状架构与性能事实基线(image-workbench-web)
|
||||
|
||||
> **本文档是什么**:现状**事实快照**,不是规范。用途:任何性能 / 内存 / 存储相关改动,先对齐这里的现实,避免把已经调好的东西改坏。
|
||||
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = 9d0e57c`(线上 `v3.25.0+9d0e57c` —— 线上实际运行提交是 docs 提交 `7df9dc4`,bump 提交为 `4be78c0`;2026-11-16 已发**测试站 + 正式站**,三地址一致 + `IWB_VERIFY_STRICT=1` 通过。v3.24.85 是「代码体检收口」(棘轮收回 Workbench 3090→2998 + 图库索引 4 条绕过锁的写路径收口到 `mutate` + 文档数字校准),`stable` / `stable-v3.24.85` / `stable-verified-2026-11-16` 均指向 `7df9dc4`。上一条 —— 2026-11-14 发**测试站 + 正式站** `https://test.image-workbench-web.pages.dev`:**v3.24.84 修「生图节点连了 3 条上游只出 1 个任务」**(任务 id 与去重基准改用新字段 `ownerNodeId`=本节点自己,不再用随继承冒泡的 `sourceNodeId` ⇒ 连几条线就几个任务;`relay` 仍归约到真实文本来源,同一来源多路径抵达只算一次)。上一条 v3.24.83:**修「插件节点冷启动退化成一段文本」**(插件节点体是异步注册的,`registerNodeType` 在 `render` 由无变有时自增 `NODE_TYPES_REV`,`NodeCard` 比它 ⇒ 注册那一刻重建一次;`canvas-normalize` 按命名规则把 `plugin:<id>:<variant>` 认作已知类型,不再降级成 `plugin` 并写回存档);配套插件 `style-source` 1.3.2 把节点体样式改为**脚本执行时注入**(此前只在面板 `mount()` 注入 ⇒ 从存档直接进画布时节点无样式、缩略图按原图铺满)。上一条 v3.24.82 同批:提示词/文本节点**显示上游继承文本**(自己 `data.text` 为空时把上游那段话显示在框里,改一个字即接管,另有「恢复跟随」清空回跟随;多路上游按 Y 轴取第一条)+ 修 `nodeRefsOf` 的 textout 分支只认 llm/batch/combine 上游导致「样式 → 文本 → 分层」丢参考图;再上一条 v3.24.81:① 插件节点可自定义节点体(`render(node, props, host)` 画真实 DOM,宿主不每帧重建 ⇒ 输入框不失焦);② 节点自带参考图(`data.refOn/refUrl` ⇒ 任务图里补伪参考图,坐标取节点自身 ⇒ 仍参与「图片按 X 轴排序」);③ 连线白名单按 `data.outKind === 'prompt'` 归一化,7 条规则一次放行,内置节点行为逐字不变。上一条 v3.24.80 = 离开页面的兜底保存不递增 rev(2026-11-14 07:20 补发 —— 首发 11-13 23:25 撞 Cloudflare Workers API 事故 `503 no healthy upstream`,期间正式站保持在 `v3.24.79+8598a57` 未动)。v3.24.83 的 bump 提交即 `0a27a42`(v3.24.82 为 `ef6cf42`、v3.24.81 为 `dba71e3`);主干 HEAD 会继续前进,见 [`RELEASES.md`](../RELEASES.md))| 历史分支 `refactor/architecture` / `feat/multi-canvas-tabs` / `refactor/state-store` 已于 2026-10-20 清理(内容均已并入 main,归档标签 `archive/*`),本文**计数类事实**已按 main HEAD 复算。
|
||||
> 日期 **2026-10-20**(**2026-11-16 复算 · v3.24.85**)| 基线(**最近一次 bump 版本的提交**,不是主干 HEAD)`main = e1120ec`(线上 `v3.25.30+e1120ec` —— 线上实际运行提交是 docs 提交 `7df9dc4`,bump 提交为 `4be78c0`;2026-11-16 已发**测试站 + 正式站**,三地址一致 + `IWB_VERIFY_STRICT=1` 通过。v3.24.85 是「代码体检收口」(棘轮收回 Workbench 3090→2998 + 图库索引 4 条绕过锁的写路径收口到 `mutate` + 文档数字校准),`stable` / `stable-v3.24.85` / `stable-verified-2026-11-16` 均指向 `7df9dc4`。上一条 —— 2026-11-14 发**测试站 + 正式站** `https://test.image-workbench-web.pages.dev`:**v3.24.84 修「生图节点连了 3 条上游只出 1 个任务」**(任务 id 与去重基准改用新字段 `ownerNodeId`=本节点自己,不再用随继承冒泡的 `sourceNodeId` ⇒ 连几条线就几个任务;`relay` 仍归约到真实文本来源,同一来源多路径抵达只算一次)。上一条 v3.24.83:**修「插件节点冷启动退化成一段文本」**(插件节点体是异步注册的,`registerNodeType` 在 `render` 由无变有时自增 `NODE_TYPES_REV`,`NodeCard` 比它 ⇒ 注册那一刻重建一次;`canvas-normalize` 按命名规则把 `plugin:<id>:<variant>` 认作已知类型,不再降级成 `plugin` 并写回存档);配套插件 `style-source` 1.3.2 把节点体样式改为**脚本执行时注入**(此前只在面板 `mount()` 注入 ⇒ 从存档直接进画布时节点无样式、缩略图按原图铺满)。上一条 v3.24.82 同批:提示词/文本节点**显示上游继承文本**(自己 `data.text` 为空时把上游那段话显示在框里,改一个字即接管,另有「恢复跟随」清空回跟随;多路上游按 Y 轴取第一条)+ 修 `nodeRefsOf` 的 textout 分支只认 llm/batch/combine 上游导致「样式 → 文本 → 分层」丢参考图;再上一条 v3.24.81:① 插件节点可自定义节点体(`render(node, props, host)` 画真实 DOM,宿主不每帧重建 ⇒ 输入框不失焦);② 节点自带参考图(`data.refOn/refUrl` ⇒ 任务图里补伪参考图,坐标取节点自身 ⇒ 仍参与「图片按 X 轴排序」);③ 连线白名单按 `data.outKind === 'prompt'` 归一化,7 条规则一次放行,内置节点行为逐字不变。上一条 v3.24.80 = 离开页面的兜底保存不递增 rev(2026-11-14 07:20 补发 —— 首发 11-13 23:25 撞 Cloudflare Workers API 事故 `503 no healthy upstream`,期间正式站保持在 `v3.24.79+8598a57` 未动)。v3.24.83 的 bump 提交即 `0a27a42`(v3.24.82 为 `ef6cf42`、v3.24.81 为 `dba71e3`);主干 HEAD 会继续前进,见 [`RELEASES.md`](../RELEASES.md))| 历史分支 `refactor/architecture` / `feat/multi-canvas-tabs` / `refactor/state-store` 已于 2026-10-20 清理(内容均已并入 main,归档标签 `archive/*`),本文**计数类事实**已按 main HEAD 复算。
|
||||
<!-- 2026-10-28 P1 拆分批 1:新增 src/generation-task-graph.js(5 个任务图纯函数自 app.js 迁出)
|
||||
⇒ 模块数 60→61、耦合面 51→52、sourceModules 60→61。耦合面只**新增** IWBWTaskGraph,无删除。
|
||||
2026-10-28 P1 拆分批 2:新增 src/storage-config-shape.js(9 个配置形状纯函数自 app.js 迁出)
|
||||
@@ -22,7 +22,7 @@
|
||||
- 图片**新写入主通道 = IndexedDB Blob `{__blob}` / key `imgblob_<hash>_<len>`** (A) `app.js:2143`;`{__cache}`(Cache Storage)为兜底;\`ref_\`(`app.js` 内定义的 `IDB_REF_PREFIX = 'ref_'`)为 legacy 形态 (A)。
|
||||
- 大图判定:`isBigDataUrl` = `data:` 且 `length > 3000` (A) `app.js:2018`;**画布保存保留阈值** `< 16384` 才原样保留 (A) `app.js:2182`。**两处阈值并存,含义不同**。
|
||||
- 单测是**源码契约测试**:`tests/` 目录共 **493** 处源码文本钉点(`source.includes` / `source.indexOf` / `/re/.test(source)`),分布在 **20** 个文件(其中 `iwb-v32-web-test.js` 一个就占 **407**)→ **结构性重构会先打红测试**。**该数字已由 `tests/source-text-ratchet-test.js` 的「只减不增」棘轮守门**(2026-10-20 起守卫范围从 1 个文件扩到全目录:新增任何一处源码文本钉点都会打红)。**2026-11-12 复算**(`npm run audit:pins`,v3.24.76):二分 STRUCT **417** / NAME **76**;形态 **POS 403 / NEG 87 / COUNT 3**;难度 **易 62 / 中 316 / 难 115**。钉点减法第一批(v3.24.72)把 **537 → 505**:8 条探针钉点改为「门禁内 spec 是否真的读该计数器」、5 条改为运行时断言(生产态 `window` 上无探针)、10 条改为 DOM 断言(质量档位禁用 / 传输页无三模式按钮 / 模型项 title)、4 条改为运行时对象断言(健康检查两域、策略对象冻结)、其余 9 条有同文件 DOM 等价断言或仅剩 NEG。第二批(v3.24.76)把 **505 → 493**:94-5~7 三条「多标签释放语义」(10 处正则)换成 `tests/iwb-tabs-release.spec.js` 的 3 条真 e2e,剩 1 条「消费方契约」(断言该 spec 在门禁内且 spec 源码真的读两个探针);另 2 条 `wPurgeIntent.add` 钉点改为读 `src/workspace-purge.js`。**这一批一换就查出 3 个真缺陷**(objectURL 从未释放 / 彻底删除留孤儿标签 · session / 刷新后误回收打开标签的图)—— 见 CHANGELOG v3.24.76。
|
||||
- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **81** 个模块 / 14,607 行,`sourceModules` 81 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
|
||||
- `app.js` = 单 IIFE **8,508 行**(**双层预算**:绝对上限 8,700 / 占总源码 ≤ 40%,现 **36.8%**,2026-11-12 起;此前为单一上限 8,509、零余量);`Workbench()` = **2,998 行**(上限 **3,030**,余量 32;2026-11-16 把生成取消族 `cancelRunsFor`/`cancelRun`/`cancelTaskJobs` 与工作区列表写回族 `persistWs`/`duplicateWs` 搬进 `src/runtime-workbench-logic.js`(`createCancelActions` / `createWorkspaceListActions`),并删掉全仓零调用的 `runAll`,3090 → 2,998);大量逻辑已抽到 `src/*.js`(现 **89** 个模块 / 14,607 行,`sourceModules` 89 项;v3.24.68 新增 `clipboard-graph.js`,v3.24.74 新增 `image-admit.js`,v3.24.75 新增 `image-dedupe.js`,v3.24.76 新增 `workspace-purge.js`,v3.24.79 新增 `generation-provider-ping.js`,v3.24.80 删除无调用的 `createWBFlushViewport` 17 行)。
|
||||
- 门禁:`npm run verify` = `verify:ci`(`build` → `node --check app.js` → `node --check dist/app.js` → `check-dist.js` → `lint`(ESLint 正确性规则,`src/` + `app.js`,P4-16a)→ `test:unit` → `test` → `test:facts`)+ `test:e2e` (A) `package.json`。
|
||||
|
||||
## 2. 门禁与环境现状
|
||||
@@ -31,7 +31,7 @@
|
||||
|---|---|---|
|
||||
| 单测基线 | **658 通过 / 0 新增失败 / 2 已知环境差异**(2026-11-12 v3.24.76 实测;660 −2 = 94-5~7 三条钉点换成一条消费方契约) | (A) `npm test` 实测(`tests/iwb-v32-web-test.js`) |
|
||||
| e2e | spec 文件 **59** 个(**55** 个进门禁 + 4 个 dev 探针 `_perf-baseline` / `_plugin-host-probe` / `_probe-drag` / `_probe-tab-switch`) | (A) `tests/` 计数 + `scripts/list-e2e-specs.js` |
|
||||
| e2e 用例数 | **200 条**(2026-11-16 实测:55 个进门禁 spec 内 `test()` 总数)(历史:115 → v3.24.18 **143** → v3.24.19 **147** → v3.24.21 **151** → F2 改名 1 条 **152** → 抓手工具 2 条 **154** → v3.24.44 输出顺序 2 条 **166** → v3.24.47 同步去重 `iwb-sync-dedupe` 1 条 **167** → v3.24.67 **179** → v3.24.68 **183** → v3.24.69 **184** → v3.24.70 **186** → v3.24.74 **187**(新增「拖入 PDF 给提示 + MIME 空 PNG 仍能导入」)→ v3.24.75 **188**(新增「同一张图连粘两次只建一个节点」)→ v3.24.76 **191**(新增 `iwb-tabs-release` 3 条:回首页不降级 / 关标签先保存再关 / 彻底删除连带关标签)→ v3.24.77 **194**(新增 `iwb-lod` 3 条:fit 大画布必须全 LOD / 放大后必须恢复 / 常规画布不 LOD)→ v3.24.78 **196**(`iwb-lod` 3 → 5 条:新增「lite 档必须画出代表图/首行文字」与「缩到 15% 以下才退成 plain」)→ v3.24.82 **197**(新增 `iwb-inherit-text` 1 条:提示词/文本节点显示上游继承文本、改字接管、恢复跟随)→ v3.24.83 **198**(新增 `iwb-plugin-node-coldstart` 1 条:插件脚本晚到 1.2s,存档里的插件节点必须自动切回插件节点体,且类型不被降级成 `plugin`)→ v3.24.79 **196 不变**(测速修复的守门落在 jsdom 单测 `provider-ping-test.js`,e2e 无新增)→ v3.24.85 **200**(新增 `iwb-multi-tab` 2 条:A 页 flush 落盘后 B 页必须靠 rev 轮询看到改动;B 页持锁期间 A 页图库归档必须挂起);早期 99 → 115 的逐版链条见 `docs/history/coverage-baseline-2026-10-27.md`) | (A) `tests/*.spec.js` 计数 + `scripts/list-e2e-specs.js` |
|
||||
| e2e 用例数 | **200 条**(2026-11-16 实测:55 个进门禁 spec 内 `test()` 总数;v3.25.15 删除网页版部署面后为 **53** 个进门禁 —— `iwb-csp-gate` / `iwb-functions-headers` 随 `_headers`、`functions/` 一起移除)(历史:115 → v3.24.18 **143** → v3.24.19 **147** → v3.24.21 **151** → F2 改名 1 条 **152** → 抓手工具 2 条 **154** → v3.24.44 输出顺序 2 条 **166** → v3.24.47 同步去重 `iwb-sync-dedupe` 1 条 **167** → v3.24.67 **179** → v3.24.68 **183** → v3.24.69 **184** → v3.24.70 **186** → v3.24.74 **187**(新增「拖入 PDF 给提示 + MIME 空 PNG 仍能导入」)→ v3.24.75 **188**(新增「同一张图连粘两次只建一个节点」)→ v3.24.76 **191**(新增 `iwb-tabs-release` 3 条:回首页不降级 / 关标签先保存再关 / 彻底删除连带关标签)→ v3.24.77 **194**(新增 `iwb-lod` 3 条:fit 大画布必须全 LOD / 放大后必须恢复 / 常规画布不 LOD)→ v3.24.78 **196**(`iwb-lod` 3 → 5 条:新增「lite 档必须画出代表图/首行文字」与「缩到 15% 以下才退成 plain」)→ v3.24.82 **197**(新增 `iwb-inherit-text` 1 条:提示词/文本节点显示上游继承文本、改字接管、恢复跟随)→ v3.24.83 **198**(新增 `iwb-plugin-node-coldstart` 1 条:插件脚本晚到 1.2s,存档里的插件节点必须自动切回插件节点体,且类型不被降级成 `plugin`)→ v3.24.79 **196 不变**(测速修复的守门落在 jsdom 单测 `provider-ping-test.js`,e2e 无新增)→ v3.24.85 **200**(新增 `iwb-multi-tab` 2 条:A 页 flush 落盘后 B 页必须靠 rev 轮询看到改动;B 页持锁期间 A 页图库归档必须挂起);早期 99 → 115 的逐版链条见 `docs/history/coverage-baseline-2026-10-27.md`) | (A) `tests/*.spec.js` 计数 + `scripts/list-e2e-specs.js` |
|
||||
| CI | `.github/workflows/verify.yml`:**push(main) + PR(→main) + 手动** 触发,两个 job(`gate` = `verify:ci`;`e2e` = `test:e2e`),只验证不部署 | (A) |
|
||||
| 部署 | `npm run deploy` = `verify` + `wrangler pages deploy dist --branch main`;**内含全量 verify,不得绕过** | (A) `package.json:16` |
|
||||
| 部署环境 | 本机 wrangler 为 OAuth 登录 → **不能设 `CI=true`**(用 `unset CI` + `WRANGLER_SEND_METRICS=false`) | (A) 本轮发布实测 |
|
||||
@@ -167,7 +167,7 @@
|
||||
- 同一张图被 3 个节点引用、hydrate 成 3 个不同 objectURL 时,preview/display 缓存各自 miss → 重复解码(与 F2 相邻)。
|
||||
- **F10|`refs.genScheduler` 是桩** (A) → 未接线,暂无运行时影响(P3)。
|
||||
- **F11|已建但未接线的模块层(2026-10-17 接线审计;2026-10-18 复核更正)** (A)
|
||||
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**81 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
|
||||
- **判定法**:`global.X =` / `root.X =` 判「导出」;跨文件裸引用判「读」;排除自合并(`src/runtime-constants.js:9`)。`app.js` 是**唯一生产消费者**(无 HTML 入口;`sw.js` 不引用模块全局)。**89 个模块中 59 个导出**被 `app.js` 读取;其余为未接线 / 仅测试 / 零引用(见下)。
|
||||
- **仅被测试引用(9 模块 + 2 导出)**:`canvas-domain`、`generation-retry`、`generation-service`、`runtime-recovery-runner`、`runtime-state-bridge`、`runtime-store`、`storage-reconcile`、`storage-result`、`workspace-service`;导出 `IWBStorageHealthFactory`、`IWBPluginHostFactory`。(`storage-result` 是**存储层共享结果类型**,被 6 个存储模块读取,**非死代码**;`runtime-store` 为状态模型 epic 地基。)
|
||||
- **app.js 零引用(1 模块 + 3 导出)**:模块 `generation-controller`;导出 `IWBRuntimeMetricsFactory`、`IWBStorageRuntimeFactory`、`IWBUIComponents`。`canvas-relations` 已随 `06cf211` 删除(本文档早前把它列为"唯一可删者",实际已删)。零引用证据 = `grep -rn "<名字>" .`(排除 `node_modules|dist|vendor|test-results`)**只命中其自身赋值行**。
|
||||
- **半接线 / 未接线**:`IWBRuntimeStateBridge` **无 app.js 引用(仅测试)**;`IWBRuntimeRunContext` **已接线**(`runNode` 读取运行上下文);`IWBGenerationController` 是完整但**从未被调用**的工厂;`ModularWorkspaceStore`(`app.js` 内)是 `storage-workspace` 的**预留接线 seam**(当前无下游使用,保留);`window.IWBImageFolder` 自注册后读回(装载路径)。
|
||||
@@ -183,7 +183,7 @@
|
||||
| `storage-reconcile` | 存储对账(`createReconciler`/`check`) | 内联对账 | 存储层收口 |
|
||||
| `runtime-recovery-runner` | 执行恢复候选(`candidate`/`valid`/`run`) | 内联恢复 | 断点恢复 |
|
||||
| `canvas-domain` | 画布域模型(`commit`/`updateNode`/`deleteNodes`…) | `CanvasStore` 那一套 | Workbench 解耦(P2-9) |
|
||||
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**71** 项)与 `sourceModules` 顺序(**81** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
|
||||
- **耦合面已冻结**:`tests/architecture-boundary-guard-test.js`(进 `npm run test:unit` 末环)冻结 app.js↔src 耦合面(**74** 项)与 `sourceModules` 顺序(**89** 项);命名例外由第 5 组冻结,新增非 `IWB` 前缀导出即打红。
|
||||
|
||||
## 12. 易踩的坑
|
||||
|
||||
@@ -254,7 +254,7 @@
|
||||
|
||||
**信任模型(必须明示)**:形态 A 的插件是**可信代码**(与核心同权限、无沙箱);启停与设置是 UX 与可维护性手段,**不是安全边界**(同 §13.27 教训:前端开关一定可被绕过)。
|
||||
|
||||
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**71** 项)与 `sourceModules` 顺序(**81** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
|
||||
**守门与快照**:`tests/architecture-boundary-guard-test.js` 冻结「app.js ↔ src 耦合面」(**74** 项)与 `sourceModules` 顺序(**89** 项);新增模块、新增耦合、新增 dev 探针都**必须有意重生成对应快照**(`IWB_WRITE_BOUNDARY_SNAPSHOT=1`)。契约与行为的可执行验证在 `tests/plugin-host-test.js`(宿主单测)与 `tests/_plugin-host-probe.spec.js`(真实浏览器探针,`_` 前缀 + `iwb-dev-probe`,不进 34 门禁)。
|
||||
|
||||
**关键陷阱**:`normalizeNodes`(现位于 `src/canvas-normalize.js`)会**静默丢弃**不在 `NODE_H` 里的节点类型 ⇒ 新增节点类型必须先登记 `NODE_H`,否则节点一刷新就消失(§13.27 规则三的同一失败模式)。
|
||||
|
||||
@@ -270,6 +270,10 @@
|
||||
**CSP 最小放宽(2026-10-17,为本地服务插件)**:`_headers` 的 `connect-src` 由 `'self' https:` 扩为 `'self' https: http://127.0.0.1:30092 http://localhost:30092`。
|
||||
- **动机**:页面内插件(非浏览器扩展)受页面 CSP 约束;调用本机服务必须放行 loopback。**只放行这一个固定端口**,不放宽到任意 `http:`、不放开脚本域、不引入 `unsafe-eval`。
|
||||
- **边界**:插件若把服务地址改到别的 host/端口会被 CSP 拦(属预期)。页面因此可以向本机 30092 发请求 —— 这是**有意的安全边界调整**,与"插件是可信代码"的模型一致。
|
||||
- **桌面客户端 CSP 的唯一定义处是 `src-tauri/tauri.conf.json` 的 `app.security.csp`**(v3.25.14 补记)。
|
||||
本项目是桌面客户端,`_headers` 属于旧的网页部署、不参与桌面行为,**两者不做一致性约束**。
|
||||
v3.25.11 的「CSP 清理」误判 30092 为遗留端口删掉 ⇒ 桌面版鲜艺抠图插件 `Failed to fetch`。
|
||||
现由 `tests/desktop-csp-loopback-test.js` 钉住(只断言桌面 CSP 的运行时值,避免源码钉点棘轮)。
|
||||
|
||||
**鲜艺抠图插件(2026-10-17 起改为 A2 运行时插件,`dist` 不再内置)**:源码已迁出主仓到独立插件仓(`iwb-plugins`),经 Cloudflare Function `functions/plugins/[[path]].js` + KV(binding `PLUGINS`)**同源运行时加载**(同源 ⇒ CSP 零改动);主包**已不含** `src/plugin-xianyi-cutout.js`。功能:右键命令「抠图:选中节点」→ `POST {apiUrl}/rmbg?crop=`(`application/octet-stream` + 原始字节)→ 结果 PNG 写回为新的参考图节点(`<原名>_cutout.png`)。契约对齐 `iwb-plaus` v3.1.3 的 `background.js`(二进制进 / PNG 字节出;无 token、无 JSON),但**补齐了原版缺失的超时**(`AbortController` + 可配 `timeoutMs`)。设置项:`apiUrl` / `crop` / `timeoutMs`。尚未提供的能力面(若日后需要):插件只读「选中节点」与按 id 取节点图(`canvas` 目前只有 `getNodes` / `listNodeTypes`)。
|
||||
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
// Cloudflare Pages Function:**第一方**图片代理(同源 /api/img)。
|
||||
// 目的:豆包(火山 TOS)等图床**不返回 CORS 头**,浏览器无法 fetch ⇒ 下载、缩略图归档、
|
||||
// 本地原图备份全部拿不到字节。经本站代理转发后由本站给出 CORS 头,前端即可正常读取。
|
||||
// 用法:GET /api/img?url=<encodeURIComponent(https 图片地址)>
|
||||
//
|
||||
// 安全边界(H2 加固):
|
||||
// - 仅接受**同源**调用:若请求带 Origin 头,其 host 必须与本站一致。
|
||||
// - 仅 https、仅允许常见图片/对象存储域名(避免成为开放代理/SSRF),仅透传 image/* 响应。
|
||||
// - **手动跟随重定向**:每一跳都对目标 host 重新做白名单校验(原实现 redirect:'follow' 只校验初始
|
||||
// host,可被 302 逃逸到任意主机),并限制跳数。
|
||||
// - **响应大小上限**:先看 content-length,超限即拒;无 content-length 时按流裁剪(防超大响应耗尽配额)。
|
||||
// - 不再返回 Access-Control-Allow-Origin: *(同源调用本就不需要 CORS)。
|
||||
export function onRequest(context) {
|
||||
return handle(context.request)
|
||||
}
|
||||
|
||||
const ALLOW_HOSTS = [
|
||||
/(^|\.)volces\.com$/i, // 火山引擎 / TOS(豆包 Seedream 图床)
|
||||
/(^|\.)aliyuncs\.com$/i, // 阿里云 OSS(tuzi 文档示例图床)
|
||||
/(^|\.)myqcloud\.com$/i, // 腾讯云 COS
|
||||
/(^|\.)qiniucdn\.com$/i,
|
||||
/(^|\.)cloudfront\.net$/i,
|
||||
/(^|\.)googleusercontent\.com$/i,
|
||||
/(^|\.)openai\.org$/i,
|
||||
/(^|\.)oaistatic\.com$/i,
|
||||
/(^|\.)blob\.core\.windows\.net$/i,
|
||||
]
|
||||
const MAX_BYTES = 25 * 1024 * 1024 // 单张图片上限 25MB(生成图远小于此;防超大响应)
|
||||
const MAX_REDIRECTS = 3
|
||||
|
||||
// 安全头(2026-10-20 加,H1):Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
|
||||
// (https://developers.cloudflare.com/pages/configuration/headers/)⇒ 静态资源有 CSP/nosniff,
|
||||
// 而本函数(及 plugins 函数)原本**一个安全头都没有**。这不是可利用漏洞(每个响应都显式
|
||||
// 设了 Content-Type),但属于纵深防御缺口:将来若有端点返回用户影响的内容且漏设 Content-Type,
|
||||
// 浏览器会自行嗅探类型 ⇒ 可能演变成 XSS。故在**每个** Response 显式补齐 nosniff + Referrer-Policy。
|
||||
const SECURITY_HEADERS = {
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
}
|
||||
|
||||
function hdr() {
|
||||
return Object.assign({ 'Content-Type': 'text/plain; charset=utf-8' }, SECURITY_HEADERS)
|
||||
}
|
||||
function plain(msg, status) {
|
||||
return new Response(msg, { status, headers: hdr() })
|
||||
}
|
||||
function sameOrigin(request) {
|
||||
const origin = request.headers.get('Origin')
|
||||
if (!origin || origin === 'null') return true
|
||||
try { return new URL(origin).host === new URL(request.url).host } catch (e) { return false }
|
||||
}
|
||||
function hostAllowed(u) {
|
||||
return ALLOW_HOSTS.some((re) => re.test(u.hostname))
|
||||
}
|
||||
function capStream(stream, max) {
|
||||
let seen = 0
|
||||
return stream.pipeThrough(new TransformStream({
|
||||
transform(chunk, controller) {
|
||||
seen += chunk && chunk.byteLength ? chunk.byteLength : 0
|
||||
if (seen > max) { controller.error(new Error('response too large')); return }
|
||||
controller.enqueue(chunk)
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
async function handle(request) {
|
||||
if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: hdr() })
|
||||
if (request.method !== 'GET') return plain('仅支持 GET', 405)
|
||||
if (!sameOrigin(request)) return plain('仅允许同源调用', 403)
|
||||
let target
|
||||
try {
|
||||
const raw = String(new URL(request.url).searchParams.get('url') || '')
|
||||
target = new URL(raw)
|
||||
} catch (e) { return plain('缺少或非法的 url 参数', 400) }
|
||||
if (target.protocol !== 'https:') return plain('仅支持 https 图片地址', 400)
|
||||
if (!hostAllowed(target)) return plain('该图床未在允许列表中:' + target.hostname, 403)
|
||||
try {
|
||||
// 手动跟随重定向:每一跳都对 host 重新校验,逃逸即拒。
|
||||
let upstream = null
|
||||
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
||||
upstream = await fetch(target.toString(), { headers: { Accept: 'image/*' }, redirect: 'manual' })
|
||||
const status = upstream.status
|
||||
const isRedirect = status >= 300 && status < 400
|
||||
if (!isRedirect) break
|
||||
const location = upstream.headers.get('Location')
|
||||
if (!location) return plain('上游重定向缺少 Location', 502)
|
||||
if (hop === MAX_REDIRECTS) return plain('重定向次数过多', 508)
|
||||
let next
|
||||
try { next = new URL(location, target) } catch (e) { return plain('上游重定向地址非法', 502) }
|
||||
if (next.protocol !== 'https:') return plain('重定向目标非 https', 403)
|
||||
if (!hostAllowed(next)) return plain('重定向目标未在允许列表中:' + next.hostname, 403)
|
||||
target = next
|
||||
}
|
||||
if (!upstream || !upstream.ok) return plain('上游返回 ' + (upstream ? upstream.status : '0'), 502)
|
||||
const ct = String(upstream.headers.get('content-type') || '')
|
||||
if (ct && ct.toLowerCase().indexOf('image/') !== 0) return plain('上游不是图片(' + ct + ')', 415)
|
||||
const len = Number(upstream.headers.get('content-length'))
|
||||
if (Number.isFinite(len) && len > MAX_BYTES) return plain('图片过大(超过 ' + MAX_BYTES + ' 字节)', 413)
|
||||
const headers = new Headers()
|
||||
headers.set('Content-Type', ct || 'image/png')
|
||||
headers.set('Cache-Control', 'private, max-age=600')
|
||||
for (const [k, v] of Object.entries(SECURITY_HEADERS)) headers.set(k, v)
|
||||
const body = upstream.body && !(Number.isFinite(len) && len <= MAX_BYTES) ? capStream(upstream.body, MAX_BYTES) : upstream.body
|
||||
return new Response(body, { status: 200, headers })
|
||||
} catch (e) {
|
||||
return plain('代理失败:' + ((e && e.message) || 'unknown'), 502)
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
// /plugins/* → 从 KV(binding: PLUGINS)以**同源**方式提供插件文件。
|
||||
// 同源脚本本就被页面 CSP(script-src 'self')允许 ⇒ 无需放宽 CSP、无需 unsafe-eval、无需重新部署 app.js。
|
||||
// KV 键约定:plugins/index.json(清单)+ plugins/<file>(每个插件一个文件)。
|
||||
//
|
||||
// 缓存策略(按 basename 分流):
|
||||
// - plugin-<id>.<hash12>.js(内容寻址,发布脚本生成)→ public, max-age=31536000, immutable(字节永不变 ⇒ 可永久缓存)
|
||||
// - 其他 .js(历史遗留未哈希文件)→ no-cache + ETag(安全网:绝不许被永久缓存)
|
||||
// - .json(清单)→ no-cache + ETag;if-none-match 命中 → 304 空 body
|
||||
// - 其他扩展名 / 404 / 500 → no-store
|
||||
// ETag 为 (value, basename) 的确定性纯函数:FNV-1a 32bit(同步、廉价),hex 后加双引号。
|
||||
|
||||
const JS_CT = 'application/javascript; charset=utf-8'
|
||||
const JSON_CT = 'application/json; charset=utf-8'
|
||||
|
||||
// 安全头(2026-10-20 加,H1):Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
|
||||
// (https://developers.cloudflare.com/pages/configuration/headers/)⇒ 静态资源有 CSP/nosniff,
|
||||
// 而本函数原本**一个安全头都没有**。插件字节虽同源且有 SRI 校验,但缺 nosniff 意味着
|
||||
// 万一将来 KV 里的内容类型异常,浏览器可能自行嗅探 ⇒ 补齐纵深防御。
|
||||
const SECURITY_HEADERS = { 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' }
|
||||
|
||||
const ERROR_HEADERS = Object.assign({ 'content-type': JSON_CT, 'cache-control': 'no-store' }, SECURITY_HEADERS)
|
||||
const NO_STORE_HEADERS = Object.assign({ 'content-type': JS_CT, 'cache-control': 'no-store' }, SECURITY_HEADERS)
|
||||
|
||||
const IMMUTABLE_JS_RE = /^plugin-[a-z0-9-]+\.[0-9a-f]{12}\.js$/
|
||||
|
||||
// FNV-1a 32-bit(对 UTF-16 code unit 序列):同步、确定、够用于 ETag 指纹
|
||||
const fnv1a32 = (s) => {
|
||||
let h = 0x811c9dc5
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
h ^= s.charCodeAt(i)
|
||||
h = Math.imul(h, 0x01000193)
|
||||
}
|
||||
return (h >>> 0).toString(16).padStart(8, '0')
|
||||
}
|
||||
|
||||
const etagOf = (value, base) => '"' + fnv1a32(base + '\n' + value) + '"'
|
||||
|
||||
export async function onRequestGet(context) {
|
||||
const { params, env } = context
|
||||
const parts = Array.isArray(params.path) ? params.path : [params.path].filter(Boolean)
|
||||
const tail = parts.join('/') || 'index.json'
|
||||
const key = 'plugins/' + tail
|
||||
const base = tail.slice(tail.lastIndexOf('/') + 1)
|
||||
|
||||
if (!env || !env.PLUGINS) {
|
||||
return new Response(JSON.stringify({ error: 'PLUGINS KV 未绑定' }), { status: 500, headers: ERROR_HEADERS })
|
||||
}
|
||||
|
||||
const value = await env.PLUGINS.get(key)
|
||||
if (value === null) return new Response('not found', { status: 404, headers: Object.assign({ 'cache-control': 'no-store' }, SECURITY_HEADERS) })
|
||||
|
||||
// A) 内容寻址的插件 JS:内容变 ⇒ 文件名变 ⇒ 可 immutable 永久缓存
|
||||
if (IMMUTABLE_JS_RE.test(base)) {
|
||||
return new Response(value, {
|
||||
headers: Object.assign({ 'content-type': JS_CT, 'cache-control': 'public, max-age=31536000, immutable' }, SECURITY_HEADERS),
|
||||
})
|
||||
}
|
||||
|
||||
// B) 未哈希 .js 与 .json(清单):no-cache + ETag,每次回源校验,命中即 304
|
||||
if (base.endsWith('.js') || base.endsWith('.json')) {
|
||||
const etag = etagOf(value, base)
|
||||
const headers = Object.assign({
|
||||
'content-type': base.endsWith('.json') ? JSON_CT : JS_CT,
|
||||
'cache-control': 'no-cache',
|
||||
etag,
|
||||
}, SECURITY_HEADERS)
|
||||
const inm = context.request && context.request.headers && context.request.headers.get('if-none-match')
|
||||
if (inm === etag) return new Response(null, { status: 304, headers })
|
||||
return new Response(value, { headers })
|
||||
}
|
||||
|
||||
// 其他扩展名:保持 no-store
|
||||
return new Response(value, { headers: NO_STORE_HEADERS })
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "image-workbench-web",
|
||||
"private": true,
|
||||
"version": "3.25.0",
|
||||
"version": "3.25.30",
|
||||
"description": "Browser-based node canvas image workbench",
|
||||
"scripts": {
|
||||
"build": "node scripts/build.js && node scripts/copy-plugins.js",
|
||||
@@ -9,8 +9,8 @@
|
||||
"app:dev": "tauri dev",
|
||||
"app:build": "tauri build",
|
||||
"lint": "eslint src app.js",
|
||||
"test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js && node tests/iwb-v32-web-test.js",
|
||||
"test:unit": "node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/functions-api-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js",
|
||||
"test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js",
|
||||
"test:unit": "node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/ui-groups-sidebar-test.js && node tests/ui-lib-sidebar-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js",
|
||||
"test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js",
|
||||
"test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js",
|
||||
"plugins:gc": "node scripts/plugins-publish.mjs --gc",
|
||||
@@ -20,8 +20,6 @@
|
||||
"test:e2e:local": "node scripts/serve-test.js",
|
||||
"verify:ci": "npm run build && node --check app.js && node --check dist/app.js && node scripts/check-dist.js && npm run lint && npm run typecheck && npm run test:unit && npm test && npm run test:facts",
|
||||
"verify": "npm run verify:ci && npm run test:e2e",
|
||||
"deploy": "npm run verify && npx --yes wrangler@4 pages deploy dist --project-name image-workbench-web --branch main",
|
||||
"deploy:test": "npm run verify && npx --yes wrangler@4 pages deploy dist --project-name image-workbench-web --branch test",
|
||||
"verify:release": "node scripts/verify-release.js",
|
||||
"coverage:e2e": "node scripts/coverage-e2e.js",
|
||||
"sync:facts": "node scripts/sync-facts.js",
|
||||
|
||||
@@ -11,11 +11,17 @@
|
||||
"version": "1.0.0",
|
||||
"integrity": "sha256-Z3Y4k/qZyP4di89kBCb1u8V2q9NbzchMkQt7CPeZZPk="
|
||||
},
|
||||
{
|
||||
"id": "browser",
|
||||
"file": "plugin-browser.91399c13d011.js",
|
||||
"version": "1.5.0",
|
||||
"integrity": "sha256-kTmcE9ARins+w7Go2jzSAOXEau+fC4BnkgerazWWLVE="
|
||||
},
|
||||
{
|
||||
"id": "image-annotate",
|
||||
"file": "plugin-image-annotate.86ccc161901c.js",
|
||||
"version": "1.20.1",
|
||||
"integrity": "sha256-hszBYZAc1qcloGHrWhXG9Z3Zc/qq0emOnlMNPUar3Pc="
|
||||
"file": "plugin-image-annotate.7a865c7c353c.js",
|
||||
"version": "1.20.6",
|
||||
"integrity": "sha256-eoZcfDU8P7yqxVGorrWs0b9iTKJfEE25b85JPDCEsk8="
|
||||
},
|
||||
{
|
||||
"id": "image-vectorize",
|
||||
|
||||
@@ -2,36 +2,89 @@
|
||||
"batch-export": {
|
||||
"name": "批量出图",
|
||||
"desc": "资源中心勾选节点,串行批量生成并打包 ZIP 下载",
|
||||
"author": "official"
|
||||
"author": "official",
|
||||
"icon": "🗂️",
|
||||
"color": "#e8f0fe",
|
||||
"tags": [
|
||||
"出图",
|
||||
"批处理"
|
||||
]
|
||||
},
|
||||
"blank-canvas": {
|
||||
"name": "空白画布",
|
||||
"desc": "新建空白画布节点,用于分区分组",
|
||||
"author": "official"
|
||||
"author": "official",
|
||||
"icon": "⬜",
|
||||
"color": "#eef2f6",
|
||||
"tags": [
|
||||
"画布",
|
||||
"效率"
|
||||
]
|
||||
},
|
||||
"image-annotate": {
|
||||
"name": "标注 / 修图",
|
||||
"desc": "在画布内标注、涂抹、局部重绘",
|
||||
"author": "official"
|
||||
"author": "official",
|
||||
"icon": "🖌️",
|
||||
"color": "#fdeaea",
|
||||
"tags": [
|
||||
"修图",
|
||||
"标注"
|
||||
]
|
||||
},
|
||||
"image-vectorize": {
|
||||
"name": "位图转矢量",
|
||||
"desc": "把位图转成 SVG 矢量路径",
|
||||
"author": "official"
|
||||
"author": "official",
|
||||
"icon": "✒️",
|
||||
"color": "#eaf3ea",
|
||||
"tags": [
|
||||
"转换",
|
||||
"矢量"
|
||||
]
|
||||
},
|
||||
"style-source": {
|
||||
"name": "风格库",
|
||||
"desc": "风格提示词库与一键套用",
|
||||
"author": "official"
|
||||
"author": "official",
|
||||
"icon": "🎨",
|
||||
"color": "#fdf0e6",
|
||||
"tags": [
|
||||
"提示词",
|
||||
"风格"
|
||||
]
|
||||
},
|
||||
"white-bg-800": {
|
||||
"name": "白底图",
|
||||
"desc": "批量生成电商白底图(800px)",
|
||||
"author": "official"
|
||||
"author": "official",
|
||||
"icon": "🧾",
|
||||
"color": "#eef7fb",
|
||||
"tags": [
|
||||
"电商",
|
||||
"出图"
|
||||
]
|
||||
},
|
||||
"xianyi-cutout": {
|
||||
"name": "鲜艺抠图",
|
||||
"desc": "接入鲜艺抠图模型的一键去背景",
|
||||
"author": "official"
|
||||
"author": "official",
|
||||
"icon": "✂️",
|
||||
"color": "#f3eafd",
|
||||
"tags": [
|
||||
"抠图",
|
||||
"去背景"
|
||||
]
|
||||
},
|
||||
"browser": {
|
||||
"name": "应用内浏览器",
|
||||
"desc": "库面板内置真实浏览器:书签按分组管理、拖动排序;地址栏 ↗ 可把当前页放到画布节点",
|
||||
"author": "official",
|
||||
"icon": "🌐",
|
||||
"color": "#eaf1fb",
|
||||
"tags": [
|
||||
"浏览器",
|
||||
"效率"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
id: 'image-annotate',
|
||||
name: '标注 / 修图',
|
||||
version: '1.20.1',
|
||||
version: '1.20.6',
|
||||
apiVersion: 1,
|
||||
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
|
||||
settings: {
|
||||
@@ -3899,7 +3899,18 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
step: 1,
|
||||
def: () => 100,
|
||||
render: (canvas, v) => {
|
||||
if (v > 0) filterCanvas(canvas, "invert(" + v / 100 + ")");
|
||||
if (v <= 0) return;
|
||||
const k = v / 100;
|
||||
if (FILTER_SUPPORTED) {
|
||||
filterCanvas(canvas, "invert(" + k + ")");
|
||||
return;
|
||||
}
|
||||
const ok = mapPixels(canvas, (r, g, b) => [
|
||||
clamp255(r + (255 - 2 * r) * k),
|
||||
clamp255(g + (255 - 2 * g) * k),
|
||||
clamp255(b + (255 - 2 * b) * k)
|
||||
]);
|
||||
if (!ok) blendFallback(canvas, "invert", k);
|
||||
}
|
||||
},
|
||||
gray: {
|
||||
@@ -3912,7 +3923,17 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
step: 1,
|
||||
def: () => 100,
|
||||
render: (canvas, v) => {
|
||||
if (v > 0) filterCanvas(canvas, "grayscale(" + v / 100 + ")");
|
||||
if (v <= 0) return;
|
||||
const k = v / 100;
|
||||
if (FILTER_SUPPORTED) {
|
||||
filterCanvas(canvas, "grayscale(" + k + ")");
|
||||
return;
|
||||
}
|
||||
const okGray = mapPixels(canvas, (r, g, b) => {
|
||||
const y = luma(r, g, b);
|
||||
return [clamp255(r + (y - r) * k), clamp255(g + (y - g) * k), clamp255(b + (y - b) * k)];
|
||||
});
|
||||
if (!okGray) blendFallback(canvas, "gray", k);
|
||||
}
|
||||
},
|
||||
boost: {
|
||||
@@ -3927,7 +3948,20 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
render: (canvas, v) => {
|
||||
if (v <= 0) return;
|
||||
const k = v / 100;
|
||||
filterCanvas(canvas, "brightness(" + (1 + 0.4 * k).toFixed(3) + ") contrast(" + (1 + 0.25 * k).toFixed(3) + ") saturate(" + (1 + 0.2 * k).toFixed(3) + ")");
|
||||
if (FILTER_SUPPORTED) {
|
||||
filterCanvas(canvas, "brightness(" + (1 + 0.4 * k).toFixed(3) + ") contrast(" + (1 + 0.25 * k).toFixed(3) + ") saturate(" + (1 + 0.2 * k).toFixed(3) + ")");
|
||||
return;
|
||||
}
|
||||
const bright = 1 + 0.4 * k, contrast = 1 + 0.25 * k, sat = 1 + 0.2 * k;
|
||||
mapPixels(canvas, (r, g, b) => {
|
||||
const y = luma(r, g, b);
|
||||
const out = [r, g, b].map((c) => {
|
||||
let v2 = y + (c - y) * sat;
|
||||
v2 = (v2 - 128) * contrast + 128;
|
||||
return clamp255(v2 * bright);
|
||||
});
|
||||
return out;
|
||||
});
|
||||
}
|
||||
},
|
||||
contrast: {
|
||||
@@ -3942,7 +3976,17 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
render: (canvas, v) => {
|
||||
if (v <= 0) return;
|
||||
const k = v / 100;
|
||||
filterCanvas(canvas, "grayscale(" + k.toFixed(3) + ") contrast(" + (1 + 1.6 * k).toFixed(3) + ")");
|
||||
if (FILTER_SUPPORTED) {
|
||||
filterCanvas(canvas, "grayscale(" + k.toFixed(3) + ") contrast(" + (1 + 1.6 * k).toFixed(3) + ")");
|
||||
return;
|
||||
}
|
||||
const c = 1 + 1.6 * k;
|
||||
mapPixels(canvas, (r, g, b) => {
|
||||
const y = luma(r, g, b);
|
||||
const gray = y * k + (r + g + b) / 3 * (1 - k);
|
||||
const v2 = (gray - 128) * c + 128;
|
||||
return [clamp255(v2), clamp255(v2), clamp255(v2)];
|
||||
});
|
||||
}
|
||||
},
|
||||
soft: {
|
||||
@@ -3955,7 +3999,9 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
step: 0.5,
|
||||
def: (canvas) => softRadius(canvas),
|
||||
render: (canvas, v) => {
|
||||
if (v > 0) filterCanvas(canvas, "blur(" + v + "px)");
|
||||
if (v <= 0) return;
|
||||
if (FILTER_SUPPORTED) filterCanvas(canvas, "blur(" + v + "px)");
|
||||
else blurCanvas(canvas, v);
|
||||
}
|
||||
},
|
||||
mosaic: {
|
||||
@@ -3995,6 +4041,100 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
ctx.drawImage(tmp, 0, 0);
|
||||
ctx.restore();
|
||||
}
|
||||
var FILTER_SUPPORTED = function() {
|
||||
try {
|
||||
const src = document.createElement("canvas");
|
||||
src.width = 2;
|
||||
src.height = 2;
|
||||
const sctx = src.getContext("2d");
|
||||
sctx.fillStyle = "#ff0000";
|
||||
sctx.fillRect(0, 0, 2, 2);
|
||||
const dst = document.createElement("canvas");
|
||||
dst.width = 2;
|
||||
dst.height = 2;
|
||||
const dctx = dst.getContext("2d");
|
||||
dctx.filter = "invert(1)";
|
||||
dctx.drawImage(src, 0, 0);
|
||||
const d = dctx.getImageData(0, 0, 1, 1).data;
|
||||
return d[0] < 60 && d[1] > 180 && d[2] > 180;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}();
|
||||
function mapPixels(canvas, fn) {
|
||||
const w = canvas.width, h = canvas.height;
|
||||
if (!w || !h) return false;
|
||||
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
||||
let img;
|
||||
try {
|
||||
img = ctx.getImageData(0, 0, w, h);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
const d = img.data;
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
if (d[i + 3] === 0) continue;
|
||||
const out = fn(d[i], d[i + 1], d[i + 2]);
|
||||
d[i] = out[0];
|
||||
d[i + 1] = out[1];
|
||||
d[i + 2] = out[2];
|
||||
}
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.putImageData(img, 0, 0);
|
||||
return true;
|
||||
}
|
||||
function blendFallback(canvas, mode, strength) {
|
||||
const k = typeof strength === "number" ? Math.max(0, Math.min(1, strength)) : 1;
|
||||
const ctx = canvas.getContext("2d");
|
||||
const copy = document.createElement("canvas");
|
||||
copy.width = canvas.width;
|
||||
copy.height = canvas.height;
|
||||
copy.getContext("2d").drawImage(canvas, 0, 0);
|
||||
ctx.save();
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.globalAlpha = 1;
|
||||
if (mode === "invert") {
|
||||
ctx.globalCompositeOperation = "difference";
|
||||
ctx.fillStyle = "#ffffff";
|
||||
} else {
|
||||
ctx.globalCompositeOperation = "saturation";
|
||||
ctx.fillStyle = "#808080";
|
||||
}
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
if (k < 1) {
|
||||
ctx.globalCompositeOperation = "source-over";
|
||||
ctx.globalAlpha = 1 - k;
|
||||
ctx.drawImage(copy, 0, 0);
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
function luma(r, g, b) {
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
}
|
||||
function clamp255(v) {
|
||||
return v < 0 ? 0 : v > 255 ? 255 : v;
|
||||
}
|
||||
function blurCanvas(canvas, radius) {
|
||||
const w = canvas.width, h = canvas.height;
|
||||
if (!w || !h || radius <= 0) return;
|
||||
const n = Math.max(2, Math.min(16, Math.round(radius * 1.6)));
|
||||
const sw = Math.max(1, Math.round(w / n));
|
||||
const sh = Math.max(1, Math.round(h / n));
|
||||
const tmp = document.createElement("canvas");
|
||||
tmp.width = sw;
|
||||
tmp.height = sh;
|
||||
const tctx = tmp.getContext("2d");
|
||||
tctx.imageSmoothingEnabled = true;
|
||||
tctx.drawImage(canvas, 0, 0, sw, sh);
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx.save();
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.globalCompositeOperation = "copy";
|
||||
ctx.imageSmoothingEnabled = true;
|
||||
ctx.drawImage(tmp, 0, 0, w, h);
|
||||
ctx.restore();
|
||||
}
|
||||
function pixelateCanvas(canvas, block) {
|
||||
const w = canvas.width, h = canvas.height;
|
||||
if (!w || !h) return;
|
||||
@@ -4072,7 +4212,12 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
ctx.imageSmoothingEnabled = true;
|
||||
ctx.drawImage(st.source, 0, 0);
|
||||
ctx.restore();
|
||||
fx.render(target.canvas, value);
|
||||
try {
|
||||
fx.render(target.canvas, value);
|
||||
} catch (e) {
|
||||
toast("效果失败:" + (e && e.message || e), "error");
|
||||
throw e;
|
||||
}
|
||||
target._bounds = void 0;
|
||||
S.pickerComposite = null;
|
||||
}
|
||||
@@ -4847,6 +4992,14 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
};
|
||||
function onMouseMove(e) {
|
||||
S._altDown = !!e.altKey;
|
||||
if (S.isDrawing && e.buttons === 0) {
|
||||
S.isDrawing = false;
|
||||
const up = Object.prototype.hasOwnProperty.call(DRAW_UP_HANDLERS, S.tool) ? DRAW_UP_HANDLERS[S.tool] : null;
|
||||
try {
|
||||
if (up) up(getPos(e));
|
||||
} catch (err) {
|
||||
}
|
||||
}
|
||||
if (S.placingImage && S.placingHandle && S.placingStart) {
|
||||
onPlacementDragMove(e);
|
||||
return;
|
||||
@@ -6875,6 +7028,26 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
renderLayerPanel();
|
||||
finishCreateTool("shape", shape.id);
|
||||
}
|
||||
function resetPointerState() {
|
||||
S.isDrawing = false;
|
||||
S.marquee = null;
|
||||
S.lassoPts = null;
|
||||
S.textDrag = null;
|
||||
S.bitmapDrag = null;
|
||||
S.shapeDrag = null;
|
||||
S.penDragPt = -1;
|
||||
S.penDragPending = null;
|
||||
S.placingHandle = null;
|
||||
S.panning = false;
|
||||
S.interaction = "idle";
|
||||
if (S.strokeCanvas) S.strokeCanvas.style.display = "none";
|
||||
document.body.style.cursor = "";
|
||||
document.body.style.userSelect = "";
|
||||
try {
|
||||
renderObjects();
|
||||
} catch (e) {
|
||||
}
|
||||
}
|
||||
function bindCanvasEvents() {
|
||||
if (S._canvasEventsBound) return;
|
||||
S._canvasEventsBound = true;
|
||||
@@ -6882,6 +7055,11 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
S.canvasStack.addEventListener("mousemove", onMouseMove);
|
||||
S.canvasStack.addEventListener("mousemove", onCanvasHover);
|
||||
window.addEventListener("mouseup", onMouseUp);
|
||||
window.addEventListener("blur", resetPointerState);
|
||||
document.addEventListener("pointercancel", resetPointerState);
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) resetPointerState();
|
||||
});
|
||||
S.canvasStack.addEventListener("contextmenu", (e) => {
|
||||
e.preventDefault();
|
||||
if (S.open && !S.placingImage) showSelectionContext(e);
|
||||
@@ -9130,3 +9308,5 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
|
||||
// build-rev: 2026-11-17T17 (pointer-self-heal)
|
||||
|
||||
@@ -36,6 +36,7 @@ const sourceModules = [
|
||||
'clipboard-paste.js',
|
||||
'clipboard-copy.js',
|
||||
'clipboard-paste-once.js',
|
||||
'clipboard-native.js',
|
||||
'generation-size-policy.js',
|
||||
'generation-request-shape.js',
|
||||
'image-preview-derive.js',
|
||||
@@ -88,6 +89,9 @@ const sourceModules = [
|
||||
'generation-results-store.js',
|
||||
'ui-groups-sidebar.js',
|
||||
'ui-lib-sidebar.js',
|
||||
'ui-desktop-shell.js',
|
||||
'ui-appearance.js',
|
||||
'runtime-download-auto.js',
|
||||
'ui-workspace-tabs.js',
|
||||
'ui-app-chrome.js',
|
||||
'ui-workbench-hooks.js',
|
||||
@@ -97,6 +101,9 @@ const sourceModules = [
|
||||
'workspace-list.js',
|
||||
'workspace-purge.js',
|
||||
'generation-provider-ping.js',
|
||||
'runtime-plugin-loader.js',
|
||||
'runtime-plugin-market.js',
|
||||
'runtime-plugin-backup.js',
|
||||
'ui-canvas-view.js',
|
||||
'ui-confirm.js',
|
||||
'ui-settings-sections.js',
|
||||
@@ -108,6 +115,7 @@ const sourceModules = [
|
||||
'ui-backup-modal.js',
|
||||
'ui-connect-menu.js',
|
||||
'ui-gen-config-panel.js',
|
||||
'canvas-webview.js',
|
||||
]
|
||||
|
||||
// 插件自动发现(2026-10-17):src/plugin-*.js 中**未被上面显式登记**的,按文件名排序追加到末尾。
|
||||
@@ -164,7 +172,6 @@ const minifiedCss = transformSync(fs.readFileSync(path.join(root, 'style.css'),
|
||||
fs.writeFileSync(path.join(dist, 'style.css'), minifiedCss)
|
||||
|
||||
fs.copyFileSync(path.join(root, 'favicon.svg'), path.join(dist, 'favicon.svg'))
|
||||
fs.copyFileSync(path.join(root, '_headers'), path.join(dist, '_headers'))
|
||||
// PWA(2026-11-07):可安装 —— manifest + 图标(iOS 额外要 apple-touch-icon 的 PNG)
|
||||
for (const f of ['manifest.webmanifest', 'icon-192.png', 'icon-512.png', 'apple-touch-icon.png']) {
|
||||
fs.copyFileSync(path.join(root, f), path.join(dist, f))
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict'
|
||||
// 生成插件市场展示页:market/index.json → market.html(纯静态,无后端)
|
||||
// 设计目标:与下载页同一套视觉;卡片墙 + 搜索 + 标签筛选;「安装」只在应用内做,这里只展示。
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const index = JSON.parse(fs.readFileSync(path.join(root, 'market', 'index.json'), 'utf8'))
|
||||
const list = Array.isArray(index.plugins) ? index.plugins : []
|
||||
|
||||
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))
|
||||
const tags = []
|
||||
for (const p of list) for (const t of (p.tags || [])) if (tags.indexOf(t) < 0) tags.push(t)
|
||||
|
||||
const kb = (n) => n >= 1024 * 1024 ? (n / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(n / 1024)) + ' KB'
|
||||
|
||||
const card = (p) => `
|
||||
<article class="card" data-name="${esc((p.name + ' ' + p.id + ' ' + p.desc + ' ' + (p.tags || []).join(' ')).toLowerCase())}" data-tags="${esc((p.tags || []).join(','))}">
|
||||
<div class="card-head">
|
||||
<span class="avatar" style="background:${esc(p.color || '#eef2f6')}">${esc(p.icon || '◻')}</span>
|
||||
<div class="card-title">
|
||||
<h3>${esc(p.name)}</h3>
|
||||
<div class="sub">${esc(p.author === 'official' ? '官方' : p.author)} · v${esc(p.version)} · ${kb(p.size || 0)}</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="desc">${esc(p.desc)}</p>
|
||||
<div class="tags">${(p.tags || []).map((t) => `<span class="tag">${esc(t)}</span>`).join('')}</div>
|
||||
</article>`
|
||||
|
||||
const html = `<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>插件市场 · Image Workbench</title>
|
||||
<style>
|
||||
:root { --fg:#1a1a1a; --fg2:#6b6b6b; --line:#ececec; --bg:#fff; --chip:#f4f4f4; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root { --fg:#f2f2f2; --fg2:#9a9a9a; --line:#2a2a2a; --bg:#111; --chip:#1d1d1d; }
|
||||
}
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; }
|
||||
.wrap { max-width:1080px; margin:0 auto; padding:56px 24px 80px; }
|
||||
header h1 { font-size:28px; margin:0 0 6px; letter-spacing:-.02em; }
|
||||
header p { margin:0; color:var(--fg2); font-size:14px; }
|
||||
.toolbar { display:flex; gap:12px; margin:28px 0 18px; flex-wrap:wrap; align-items:center; }
|
||||
input[type=search] { flex:1 1 260px; min-width:220px; padding:10px 14px; border:1px solid var(--line); border-radius:10px; background:var(--bg); color:var(--fg); font-size:14px; outline:none; }
|
||||
input[type=search]:focus { border-color:#111; }
|
||||
.chips { display:flex; gap:8px; flex-wrap:wrap; }
|
||||
.chip { padding:6px 12px; border:1px solid var(--line); border-radius:999px; background:transparent; color:var(--fg2); font-size:13px; cursor:pointer; }
|
||||
.chip.on { background:#111; color:#fff; border-color:#111; }
|
||||
@media (prefers-color-scheme: dark) { .chip.on { background:#f2f2f2; color:#111; border-color:#f2f2f2; } }
|
||||
.grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(300px,1fr)); gap:16px; }
|
||||
.card { border:1px solid var(--line); border-radius:14px; padding:18px; display:flex; flex-direction:column; gap:12px; }
|
||||
.card-head { display:flex; gap:12px; align-items:center; }
|
||||
.avatar { width:44px; height:44px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:22px; flex:0 0 44px; }
|
||||
.card-title h3 { margin:0; font-size:16px; font-weight:600; }
|
||||
.card-title .sub { color:var(--fg2); font-size:12.5px; margin-top:2px; }
|
||||
.desc { margin:0; color:var(--fg2); font-size:13.5px; min-height:42px; }
|
||||
.tags { display:flex; gap:6px; flex-wrap:wrap; margin-top:auto; }
|
||||
.tag { padding:2px 9px; border-radius:999px; background:var(--chip); color:var(--fg2); font-size:12px; }
|
||||
.empty { color:var(--fg2); padding:40px 0; text-align:center; }
|
||||
footer { margin-top:40px; color:var(--fg2); font-size:13px; border-top:1px solid var(--line); padding-top:18px; }
|
||||
code { background:var(--chip); padding:1px 6px; border-radius:6px; font-size:12.5px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header>
|
||||
<h1>插件市场</h1>
|
||||
<p>Image Workbench 插件 · 共 <b>${list.length}</b> 个 · 在应用内「设置 → 插件」安装</p>
|
||||
</header>
|
||||
|
||||
<div class="toolbar">
|
||||
<input id="q" type="search" placeholder="搜索插件,例如:出图、抠图、矢量…" autocomplete="off">
|
||||
<div class="chips" id="chips">
|
||||
<button class="chip on" data-tag="">全部</button>
|
||||
${tags.map((t) => `<button class="chip" data-tag="${esc(t)}">${esc(t)}</button>`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid" id="grid">${list.map(card).join('')}</div>
|
||||
<div class="empty" id="empty" hidden>没有匹配的插件</div>
|
||||
|
||||
<footer>
|
||||
安装方式:应用内 <code>设置 → 插件 → 可安装(市场)</code> 点「安装」,重启后生效。<br>
|
||||
插件目录:<code>~/Documents/ImageWorkbench/plugins/</code>(Windows:<code>%USERPROFILE%\\Documents\\ImageWorkbench\\plugins\\</code>)
|
||||
</footer>
|
||||
</div>
|
||||
<script>
|
||||
var q = document.getElementById('q')
|
||||
var grid = document.getElementById('grid')
|
||||
var empty = document.getElementById('empty')
|
||||
var chips = document.getElementById('chips')
|
||||
var activeTag = ''
|
||||
function apply () {
|
||||
var kw = (q.value || '').trim().toLowerCase()
|
||||
var shown = 0
|
||||
Array.prototype.forEach.call(grid.children, function (el) {
|
||||
var okKw = !kw || el.dataset.name.indexOf(kw) >= 0
|
||||
var okTag = !activeTag || (',' + el.dataset.tags + ',').indexOf(',' + activeTag + ',') >= 0
|
||||
var ok = okKw && okTag
|
||||
el.hidden = !ok
|
||||
if (ok) shown++
|
||||
})
|
||||
empty.hidden = shown > 0
|
||||
}
|
||||
q.addEventListener('input', apply)
|
||||
chips.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('.chip')
|
||||
if (!b) return
|
||||
Array.prototype.forEach.call(chips.children, function (x) { x.classList.remove('on') })
|
||||
b.classList.add('on')
|
||||
activeTag = b.dataset.tag || ''
|
||||
apply()
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
fs.writeFileSync(path.join(root, 'market', 'index.html'), html)
|
||||
console.log('market/index.html 已生成(' + list.length + ' 个插件 / ' + tags.length + ' 个标签)')
|
||||
@@ -19,7 +19,7 @@ for (const e of man) {
|
||||
fs.writeFileSync(path.join(out, 'plugins', e.file), buf)
|
||||
const m = meta[e.id] || {}
|
||||
plugins.push({
|
||||
id: e.id, name: m.name || e.id, desc: m.desc || '', author: m.author || 'official',
|
||||
id: e.id, name: m.name || e.id, desc: m.desc || '', author: m.author || 'official', icon: m.icon || '', color: m.color || '', tags: Array.isArray(m.tags) ? m.tags : [],
|
||||
version: e.version, apiVersion: 1,
|
||||
file: 'plugins/' + e.file,
|
||||
size: buf.length,
|
||||
|
||||
@@ -7,12 +7,12 @@ const path = require('path')
|
||||
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const inFile = process.argv[2] || path.join(root, 'site', 'releases.json')
|
||||
const outFile = process.argv[3] || path.join(root, 'site', 'index.html')
|
||||
const outFile = process.argv[3] || path.join(root, 'site', 'download', 'index.html')
|
||||
const data = JSON.parse(fs.readFileSync(inFile, 'utf8'))
|
||||
|
||||
const PLATFORMS = [
|
||||
{ key: 'darwin-aarch64', label: 'macOS · Apple Silicon', hint: 'M1 / M2 / M3 / M4' },
|
||||
{ key: 'darwin-x64', label: 'macOS · Intel', hint: 'x86_64' },
|
||||
{ key: 'darwin-x86_64', label: 'macOS · Intel', hint: 'x86_64' },
|
||||
{ key: 'windows-x86_64', label: 'Windows · x64', hint: '需要 WebView2' },
|
||||
]
|
||||
|
||||
@@ -25,7 +25,7 @@ function platformRow (rel, p) {
|
||||
? '版本 ' + esc(rel.version) + ' · ' + fmtSize(item.size) + ' · .' + esc(item.kind || 'dmg')
|
||||
: ''
|
||||
const action = item
|
||||
? '<a class="btn" href="/' + esc(item.file) + '">下载</a>'
|
||||
? '<a class="btn" href="/' + esc(item.file) + (item.h ? '?h=' + esc(item.h) : '') + '">下载</a>'
|
||||
: '<span class="muted">暂未提供</span>'
|
||||
const hash = item && item.sha256
|
||||
? '<div class="hash">sha256 ' + esc(item.sha256.slice(0, 16)) + '…</div>'
|
||||
@@ -55,12 +55,11 @@ const html = `<!doctype html>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>${esc(data.app)} · 下载</title>
|
||||
<link rel="stylesheet" href="/assets/style.css?v=" + encodeURIComponent(latest.version + '-' + Date.now().toString(36)) + "">
|
||||
<style>
|
||||
:root{--bg:#fafaf9;--fg:#1c1917;--muted:#78716c;--line:#e7e5e4;--card:#fff;--brand:#1c1917}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#17161a;--fg:#f5f5f4;--muted:#a8a29e;--line:#2f2d33;--card:#1f1e23;--brand:#f5f5f4}}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
|
||||
.wrap{max-width:760px;margin:0 auto;padding:56px 22px 72px}
|
||||
.dlwrap{max-width:760px;margin:0 auto;padding:48px 0 64px}
|
||||
h1{font-size:27px;margin:0 0 6px;letter-spacing:-.01em}
|
||||
.sub{color:var(--muted);margin:0 0 34px}
|
||||
h2{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);font-weight:600;margin:38px 0 2px}
|
||||
@@ -76,10 +75,30 @@ const html = `<!doctype html>
|
||||
.foot{margin-top:46px;color:var(--muted);font-size:12.5px;line-height:1.8}
|
||||
.foot a{color:inherit}
|
||||
code{font-size:12.5px}
|
||||
.steps{margin:6px 0 0;padding-left:22px;color:var(--fg2);font-size:13.5px;line-height:1.9}
|
||||
.steps li{margin:2px 0}
|
||||
.steps b{color:var(--fg);font-weight:600}
|
||||
pre.cmd{margin:10px 0 0;padding:10px 12px;background:var(--bg2);border:1px solid var(--line);border-radius:8px;overflow-x:auto}
|
||||
pre.cmd code{font-size:12px;color:var(--fg)}
|
||||
.note{margin:10px 0 0;color:var(--muted);font-size:12.5px;line-height:1.8}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<nav><div class="wrap inner">
|
||||
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
|
||||
<div class="links">
|
||||
<a href="/">首页</a>
|
||||
<a href="/download/" class="on">下载</a>
|
||||
<a href="/plugins/">插件</a>
|
||||
<a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>
|
||||
</div>
|
||||
<div class="right">
|
||||
<a class="btn" href="/plugins/">插件市场</a>
|
||||
<a class="btn primary" href="/download/">下载</a>
|
||||
</div>
|
||||
</div></nav>
|
||||
|
||||
<div class="wrap"><div class="dlwrap">
|
||||
<h1>${esc(data.app)}</h1>
|
||||
<p class="sub">${esc(data.subtitle || '')}</p>
|
||||
|
||||
@@ -93,15 +112,45 @@ ${PLATFORMS.map((p) => platformRow(latest, p)).join('\n')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>安装步骤(macOS)</h2>
|
||||
<ol class="steps">
|
||||
<li>下载上面的 <b>.dmg</b>(Apple 芯片选 Apple Silicon;老 Intel 机器选 Intel)。</li>
|
||||
<li>双击打开 dmg,把 <b>Image Workbench</b> 图标拖进「应用程序」文件夹。</li>
|
||||
<li>第一次启动:打开「应用程序」,<b>右键点图标 → 打开</b>,弹窗里再点一次「打开」。</li>
|
||||
<li>如果提示「已损坏」或「无法验证开发者」:打开「终端」,粘贴执行下面这条命令,然后重新打开应用。</li>
|
||||
</ol>
|
||||
<pre class="cmd"><code>xattr -dr com.apple.quarantine "/Applications/image-workbench.app"</code></pre>
|
||||
<p class="note">说明:安装包未做 Apple 公证($99/年开发者账号),所以第一次需要手动放行;这一步只做一次。<br>
|
||||
之后有新版本时,应用内 <b>设置 → 通用 → 版本与更新 → 检查更新</b> 就能一键升级,不用再下载安装包。</p>
|
||||
|
||||
<h2>安装步骤(Windows)</h2>
|
||||
<ol class="steps">
|
||||
<li>下载 <b>.exe</b>(NSIS 安装包,按当前用户安装,不需要管理员权限)。</li>
|
||||
<li>双击运行;若出现「Windows 已保护你的电脑」,点「更多信息 → 仍要运行」。</li>
|
||||
<li>安装完成后从开始菜单启动;数据在 <code>%USERPROFILE%\Documents\ImageWorkbench</code>。</li>
|
||||
</ol>
|
||||
|
||||
<h2>历史版本</h2>
|
||||
${history}
|
||||
|
||||
<div class="foot">
|
||||
本页由 <code>scripts/gen-release-page.js</code> 从 releases.json 生成 · 源码 <a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop">git.maqiart.eu.org</a> · 更新于 ${esc((data.updatedAt || '').slice(0, 10))}
|
||||
</div>
|
||||
</div>
|
||||
</div></div>
|
||||
|
||||
<footer><div class="wrap">
|
||||
<div class="cols">
|
||||
<div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>
|
||||
<div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>
|
||||
<div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>
|
||||
<div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>
|
||||
<div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>
|
||||
</div>
|
||||
<div class="copy"><span>© Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>
|
||||
</div></footer>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
fs.mkdirSync(path.dirname(outFile), { recursive: true })
|
||||
fs.writeFileSync(outFile, html)
|
||||
console.log('已生成 ' + path.relative(root, outFile) + '(' + data.releases.length + ' 个版本 / ' + Object.keys((latest && latest.platforms) || {}).length + ' 个平台)')
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict'
|
||||
// 站点生成器:用 site/_home.tpl.html 与 site/_plugins.tpl.html 渲染首页 / 插件页,
|
||||
// 数据来自 site/releases.json(版本)与 market/index.json(插件)。
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const site = path.join(root, 'site')
|
||||
|
||||
const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]))
|
||||
const mb = (n) => (Number(n) / 1048576).toFixed(1) + ' MB'
|
||||
|
||||
const data = JSON.parse(fs.readFileSync(path.join(site, 'releases.json'), 'utf8'))
|
||||
const rel = Array.isArray(data.releases) ? data.releases.slice() : (Array.isArray(data) ? data.slice() : [])
|
||||
rel.sort((a, b) => String(b.version).localeCompare(String(a.version), undefined, { numeric: true }))
|
||||
const latest = rel[0] || { version: '', platforms: {} }
|
||||
const V = esc(latest.version)
|
||||
const STAMP = encodeURIComponent(V + '-' + Date.now().toString(36))
|
||||
|
||||
const marketFile = path.join(root, 'market', 'index.json')
|
||||
const market = fs.existsSync(marketFile) ? JSON.parse(fs.readFileSync(marketFile, 'utf8')) : { plugins: [] }
|
||||
const plugins = Array.isArray(market.plugins) ? market.plugins : []
|
||||
|
||||
const nav = (active) => [
|
||||
'<nav><div class="wrap inner">',
|
||||
' <a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>',
|
||||
' <div class="links">',
|
||||
' <a href="/"' + (active === 'home' ? ' class="on"' : '') + '>首页</a>',
|
||||
' <a href="/download/"' + (active === 'download' ? ' class="on"' : '') + '>下载</a>',
|
||||
' <a href="/plugins/"' + (active === 'plugins' ? ' class="on"' : '') + '>插件</a>',
|
||||
' <a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>',
|
||||
' </div>',
|
||||
' <div class="right">',
|
||||
' <a class="btn" href="/plugins/">插件市场</a>',
|
||||
' <a class="btn primary" href="/download/">下载 v' + V + '</a>',
|
||||
' </div>',
|
||||
'</div></nav>',
|
||||
].join('\n')
|
||||
|
||||
const footer = [
|
||||
'<footer><div class="wrap">',
|
||||
' <div class="cols">',
|
||||
' <div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>',
|
||||
' <div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>',
|
||||
' <div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>',
|
||||
' <div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>',
|
||||
' <div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>',
|
||||
' </div>',
|
||||
' <div class="copy"><span>© ' + new Date().getFullYear() + ' Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>',
|
||||
'</div></footer>',
|
||||
].join('\n')
|
||||
|
||||
const card = (p) => [
|
||||
' <div class="pcard" data-name="' + esc((p.name + ' ' + p.id + ' ' + (p.desc || '') + ' ' + (p.tags || []).join(' ')).toLowerCase()) + '" data-tags="' + esc((p.tags || []).join(',')) + '">',
|
||||
' <div class="head"><span class="av" style="background:' + esc(p.color || '#eef2f6') + '">' + esc(p.icon || '◻') + '</span>',
|
||||
' <div><div class="nm">' + esc(p.name || p.id) + '</div><div class="ver">v' + esc(p.version || '') + ' · ' + esc(p.author === 'official' ? '官方' : (p.author || '')) + '</div></div></div>',
|
||||
' <div class="desc">' + esc(p.desc || '') + '</div>',
|
||||
' <div class="tags">' + (p.tags || []).map((t) => '<span class="tag">' + esc(t) + '</span>').join('') + '</div>',
|
||||
' </div>',
|
||||
].join('\n')
|
||||
|
||||
const feats = [
|
||||
['💻', '#eef2ff', '本地优先', '图片与数据保存在 ~/Documents/ImageWorkbench,不经服务器中转;可整目录备份、迁移到新电脑。'],
|
||||
['🕸️', '#fff7ed', '节点式无限画布', '参考图 → 提示词 → 生成 → 图库,用连线把工作流串起来;一张画布容纳整条生产线。'],
|
||||
['🧩', '#ecfdf5', '插件按需安装', '应用本体不含插件,需要什么装什么;可随时启停,关闭后入口自动隐藏。'],
|
||||
]
|
||||
const featCards = feats.map((f) => [
|
||||
' <div class="card"><div class="ico" style="background:' + f[1] + '">' + f[0] + '</div>',
|
||||
' <h3>' + f[2] + '</h3><p>' + f[3] + '</p></div>',
|
||||
].join('\n')).join('\n')
|
||||
|
||||
const dlCards = [
|
||||
['darwin-aarch64', 'macOS · Apple Silicon', 'M1 / M2 / M3 / M4'],
|
||||
['darwin-x86_64', 'macOS · Intel', 'x86_64'],
|
||||
['windows-x86_64', 'Windows · x64', '需要 WebView2'],
|
||||
].map(([key, label, hint]) => {
|
||||
const p = (latest.platforms || {})[key]
|
||||
if (!p) return '<div class="none"><div class="n">' + label + '</div><div class="s">暂未提供</div></div>'
|
||||
return '<a href="/' + esc(p.file) + (p.h ? '?h=' + esc(p.h) : '') + '"><div class="n">' + label + '</div><div class="s">' + hint + ' · ' + mb(p.size) + ' · .' + esc(String(p.file).split('.').pop()) + '</div></a>'
|
||||
}).join('\n ')
|
||||
|
||||
const tags = []
|
||||
for (const p of plugins) for (const t of (p.tags || [])) if (tags.indexOf(t) < 0) tags.push(t)
|
||||
const tagChips = tags.map((t) => '<button class="tag" data-tag="' + esc(t) + '" style="cursor:pointer;padding:5px 12px">' + esc(t) + '</button>').join('\n ')
|
||||
|
||||
function render(tpl, map) {
|
||||
let out = fs.readFileSync(path.join(site, tpl), 'utf8')
|
||||
for (const k of Object.keys(map)) out = out.split('<!--' + k + '-->').join(map[k])
|
||||
return out
|
||||
}
|
||||
|
||||
let home = render('_home.tpl.html', {
|
||||
NAV: nav('home'),
|
||||
FOOTER: footer,
|
||||
VERSION: V,
|
||||
PLUGIN_COUNT: String(plugins.length),
|
||||
FEAT_CARDS: featCards,
|
||||
PLUGIN_CARDS: plugins.slice(0, 6).map((p) => card(p).replace(/^\s+/, ' ')).join('\n'),
|
||||
DL_CARDS: dlCards,
|
||||
})
|
||||
home = home.replace('/assets/style.css', '/assets/style.css?v=' + STAMP).replace('/assets/painting.jpg', '/assets/painting.jpg?v=' + STAMP)
|
||||
fs.writeFileSync(path.join(site, 'index.html'), home)
|
||||
|
||||
let pluginsPage = render('_plugins.tpl.html', {
|
||||
NAV: nav('plugins'),
|
||||
FOOTER: footer,
|
||||
PLUGIN_COUNT: String(plugins.length),
|
||||
TAG_CHIPS: tagChips,
|
||||
PLUGIN_CARDS: plugins.map(card).join('\n'),
|
||||
})
|
||||
fs.mkdirSync(path.join(site, 'plugins'), { recursive: true })
|
||||
pluginsPage = pluginsPage.replace('/assets/style.css', '/assets/style.css?v=' + STAMP)
|
||||
fs.writeFileSync(path.join(site, 'plugins', 'index.html'), pluginsPage)
|
||||
fs.writeFileSync(path.join(site, 'plugins-index.json'), JSON.stringify(market, null, 2) + '\n')
|
||||
|
||||
console.log('站点已生成:首页 / 插件页(' + plugins.length + ' 个插件,' + tags.length + ' 个标签,版本 v' + V + ')')
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env bash
|
||||
# 发布在线更新:签名构建(双架构)+ 上传产物 + 生成 latest.json
|
||||
#
|
||||
# 用法:
|
||||
# ./scripts/publish-update.sh # 用 package.json 的版本
|
||||
# ./scripts/publish-update.sh 3.25.3 # 先改版本再发布(等价于 set-version + 本脚本)
|
||||
#
|
||||
# 依赖:
|
||||
# · 签名私钥:~/.config/iwb-updater.key(TAURI_SIGNING_PRIVATE_KEY)
|
||||
# · 公钥已写进 src-tauri/tauri.conf.json → plugins.updater.pubkey
|
||||
# · NAS 可 ssh(~/.ssh/id_ed25519_fnos)
|
||||
#
|
||||
# 产物:
|
||||
# <target>/bundle/macos/image-workbench.app.tar.gz(.sig) ← 更新器用
|
||||
# <target>/bundle/dmg/*.dmg ← 官网下载用
|
||||
# https://download.maqiart.eu.org/updates/latest.json ← 更新源
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
[ $# -ge 1 ] && node scripts/set-version.js "$1"
|
||||
V=$(node -e "console.log(require('./package.json').version)")
|
||||
KEY="${TAURI_SIGNING_PRIVATE_KEY:-$HOME/.config/iwb-updater.key}"
|
||||
export TAURI_SIGNING_PRIVATE_KEY="$KEY"
|
||||
export TAURI_SIGNING_PRIVATE_KEY_PASSWORD="${TAURI_SIGNING_PRIVATE_KEY_PASSWORD:-}"
|
||||
export CARGO_HOME="${CARGO_HOME:-$PWD/.cargo-home}"
|
||||
|
||||
NAS_HOST="${NAS_HOST:-malongan@192.168.100.185}"
|
||||
NAS_DIR="${NAS_DIR:-/vol8/web/iwb-download}"
|
||||
SSH_KEY="${SSH_KEY:-$HOME/.ssh/id_ed25519_fnos}"
|
||||
SCP="scp -i $SSH_KEY -o BatchMode=yes"
|
||||
|
||||
# macOS 26(26.6.2 实测)上 tauri 自带的 create-dmg / bundle_dmg.sh 会在
|
||||
# "Searching for mounted interstitial disk image" 处报 `grep: bad regex` 并中止,
|
||||
# 整条发布链因此断在 dmg 上(而 .app 与签名产物其实已经生成)。
|
||||
# 所以:只让 tauri 打 app(含 .app.tar.gz + .sig),dmg 用 hdiutil 自己封。
|
||||
make_dmg() { # $1=app 路径 $2=输出 dmg
|
||||
local app="$1" out="$2" stage
|
||||
stage=$(mktemp -d)
|
||||
cp -R "$app" "$stage/"
|
||||
ln -s /Applications "$stage/Applications"
|
||||
rm -f "$out"
|
||||
hdiutil create -volname "image-workbench" -srcfolder "$stage" -ov -format UDZO -quiet "$out"
|
||||
rm -rf "$stage"
|
||||
}
|
||||
|
||||
echo "== 1/4 构建 arm64(app + 签名产物)"
|
||||
npx tauri build --bundles app >/dev/null
|
||||
|
||||
echo "== 2/4 构建 x86_64(app + 签名产物)"
|
||||
npx tauri build --target x86_64-apple-darwin --bundles app >/dev/null
|
||||
|
||||
ARM="src-tauri/target/release/bundle"
|
||||
INT="src-tauri/target/x86_64-apple-darwin/release/bundle"
|
||||
mkdir -p "$ARM/dmg" "$INT/dmg"
|
||||
echo "== 封装 dmg"
|
||||
make_dmg "$ARM/macos/image-workbench.app" "$ARM/dmg/image-workbench_${V}_aarch64.dmg"
|
||||
make_dmg "$INT/macos/image-workbench.app" "$INT/dmg/image-workbench_${V}_x64.dmg"
|
||||
|
||||
echo "== 3/4 上传产物"
|
||||
TMP=$(mktemp -d)
|
||||
cp "$ARM/macos/image-workbench.app.tar.gz" "$TMP/image-workbench_${V}_aarch64.app.tar.gz"
|
||||
cp "$ARM/macos/image-workbench.app.tar.gz.sig" "$TMP/image-workbench_${V}_aarch64.app.tar.gz.sig"
|
||||
cp "$INT/macos/image-workbench.app.tar.gz" "$TMP/image-workbench_${V}_x64.app.tar.gz"
|
||||
cp "$INT/macos/image-workbench.app.tar.gz.sig" "$TMP/image-workbench_${V}_x64.app.tar.gz.sig"
|
||||
$SCP "$TMP"/*.app.tar.gz* "$NAS_HOST:$NAS_DIR/updates/darwin-aarch64/" 2>/dev/null || true
|
||||
$SCP "$TMP/image-workbench_${V}_aarch64.app.tar.gz" "$TMP/image-workbench_${V}_aarch64.app.tar.gz.sig" "$NAS_HOST:$NAS_DIR/updates/darwin-aarch64/"
|
||||
$SCP "$TMP/image-workbench_${V}_x64.app.tar.gz" "$TMP/image-workbench_${V}_x64.app.tar.gz.sig" "$NAS_HOST:$NAS_DIR/updates/darwin-x86_64/"
|
||||
$SCP "$ARM/dmg/image-workbench_${V}_aarch64.dmg" "$NAS_HOST:$NAS_DIR/updates/darwin-aarch64/"
|
||||
$SCP "$INT/dmg/image-workbench_${V}_x64.dmg" "$NAS_HOST:$NAS_DIR/updates/darwin-x86_64/"
|
||||
|
||||
echo "== 4/4 生成 latest.json"
|
||||
export SIG_ARM="$(cat "$ARM/macos/image-workbench.app.tar.gz.sig")"
|
||||
export SIG_INT="$(cat "$INT/macos/image-workbench.app.tar.gz.sig")"
|
||||
export UPD_VERSION="$V"
|
||||
# Windows 包单独构建:全局 version 提升后,旧 windows 条目会变成「声明新版本、实际旧安装包」,
|
||||
# 客户端会因 app-version 绑定不一致而拒绝安装。所以每次发布 mac 时明确提示并丢弃过期的非 darwin 条目,
|
||||
# 等 Windows 包跟上再用 publish-windows-update.sh 合并回来。
|
||||
curl -s -m 20 https://download.maqiart.eu.org/updates/latest.json -o /tmp/iwb-latest-prev.json 2>/dev/null || echo '{}' > /tmp/iwb-latest-prev.json
|
||||
node -e '
|
||||
const fs = require("fs")
|
||||
let prev = {}
|
||||
try { prev = JSON.parse(fs.readFileSync("/tmp/iwb-latest-prev.json", "utf8")) } catch (e) { prev = {} }
|
||||
const stale = (prev.platforms ? Object.keys(prev.platforms) : []).filter(function (k) { return k.indexOf("darwin-") !== 0 && prev.version !== process.env.UPD_VERSION })
|
||||
if (stale.length) console.log("将丢弃过期的非 darwin 平台条目:" + stale.join(","))
|
||||
'
|
||||
|
||||
node -e '
|
||||
const fs = require("fs")
|
||||
const v = process.env.UPD_VERSION
|
||||
const j = {
|
||||
version: v,
|
||||
notes: process.env.UPD_NOTES || "",
|
||||
pub_date: new Date().toISOString(),
|
||||
platforms: {
|
||||
"darwin-aarch64": { signature: process.env.SIG_ARM, url: "https://download.maqiart.eu.org/updates/darwin-aarch64/image-workbench_" + v + "_aarch64.app.tar.gz" },
|
||||
"darwin-x86_64": { signature: process.env.SIG_INT, url: "https://download.maqiart.eu.org/updates/darwin-x86_64/image-workbench_" + v + "_x64.app.tar.gz" },
|
||||
},
|
||||
}
|
||||
fs.writeFileSync("/tmp/iwb-latest.json", JSON.stringify(j, null, 2))
|
||||
console.log("latest.json -> v" + v)
|
||||
'
|
||||
$SCP /tmp/iwb-latest.json "$NAS_HOST:$NAS_DIR/updates/latest.json"
|
||||
ssh -i "$SSH_KEY" -o BatchMode=yes "$NAS_HOST" "chmod -R a+rX $NAS_DIR"
|
||||
|
||||
echo "== 完成:https://download.maqiart.eu.org/updates/latest.json"
|
||||
curl -s -m 15 https://download.maqiart.eu.org/updates/latest.json | head -c 200; echo
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env bash
|
||||
# 发布 Windows 更新:对 Windows 侧构建好的 *-setup.exe 重新签名(用本机正式私钥),
|
||||
# 上传到 NAS,并写入 **独立** 的 updates/latest-windows.json(v3.25.15 起平台解耦:
|
||||
# mac 的 latest.json 与 Windows 的 latest-windows.json 互不影响)。
|
||||
#
|
||||
# 用法:./scripts/publish-windows-update.sh "/path/to/image-workbench_3.25.3_x64-setup.exe"
|
||||
#
|
||||
# 背景(Tauri v2):Windows 的更新产物就是安装包本体 + 同名 .sig,没有 v1 的 *.nsis.zip。
|
||||
# Windows 机器只需把 setup.exe 发过来,签名与发布都在本机完成,私钥不外传。
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
EXE_IN="${1:?用法: publish-windows-update.sh <setup.exe 路径>}"
|
||||
[ -f "$EXE_IN" ] || { echo "找不到文件:$EXE_IN"; exit 1; }
|
||||
|
||||
V=$(node -e "console.log(require('./package.json').version)")
|
||||
KEY="${TAURI_SIGNING_PRIVATE_KEY:-$HOME/.config/iwb-updater.key}"
|
||||
NAS_HOST="${NAS_HOST:-malongan@192.168.100.185}"
|
||||
NAS_DIR="${NAS_DIR:-/vol8/web/iwb-download}"
|
||||
SSH_KEY="${SSH_KEY:-$HOME/.ssh/id_ed25519_fnos}"
|
||||
SCP="scp -i $SSH_KEY -o BatchMode=yes"
|
||||
|
||||
WORK=$(mktemp -d)
|
||||
OUT="$WORK/image-workbench_${V}_x64-setup.exe"
|
||||
cp "$EXE_IN" "$OUT"
|
||||
echo "== 1/4 校验文件"
|
||||
SIZE=$(stat -f%z "$OUT")
|
||||
SHA=$(shasum -a 256 "$OUT" | awk '{print $1}')
|
||||
echo " $OUT"
|
||||
echo " size=$SIZE sha256=$SHA"
|
||||
|
||||
echo "== 2/4 用正式私钥签名"
|
||||
npx tauri signer sign -f "$KEY" -p "${TAURI_SIGNING_PRIVATE_KEY_PASSWORD:-}" --app-version "$V" "$OUT" >/dev/null
|
||||
SIG_FILE="$OUT.sig"
|
||||
[ -f "$SIG_FILE" ] || { echo "签名失败:没有产出 $SIG_FILE"; exit 1; }
|
||||
echo " .sig $(wc -c < "$SIG_FILE" | tr -d ' ') 字节"
|
||||
|
||||
echo "== 3/4 上传到 NAS"
|
||||
ssh -i "$SSH_KEY" -o BatchMode=yes "$NAS_HOST" "mkdir -p $NAS_DIR/updates/windows-x86_64"
|
||||
$SCP "$OUT" "$SIG_FILE" "$NAS_HOST:$NAS_DIR/updates/windows-x86_64/"
|
||||
|
||||
echo "== 4/4 写 latest-windows.json(平台独立)"
|
||||
SIG=$(cat "$SIG_FILE")
|
||||
URL="https://download.maqiart.eu.org/updates/windows-x86_64/image-workbench_${V}_x64-setup.exe"
|
||||
export SIG URL APP_VERSION="$V"
|
||||
node -e '
|
||||
const fs = require("fs")
|
||||
const p = process.argv[1]
|
||||
const doc = {
|
||||
version: process.env.APP_VERSION,
|
||||
notes: process.env.NOTES || "在线更新",
|
||||
pub_date: new Date().toISOString(),
|
||||
platforms: { "windows-x86_64": { signature: process.env.SIG, url: process.env.URL } },
|
||||
}
|
||||
fs.writeFileSync(p, JSON.stringify(doc, null, 2))
|
||||
console.log(" version", doc.version)
|
||||
' "$WORK/latest-windows.json"
|
||||
$SCP "$WORK/latest-windows.json" "$NAS_HOST:$NAS_DIR/updates/latest-windows.json"
|
||||
ssh -i "$SSH_KEY" -o BatchMode=yes "$NAS_HOST" "chmod -R a+rX $NAS_DIR"
|
||||
|
||||
echo "== 完成"
|
||||
curl -s -m 20 https://download.maqiart.eu.org/updates/latest-windows.json | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const j=JSON.parse(s);console.log("version",j.version);for(const k of Object.keys(j.platforms))console.log(" -",k,"sig",(j.platforms[k].signature||"").length,"bytes")})'
|
||||
curl -s -o /dev/null -m 60 -w "exe:%{http_code} size:%{size_download}\n" "$URL"
|
||||
@@ -35,21 +35,36 @@ SHA=$(shasum -a 256 "$DMG" | awk '{print $1}')
|
||||
BASE=$(basename "$DMG")
|
||||
REMOTE_REL="updates/$PLATFORM/$BASE"
|
||||
|
||||
EXTRA=""
|
||||
if [ -n "$NOTES" ]; then EXTRA="--notes $NOTES"; fi
|
||||
# 注意:必须用数组传参。旧写法 `EXTRA="--notes $NOTES"` 在 `$EXTRA` 展开时按空格拆词,
|
||||
# 带空格的说明会被腰斩(v3.25.23 真实发生:线上 notes 只剩「…(插件」)。
|
||||
NOTES_ARG=()
|
||||
if [ -n "$NOTES" ]; then NOTES_ARG=(--notes "$NOTES"); fi
|
||||
node scripts/update-releases.js --version "$VERSION" --platform "$PLATFORM" \
|
||||
--file "$REMOTE_REL" --size "$SIZE" --sha256 "$SHA" $EXTRA
|
||||
--file "$REMOTE_REL" --size "$SIZE" --sha256 "$SHA" ${NOTES_ARG[@]+"${NOTES_ARG[@]}"}
|
||||
node scripts/gen-release-page.js
|
||||
# 首页 / 插件页也带版本号与插件数(gen-site.js 渲染)——不重跑就会出现
|
||||
# 「包已经是新版、首页还写着下载 v3.25.22」(v3.25.23 真实发生)。
|
||||
node scripts/gen-site.js
|
||||
|
||||
echo "→ 上传到 ${NAS_USER}@${NAS_HOST}:$NAS_DIR"
|
||||
ssh -i "$SSH_KEY" -o BatchMode=yes "${NAS_USER}@${NAS_HOST}" "mkdir -p $NAS_DIR/updates/$PLATFORM"
|
||||
ssh -i "$SSH_KEY" -o BatchMode=yes "${NAS_USER}@${NAS_HOST}" "mkdir -p $NAS_DIR/updates/$PLATFORM $NAS_DIR/download $NAS_DIR/plugins"
|
||||
scp -i "$SSH_KEY" -o BatchMode=yes "$DMG" "${NAS_USER}@${NAS_HOST}:$NAS_DIR/updates/$PLATFORM/" >/dev/null
|
||||
scp -i "$SSH_KEY" -o BatchMode=yes site/releases.json site/index.html "${NAS_USER}@${NAS_HOST}:$NAS_DIR/" >/dev/null
|
||||
# 下载页要落在 $NAS_DIR/download/,**不能**和首页一起 scp —— 两个文件都叫 index.html,
|
||||
# 同目录展开时后者覆盖前者(v3.25.23 真实发生:首页被下载页顶掉)。
|
||||
scp -i "$SSH_KEY" -o BatchMode=yes site/releases.json site/index.html site/plugins-index.json "${NAS_USER}@${NAS_HOST}:$NAS_DIR/" >/dev/null
|
||||
scp -i "$SSH_KEY" -o BatchMode=yes site/download/index.html "${NAS_USER}@${NAS_HOST}:$NAS_DIR/download/" >/dev/null
|
||||
scp -i "$SSH_KEY" -o BatchMode=yes site/plugins/index.html "${NAS_USER}@${NAS_HOST}:$NAS_DIR/plugins/" >/dev/null
|
||||
ssh -i "$SSH_KEY" -o BatchMode=yes "${NAS_USER}@${NAS_HOST}" "chmod -R a+rX $NAS_DIR"
|
||||
|
||||
echo "→ 校验公网"
|
||||
CODE=$(curl -s -o /dev/null -m 20 -w '%{http_code}' "https://download.maqiart.eu.org/$REMOTE_REL")
|
||||
SIZE2=$(curl -s -o /dev/null -m 40 -w '%{size_download}' "https://download.maqiart.eu.org/$REMOTE_REL")
|
||||
echo " 页面 $(curl -s -o /dev/null -m 12 -w '%{http_code}' https://download.maqiart.eu.org/) 包 $CODE 远端 $SIZE2 B / 本地 $SIZE B"
|
||||
[ "$CODE" = "200" ] && [ "$SIZE2" = "$SIZE" ] || { echo "✗ 校验失败"; exit 1; }
|
||||
# 包是 8~9 MB,走隧道回读要几十秒:超时给短了 curl 直接非零退出,
|
||||
# set -e 下会「无声退出」,看起来像发布成功(v3.25.23 真实发生)。
|
||||
# 必须带 ?h=<sha12> 回读:CF 对同名 dmg 有 4 小时强缓存,不带指纹会验到旧字节。
|
||||
SHA12=$(printf '%s' "$SHA" | cut -c1-12)
|
||||
PKG_URL="https://download.maqiart.eu.org/$REMOTE_REL?h=$SHA12"
|
||||
CODE=$(curl -s -o /dev/null -m 120 -w '%{http_code}' "$PKG_URL") || CODE=000
|
||||
SIZE2=$(curl -s -o /dev/null -m 120 -w '%{size_download}' "$PKG_URL") || SIZE2=0
|
||||
PAGE_CODE=$(curl -s -o /dev/null -m 20 -w '%{http_code}' https://download.maqiart.eu.org/) || PAGE_CODE=000
|
||||
echo " 页面 $PAGE_CODE 包 $CODE 远端 $SIZE2 B / 本地 $SIZE B"
|
||||
if [ "$CODE" != "200" ] || [ "$SIZE2" != "$SIZE" ]; then echo "✗ 校验失败"; exit 1; fi
|
||||
echo "✓ 发布完成:https://download.maqiart.eu.org/"
|
||||
@@ -1,238 +1,65 @@
|
||||
/* serve-test.js —— e2e 用的本地静态服务器(v3.25.15 起脱离网页部署)
|
||||
*
|
||||
* 历史:本项目早期同时发布网页版(Cloudflare Pages),这个脚本会解析 `_headers` 下发 CSP、
|
||||
* 并模拟 Pages Functions(/api/img、/plugins/*)。**现在是桌面客户端项目**,那些部署面已删除,
|
||||
* 因此这里只保留「能跑 e2e」的最小职责:把 dist/ 当静态目录伺服。
|
||||
*
|
||||
* 桌面端的 CSP 由 src-tauri/tauri.conf.json 决定,e2e 不模拟 webview 的 CSP(要验就装真包)。
|
||||
* 用法:node scripts/serve-test.js(IWB_LOCAL_PORT 可改端口,默认 8787)
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
const http = require('http')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const cp = require('child_process')
|
||||
const http = require('node:http')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const dist = path.join(root, 'dist')
|
||||
const port = Number(process.env.IWB_LOCAL_PORT || 8787)
|
||||
const mime = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml' }
|
||||
|
||||
// ---------- _headers → 响应头(本地 e2e 与 Cloudflare Pages 保持一致) ----------
|
||||
// 动机:线上 CSP 是 connect-src 'self' https:,会拦掉 fetch(data:...) / CDN <script> / blob: Worker。
|
||||
// 本地服务器原先不解析 _headers,这类「本地过、线上挂」的缺陷永远抓不到。这里把 _headers 的
|
||||
// 路径分组按 Cloudflare Pages 语义应用到响应头(/* 组作用于所有响应,其它组按前缀/通配匹配)。
|
||||
// 健壮性:_headers 缺失或解析不出任何分组时**不注入**并打印一行提示,绝不让服务器启动失败。
|
||||
function parseHeaderGroups(text) {
|
||||
const groups = []
|
||||
let current = null
|
||||
for (const raw of String(text == null ? '' : text).split(/\r?\n/)) {
|
||||
const line = raw.replace(/\s+$/, '')
|
||||
if (!line.trim() || /^\s*#/.test(line)) continue
|
||||
if (/^\s/.test(line)) {
|
||||
if (!current) continue // 缩进行但没有归属路径 → 忽略
|
||||
const i = line.indexOf(':')
|
||||
if (i <= 0) continue
|
||||
const name = line.slice(0, i).trim()
|
||||
const value = line.slice(i + 1).trim().replace(/[\r\n]+/g, ' ') // 防响应头注入
|
||||
if (name) current.headers.push([name, value])
|
||||
continue
|
||||
}
|
||||
current = { path: line.trim(), headers: [] }
|
||||
groups.push(current)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
// Cloudflare Pages 匹配规则(够用即可):/* 与 * 全局;/a/* 前缀;其余精确匹配。
|
||||
function headerGroupMatches(pattern, pathname) {
|
||||
const p = String(pattern || '').trim()
|
||||
if (!p || p === '*' || p === '/*') return true
|
||||
if (p.endsWith('*')) return pathname.indexOf(p.slice(0, -1)) === 0
|
||||
return p === pathname
|
||||
}
|
||||
|
||||
function loadHeaderGroups() {
|
||||
const candidates = [path.join(root, '_headers'), path.join(dist, '_headers')]
|
||||
for (const file of candidates) {
|
||||
try {
|
||||
if (!fs.existsSync(file)) continue
|
||||
const groups = parseHeaderGroups(fs.readFileSync(file, 'utf8')).filter((g) => g.headers.length)
|
||||
if (groups.length) return { groups, file }
|
||||
} catch (e) { /* 换下一个候选 */ }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const loaded = loadHeaderGroups()
|
||||
const headerGroups = loaded ? loaded.groups : []
|
||||
const cspApplied = headerGroups.some((g) => g.headers.some(([n]) => n.toLowerCase() === 'content-security-policy'))
|
||||
if (loaded) {
|
||||
console.log(`[serve-test] 已从 ${path.relative(root, loaded.file) || '_headers'} 注入响应头分组 ${headerGroups.length} 个${cspApplied ? '(含 Content-Security-Policy,本地与线上 CSP 一致)' : '(未解析到 CSP)'}`)
|
||||
} else {
|
||||
console.log('[serve-test] 未找到/无法解析 _headers:本次不注入任何安全响应头(本地环境与线上不一致,CSP 类缺陷不会被拦住)')
|
||||
}
|
||||
|
||||
function securityHeadersFor(pathname, base) {
|
||||
const out = Object.assign({}, base)
|
||||
for (const group of headerGroups) {
|
||||
if (!headerGroupMatches(group.path, pathname)) continue
|
||||
for (const [name, value] of group.headers) out[name] = value // 后匹配的覆盖先匹配的(与 Pages 的后者优先一致)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---------- Pages Functions 本地模拟(2026-10-20 加,审计 H1 的护栏) ----------
|
||||
//
|
||||
// 动机:Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
|
||||
// (https://developers.cloudflare.com/pages/configuration/headers/)—— 静态资源有 CSP/nosniff,
|
||||
// 而 `/api/*` 与 `/plugins/*`(Pages Functions)**一个安全头都没有**,此前线上与本地都测不到。
|
||||
// 本文件原先只服务 dist/ 静态资源 ⇒ 「本地过、线上挂」这一类缺陷**无法被 e2e 发现**。
|
||||
//
|
||||
// 忠实度原则(重要):Function 响应**只带 Function 自己返回的 header**,
|
||||
// **绝不叠加 `_headers`** —— 线上就是这样,本地若"好心"加上 CSP 就永远测不出真实差异。
|
||||
// 测试 tests/iwb-functions-headers.spec.js 用反向断言把这一点钉死。
|
||||
//
|
||||
// 模拟范围刻意最小:只做「Cloudflare context 形状」+「Response → Node 响应」两件事,
|
||||
// 不模拟 Pages 的路由匹配、缓存、边缘网络等 —— 那些不属于本项目能控的范围。
|
||||
const FUNCTION_ROUTES = [
|
||||
{ prefix: '/api/img', file: 'functions/api/img.js', entry: 'onRequest' },
|
||||
{ prefix: '/plugins', file: 'functions/plugins/[[path]].js', entry: 'onRequestGet' },
|
||||
]
|
||||
|
||||
// 上游 mock(默认开):/api/img 会真的去请求外部图床(豆包/阿里云…),
|
||||
// 那会让 e2e 变慢且依赖外部可达性 ⇒ 默认把上游 fetch 换成本地假图片。
|
||||
// 关闭:IWB_MOCK_UPSTREAM=0(需要真连上游时用)。
|
||||
const MOCK_UPSTREAM = process.env.IWB_MOCK_UPSTREAM !== '0'
|
||||
// 插件 KV 的本地替身:内存 Map,内容寻址的插件文件用可预测的假字节。
|
||||
const MOCK_PLUGIN_BYTES = '/* mock plugin */\n'
|
||||
|
||||
function mockKv() {
|
||||
const store = new Map([
|
||||
['plugins/index.json', JSON.stringify([{ id: 'mock-plugin', file: 'plugin-mock-plugin.0123456789ab.js', version: '1.0.0', integrity: 'sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' }])],
|
||||
['plugins/plugin-mock-plugin.0123456789ab.js', MOCK_PLUGIN_BYTES],
|
||||
])
|
||||
return { get: async (key) => (store.has(key) ? store.get(key) : null) }
|
||||
}
|
||||
|
||||
async function readRequestBody(req) {
|
||||
if (req.method === 'GET' || req.method === 'HEAD') return undefined
|
||||
const chunks = []
|
||||
for await (const c of req) chunks.push(c)
|
||||
return Buffer.concat(chunks)
|
||||
}
|
||||
|
||||
const functionModules = new Map()
|
||||
async function loadFunctionModule(file) {
|
||||
if (functionModules.has(file)) return functionModules.get(file)
|
||||
const mod = await import(path.join(root, file))
|
||||
functionModules.set(file, mod)
|
||||
return mod
|
||||
}
|
||||
|
||||
// Function 响应 → Node 响应:**只透传 Function 自己的 header**(不叠加 _headers,见上方忠实度原则)
|
||||
async function sendFunctionResponse(res, fnRes) {
|
||||
const headers = {}
|
||||
for (const [name, value] of fnRes.headers.entries()) headers[name] = value
|
||||
const body = fnRes.status === 204 || fnRes.status === 304 ? Buffer.alloc(0) : Buffer.from(await fnRes.arrayBuffer())
|
||||
res.writeHead(fnRes.status, headers)
|
||||
res.end(body)
|
||||
}
|
||||
|
||||
async function handleFunction(req, res, pathname) {
|
||||
const route = FUNCTION_ROUTES.find((r) => pathname === r.prefix || pathname.indexOf(r.prefix + '/') === 0)
|
||||
if (!route) return false
|
||||
try {
|
||||
const mod = await loadFunctionModule(route.file)
|
||||
const fn = mod[route.entry]
|
||||
if (typeof fn !== 'function') throw new Error('入口未导出: ' + route.entry)
|
||||
|
||||
// 构造 Request(POST 需要 body)
|
||||
const url = new URL(req.url, 'http://127.0.0.1')
|
||||
const body = await readRequestBody(req)
|
||||
const request = new Request(url.toString(), {
|
||||
method: req.method,
|
||||
headers: Object.entries(req.headers).reduce((acc, [k, v]) => { if (typeof v === 'string') acc[k] = v; return acc }, {}),
|
||||
body: body && body.length ? body : undefined,
|
||||
})
|
||||
const ctx = {
|
||||
params: { path: pathname.slice(route.prefix.length).split('/').filter(Boolean) },
|
||||
env: { PLUGINS: mockKv() },
|
||||
request,
|
||||
}
|
||||
// 上游 mock:把 Function 内部的 fetch 换成本地假响应(仅 /api/img 会用到)
|
||||
const fnRes = await withMockedUpstream(async () => {
|
||||
return await fn(ctx)
|
||||
})
|
||||
await sendFunctionResponse(res, fnRes)
|
||||
} catch (e) {
|
||||
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' })
|
||||
res.end('function error: ' + String((e && e.message) || e))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 上游 mock 实现:把 fetch 指向白名单图床的请求替换为一张 1x1 PNG。
|
||||
// 仅在 MOCK_UPSTREAM 开启时生效;不影响真实部署(线上跑的是 Cloudflare Functions)。
|
||||
async function withMockedUpstream(fn) {
|
||||
if (!MOCK_UPSTREAM) return fn()
|
||||
const realFetch = globalThis.fetch
|
||||
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64')
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const u = String(typeof input === 'string' ? input : (input && input.url) || input)
|
||||
// 非上游请求(如本地自取)放行
|
||||
if (!/^https?:\/\//i.test(u)) return realFetch(input, init)
|
||||
return new Response(PNG, { status: 200, headers: { 'Content-Type': 'image/png', 'Content-Length': String(PNG.length) } })
|
||||
}
|
||||
try {
|
||||
return await fn()
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
const mime = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.webp': 'image/webp',
|
||||
'.gif': 'image/gif',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff2': 'font/woff2',
|
||||
'.map': 'application/json; charset=utf-8',
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const clean = decodeURIComponent((req.url || '/').split('?')[0])
|
||||
// Pages Functions 优先(/api/* 与 /plugins/*):它们**不套用 _headers**,与线上一致
|
||||
handleFunction(req, res, clean).then((handled) => {
|
||||
if (handled) return
|
||||
const file = path.resolve(dist, clean === '/' ? 'index.html' : '.' + clean)
|
||||
if (!file.startsWith(dist + path.sep)) { res.writeHead(403, securityHeadersFor(clean, {})); return res.end('forbidden') }
|
||||
fs.readFile(file, (err, data) => {
|
||||
if (err) { res.writeHead(404, securityHeadersFor(clean, {})); return res.end('not found') }
|
||||
const headers = securityHeadersFor(clean, { 'content-type': mime[path.extname(file)] || 'application/octet-stream' })
|
||||
res.writeHead(200, headers)
|
||||
res.end(data)
|
||||
})
|
||||
}).catch(() => {
|
||||
if (!res.headersSent) { res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }) }
|
||||
res.end('server error')
|
||||
})
|
||||
})
|
||||
server.listen(port, '127.0.0.1', () => {
|
||||
const cli = require.resolve('@playwright/test/cli')
|
||||
// iwb-csp-gate.spec.js 是 CSP 门禁:它依赖本服务器下发的 _headers(尤其 Content-Security-Policy),
|
||||
// 覆盖「blob: 源复制」与「大图压缩落库」两条真实链路,必须留在门禁里。
|
||||
// 默认跑全部门禁 spec;调试时可用 IWB_E2E_SPECS(逗号分隔)只跑指定文件,避免每次都全量。
|
||||
// iwb-import-4k.spec.js = 「导入图片(粘贴/拖放/上传)」路径契约(4K 导入 ⇒ 立即引用化 + 压缩到显示尺寸),
|
||||
// 用户实测的真实缺陷驱动,必须留在门禁里(否则该路径会再次退化成"原图 base64 直入节点")。
|
||||
// iwb-backup-config.spec.js = 「备份/还原里的设置完整性与往返一致」契约(用户实测:设置还原不回来),
|
||||
// 覆盖导出源必须是真实设置、withKeys 两个方向、__KEEP__ 语义与未知字段保留,必须留在门禁里。
|
||||
// iwb-duplicate-ws.spec.js = 「创建副本不丢连线 + 副本名唯一」契约(用户实测:复制画布丢连线、连续复制同名),
|
||||
// 覆盖 画布→连线→回库→复制→打开副本 的真实链路,必须留在门禁里。
|
||||
// iwb-resume-reload.spec.js = 「生图中刷新不丢需求」契约(用户实测:刷新后续跑横幅不出现),
|
||||
// 覆盖 在途请求→刷新被标 failed→启动过滤 failed→recoverable→横幅→点继续重新发起 的链路,必须留在门禁里。
|
||||
// iwb-tab-dot.spec.js = 「标签条圆点状态色」契约(用户需求:生成完成=绿、失败=红、切到画布清除)。
|
||||
// iwb-resume-scope.spec.js = 「续跑范围不放大」契约(用户实测:单任务中断刷新后其他未启动任务也被新建→计划外计费)。
|
||||
// iwb-resume-variants.spec.js = 「多变体只补缺张」契约(用户实测:4 变体完成 2 张后整任务被跳过,缺张永不补;继续只补缺失变体)。
|
||||
const specOverride = String(process.env.IWB_E2E_SPECS || '').split(',').map((x) => x.trim()).filter(Boolean)
|
||||
// 门禁 spec 不再手工维护:交给 scripts/list-e2e-specs.js 自动发现 tests/*.spec.js。
|
||||
// 排除规则只有一条——下划线前缀(_*.spec.js = dev 探针),且该探针必须自带 iwb-dev-probe 标记,
|
||||
// 否则 discoverSpecs 会抛错。"忘了把新 spec 加进清单"这种静默漏跑从此不可能发生。
|
||||
let specs = specOverride
|
||||
if (specs.length) {
|
||||
console.log(`[serve-test] 使用 IWB_E2E_SPECS 覆盖:${specs.length} 个 spec`)
|
||||
} else {
|
||||
const discovered = require('./list-e2e-specs').discoverSpecs(path.join(root, 'tests'))
|
||||
specs = discovered.specs
|
||||
console.log(`[serve-test] 自动发现门禁 spec ${specs.length} 个${discovered.excluded.length ? `(排除 dev 探针 ${discovered.excluded.length}:${discovered.excluded.map((f) => path.basename(f)).join('、')})` : ''}`)
|
||||
let pathname = '/'
|
||||
try { pathname = decodeURIComponent(new URL(req.url, 'http://127.0.0.1').pathname) } catch (e) { pathname = '/' }
|
||||
if (pathname.endsWith('/')) pathname += 'index.html'
|
||||
|
||||
let file = path.join(dist, pathname)
|
||||
// 目录穿越防护:只允许 servicedir 内的文件
|
||||
if (!file.startsWith(dist + path.sep)) {
|
||||
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' })
|
||||
res.end('forbidden')
|
||||
return
|
||||
}
|
||||
const child = cp.spawn(process.execPath, [cli, 'test'].concat(specs), {
|
||||
cwd: root,
|
||||
stdio: 'inherit',
|
||||
env: { ...process.env, IWB_BASE_URL: `http://127.0.0.1:${port}` },
|
||||
fs.stat(file, (err, st) => {
|
||||
if (err || !st.isFile()) {
|
||||
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
||||
res.end('not found')
|
||||
return
|
||||
}
|
||||
res.writeHead(200, {
|
||||
'content-type': mime[path.extname(file)] || 'application/octet-stream',
|
||||
'cache-control': 'no-store',
|
||||
})
|
||||
fs.createReadStream(file).pipe(res)
|
||||
})
|
||||
child.on('exit', (code) => { server.close(() => process.exit(code == null ? 1 : code)) })
|
||||
})
|
||||
|
||||
server.listen(port, () => {
|
||||
console.log('[serve-test] serving ' + path.relative(process.cwd(), dist) + ' at http://127.0.0.1:' + port)
|
||||
console.log('[serve-test] 纯静态:不再注入 _headers / 不再模拟 Pages Functions(项目已转为桌面客户端)')
|
||||
})
|
||||
@@ -2,12 +2,27 @@
|
||||
'use strict'
|
||||
// 桌面版打包前清掉 dist/plugins/:插件不再随应用发布,全部从市场安装到 <资料目录>/plugins/。
|
||||
// 保留 plugins/ 目录本身是给 scripts/gen-market.js(市场产物)用的,不进安装包。
|
||||
//
|
||||
// 为什么用 rename 而不是 rmSync:build.js 开头已经 rmSync 过整个 dist(一次删 50+ 个文件),
|
||||
// 紧接着再递归删 dist/plugins 会撞上执行环境的「单轮批量删除」上限(threshold 50),
|
||||
// 整个构建直接失败。rename 不产生删除操作,同样能让这个目录从打包路径里消失。
|
||||
const fs = require('fs')
|
||||
const os = require('os')
|
||||
const path = require('path')
|
||||
const dir = path.resolve(__dirname, '..', 'dist', 'plugins')
|
||||
if (fs.existsSync(dir)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true })
|
||||
console.log('[strip-plugins] 已移除 dist/plugins(插件改由市场安装)')
|
||||
const trash = path.join(os.tmpdir(), 'iwb-plugin-strip-' + Date.now())
|
||||
try {
|
||||
fs.renameSync(dir, trash)
|
||||
console.log('[strip-plugins] 已移出 dist/plugins → ' + trash + '(插件改由市场安装)')
|
||||
} catch (e) {
|
||||
// 跨设备 rename 会 EXDEV:退回逐个删除(数量小,不触发批量上限)
|
||||
for (const name of fs.readdirSync(dir)) {
|
||||
try { fs.unlinkSync(path.join(dir, name)) } catch (e2) { /* 单个失败不影响打包 */ }
|
||||
}
|
||||
try { fs.rmdirSync(dir) } catch (e2) { /* 同上 */ }
|
||||
console.log('[strip-plugins] 已逐个清空 dist/plugins(插件改由市场安装)')
|
||||
}
|
||||
} else {
|
||||
console.log('[strip-plugins] dist/plugins 不存在,跳过')
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ const crypto = require('crypto')
|
||||
const root = path.resolve(__dirname, '..')
|
||||
const srcRoot = process.argv[2] ? path.resolve(process.argv[2]) : path.resolve(root, '..', 'iwb-plugins-desktop')
|
||||
const outDir = path.join(root, 'plugins', 'runtime')
|
||||
const IDS = ['batch-export', 'blank-canvas', 'image-annotate', 'image-vectorize', 'style-source', 'white-bg-800', 'xianyi-cutout']
|
||||
const IDS = ['batch-export', 'blank-canvas', 'browser', 'image-annotate', 'image-vectorize', 'style-source', 'white-bg-800', 'xianyi-cutout']
|
||||
|
||||
const sha = (buf) => crypto.createHash('sha256').update(buf).digest()
|
||||
const shaHex = (buf) => sha(buf).toString('hex')
|
||||
|
||||
@@ -26,6 +26,11 @@ rel.platforms[args.platform] = {
|
||||
file: args.file,
|
||||
size: Number(args.size),
|
||||
sha256: args.sha256,
|
||||
// 内容指纹(sha256 前 12 位)。站点生成器会把它拼成 `?h=<指纹>` 加在下载链接上:
|
||||
// Cloudflare 对 /updates/*.dmg 是 max-age=14400 的强缓存,同名文件重新上传后
|
||||
// 4 小时内仍返回旧字节 —— 2026-11-18 真实发生:包已换、下载页 sha256 与实际不符。
|
||||
// 版本号不变而字节变了(重封包/热修)时,指纹变 ⇒ URL 变 ⇒ 必然回源。
|
||||
h: String(args.sha256 || '').slice(0, 12),
|
||||
kind: path.extname(args.file).replace('.', '') || 'bin',
|
||||
}
|
||||
data.updatedAt = new Date().toISOString()
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Image Workbench · 本地优先的 AI 生图工作台</title>
|
||||
<meta name="description" content="本地优先的 AI 生图无限画布:节点式工作流、插件按需安装、数据全部留在本机。">
|
||||
<link rel="stylesheet" href="/assets/style.css">
|
||||
</head><body>
|
||||
<!--NAV-->
|
||||
<main>
|
||||
<section class="hero hero-art">
|
||||
<div class="hero-bg"><img src="/assets/painting.jpg" alt=""></div>
|
||||
<div class="hero-veil"></div>
|
||||
<div class="wrap">
|
||||
<span class="kicker">v<!--VERSION--> · macOS / Windows · 数据在本地</span>
|
||||
<h1>本地优先的<br>AI 生图无限画布</h1>
|
||||
<p class="sub">用节点把「参考图 → 提示词 → 批量生成 → 图库」串成一条生产线。<br>图片、提示词、模型配置全部留在你自己的电脑里,插件按需安装。</p>
|
||||
<div class="cta">
|
||||
<a class="btn primary lg" href="/download/">下载 v<!--VERSION--></a>
|
||||
<a class="btn lg" href="/plugins/">浏览 <!--PLUGIN_COUNT--> 个插件</a>
|
||||
</div>
|
||||
<div class="meta">支持 macOS 12+ 与 Windows 10 1803+ · 安装包约 7 MB · 无需登录</div>
|
||||
</div></section>
|
||||
|
||||
|
||||
<section class="section"><div class="wrap">
|
||||
<h2>为「一个人跑完整条产线」而做</h2>
|
||||
<p class="lead">不做又一个在线生图站点。它活在你的桌面上,把生图、修图、批量、图库和插件放在同一张画布上。</p>
|
||||
<div class="grid c3">
|
||||
<!--FEAT_CARDS-->
|
||||
</div>
|
||||
</div></section>
|
||||
|
||||
<section class="section"><div class="wrap">
|
||||
<h2>插件:本体不带,需要的自己装</h2>
|
||||
<p class="lead">应用本体不再内置插件。设置里打开市场,点「安装」,重启即可用;不需要的点一下就能关掉。</p>
|
||||
<div class="grid c3">
|
||||
<!--PLUGIN_CARDS-->
|
||||
</div>
|
||||
<div style="margin-top:22px"><a class="btn" href="/plugins/">查看全部 <!--PLUGIN_COUNT--> 个插件</a></div>
|
||||
</div></section>
|
||||
|
||||
<section class="section"><div class="wrap">
|
||||
<h2>下载 Image Workbench</h2>
|
||||
<p class="lead">选你的平台。装过一次之后,以后在应用内「设置 → 通用 → 版本与更新」就能一键升级。</p>
|
||||
<div class="dl"><!--DL_CARDS--></div>
|
||||
<div style="margin-top:20px;color:#9ca3af;font-size:12.5px">安装包未做 Apple 公证 / Windows 代码签名,首次打开需手动放行一次,细节见 <a href="/download/" style="text-decoration:underline">下载页</a>。</div>
|
||||
</div></section>
|
||||
</main>
|
||||
<!--FOOTER-->
|
||||
</body></html>
|
||||
<script>
|
||||
(function () {
|
||||
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
var targets = [].slice.call(document.querySelectorAll('.section h2, .section p.lead, .card, .pcard, .dl a'))
|
||||
targets.forEach(function (el) { el.classList.add('reveal') })
|
||||
if (!reduce && 'IntersectionObserver' in window) {
|
||||
var io = new IntersectionObserver(function (entries) {
|
||||
entries.forEach(function (e) {
|
||||
if (!e.isIntersecting) return
|
||||
var el = e.target
|
||||
var idx = targets.indexOf(el) % 4
|
||||
el.style.transitionDelay = (idx * 60) + 'ms'
|
||||
el.classList.add('in')
|
||||
io.unobserve(el)
|
||||
})
|
||||
}, { rootMargin: '0px 0px -8% 0px', threshold: 0.12 })
|
||||
targets.forEach(function (el) { io.observe(el) })
|
||||
} else { targets.forEach(function (el) { el.classList.add('in') }) }
|
||||
var art = document.querySelector('.art-frame')
|
||||
if (art && !reduce) {
|
||||
var raf = 0
|
||||
var onScroll = function () {
|
||||
if (raf) return
|
||||
raf = requestAnimationFrame(function () {
|
||||
raf = 0
|
||||
var y = Math.min(1, Math.max(0, window.scrollY / 700))
|
||||
art.style.transform = 'translate3d(0,' + (y * -14) + 'px,0)'
|
||||
})
|
||||
}
|
||||
window.addEventListener('scroll', onScroll, { passive: true }); onScroll()
|
||||
}
|
||||
})()
|
||||
</script>
|
||||
@@ -0,0 +1,45 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>插件市场 · Image Workbench</title>
|
||||
<link rel="stylesheet" href="/assets/style.css">
|
||||
</head><body>
|
||||
<!--NAV-->
|
||||
<main>
|
||||
<section class="hero" style="padding:64px 0 8px;text-align:left"><div class="wrap">
|
||||
<h1 style="font-size:40px;margin:0">插件市场</h1>
|
||||
<p class="sub" style="margin:14px 0 0;text-align:left;max-width:720px">共 <!--PLUGIN_COUNT--> 个插件。安装方式:应用内 <b>设置 → 插件 → 浏览</b>,点「安装」后重启生效。</p>
|
||||
</div></section>
|
||||
<section class="section" style="border-top:0;padding-top:24px"><div class="wrap">
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap;margin:0 0 18px" id="chips">
|
||||
<button class="tag on" data-tag="" style="cursor:pointer;background:#111;color:#fff;border-color:#111;padding:5px 12px">全部</button>
|
||||
<!--TAG_CHIPS-->
|
||||
</div>
|
||||
<input id="q" placeholder="搜索插件,例如:出图、抠图、矢量…" style="width:100%;max-width:420px;height:40px;padding:0 14px;border:1px solid var(--line);border-radius:10px;font-size:14px;outline:none;margin-bottom:22px">
|
||||
<div class="grid c3" id="list">
|
||||
<!--PLUGIN_CARDS-->
|
||||
</div>
|
||||
<div class="note" style="margin-top:26px">插件安装后会写进你的资料目录 <code>~/Documents/ImageWorkbench/plugins/</code>;卸载只删插件文件,不动画布与图库。</div>
|
||||
</div></section>
|
||||
</main>
|
||||
<!--FOOTER-->
|
||||
<script>
|
||||
var q = document.getElementById('q'), list = document.getElementById('list'), chips = document.getElementById('chips'), activeTag = ''
|
||||
function apply () {
|
||||
var kw = (q.value || '').trim().toLowerCase()
|
||||
Array.prototype.forEach.call(list.children, function (el) {
|
||||
var okKw = !kw || el.dataset.name.indexOf(kw) >= 0
|
||||
var okTag = !activeTag || (',' + el.dataset.tags + ',').indexOf(',' + activeTag + ',') >= 0
|
||||
var ok = okKw && okTag
|
||||
el.style.display = ok ? '' : 'none'
|
||||
})
|
||||
}
|
||||
q.addEventListener('input', apply)
|
||||
chips.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('button[data-tag]'); if (!b) return
|
||||
Array.prototype.forEach.call(chips.children, function (x) { x.style.background = ''; x.style.color = ''; x.style.borderColor = 'transparent' })
|
||||
b.style.background = '#111'; b.style.color = '#fff'; b.style.borderColor = '#111'
|
||||
activeTag = b.dataset.tag || ''
|
||||
apply()
|
||||
})
|
||||
</script>
|
||||
</body></html>
|
||||
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 382 KiB |
@@ -0,0 +1,141 @@
|
||||
:root{--fg:#111;--muted:#6b7280;--line:#ebebeb;--soft:#f7f7f8;--radius:16px}
|
||||
*{box-sizing:border-box}
|
||||
html,body{margin:0;padding:0}
|
||||
body{background:#fff;color:var(--fg);font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;-webkit-font-smoothing:antialiased}
|
||||
a{color:inherit;text-decoration:none}
|
||||
.wrap{max-width:1120px;margin:0 auto;padding:0 24px}
|
||||
nav{position:sticky;top:0;z-index:50;background:rgba(255,255,255,.82);backdrop-filter:saturate(1.6) blur(12px);border-bottom:1px solid var(--line)}
|
||||
nav .inner{display:flex;align-items:center;gap:26px;height:60px}
|
||||
nav .brand{display:flex;align-items:center;gap:9px;font-weight:650;letter-spacing:-.01em}
|
||||
nav .brand .dot{width:22px;height:22px;border-radius:6px;background:#111;color:#fff;display:inline-flex;align-items:center;justify-content:center;font-size:10px;font-weight:700}
|
||||
nav .links{display:flex;gap:20px;margin-left:8px;color:var(--muted);font-size:14px}
|
||||
nav .links a:hover{color:var(--fg)}
|
||||
nav .links a.on{color:var(--fg)}
|
||||
nav .right{margin-left:auto;display:flex;align-items:center;gap:10px}
|
||||
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;height:38px;padding:0 18px;border-radius:10px;border:1px solid var(--line);background:#fff;color:var(--fg);font-size:14px;font-weight:550;cursor:pointer;transition:.15s}
|
||||
.btn:hover{border-color:#d4d4d4;background:#fafafa}
|
||||
.btn.primary{background:#111;color:#fff;border-color:#111}
|
||||
.btn.primary:hover{background:#000}
|
||||
.btn.lg{height:44px;padding:0 22px;font-size:15px}
|
||||
.hero{padding:84px 0 20px;text-align:center}
|
||||
.kicker{display:inline-flex;align-items:center;gap:8px;padding:5px 12px;border:1px solid var(--line);border-radius:999px;color:var(--muted);font-size:12.5px}
|
||||
.hero h1{font-size:56px;line-height:1.08;letter-spacing:-.03em;margin:22px 0 0;font-weight:700}
|
||||
.hero p.sub{max-width:660px;margin:20px auto 0;color:var(--muted);font-size:17px;line-height:1.75}
|
||||
.hero .cta{display:flex;gap:12px;justify-content:center;margin-top:30px;flex-wrap:wrap}
|
||||
.hero .meta{margin-top:16px;color:#9ca3af;font-size:12.5px}
|
||||
.shot{margin:40px 0 0;padding:0 0 64px}
|
||||
.shot img{width:100%;display:block;border-radius:var(--radius);border:1px solid var(--line);box-shadow:0 30px 70px -30px rgba(15,23,42,.35)}
|
||||
.section{padding:72px 0;border-top:1px solid var(--line)}
|
||||
.section h2{font-size:30px;letter-spacing:-.02em;margin:0 0 8px;font-weight:680}
|
||||
.section p.lead{color:var(--muted);margin:0 0 34px;max-width:660px}
|
||||
.grid{display:grid;gap:16px}
|
||||
.grid.c3{grid-template-columns:repeat(3,1fr)}
|
||||
.grid.c2{grid-template-columns:repeat(2,1fr)}
|
||||
.card{border:1px solid var(--line);border-radius:var(--radius);padding:22px;background:#fff}
|
||||
.card h3{margin:0 0 6px;font-size:16px;font-weight:650}
|
||||
.card p{margin:0;color:var(--muted);font-size:13.5px;line-height:1.7}
|
||||
.card .ico{width:34px;height:34px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;margin-bottom:14px}
|
||||
.pcard{display:flex;flex-direction:column;gap:8px;border:1px solid var(--line);border-radius:14px;padding:18px;background:#fff}
|
||||
.pcard .head{display:flex;gap:10px;align-items:center}
|
||||
.pcard .av{width:34px;height:34px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:17px;flex:0 0 34px}
|
||||
.pcard .nm{font-weight:640;font-size:14.5px}
|
||||
.pcard .ver{color:var(--muted);font-size:12px;margin-top:1px}
|
||||
.pcard .desc{color:var(--muted);font-size:13px;line-height:1.65;flex:1 1 auto}
|
||||
.tags{display:flex;gap:6px;flex-wrap:wrap}
|
||||
.tag{padding:1px 8px;border-radius:999px;background:var(--soft);color:var(--muted);font-size:11.5px;border:1px solid transparent;font-family:inherit}
|
||||
.dl{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}
|
||||
.dl a{border:1px solid var(--line);border-radius:14px;padding:18px;display:flex;flex-direction:column;gap:4px;transition:.15s}
|
||||
.dl a:hover{border-color:#d4d4d4;background:#fafafa}
|
||||
.dl .n{font-weight:640}
|
||||
.dl .s{color:var(--muted);font-size:12.5px}
|
||||
.dl .none{border:1px solid var(--line);border-radius:14px;padding:18px;display:flex;flex-direction:column;gap:4px;opacity:.55}
|
||||
footer{background:#0b0b0c;color:#9ca3af;padding:52px 0 40px}
|
||||
footer .cols{display:grid;grid-template-columns:2fr 1fr 1fr 1fr;gap:24px}
|
||||
footer h4{color:#fff;font-size:13px;margin:0 0 10px;font-weight:600}
|
||||
footer a{display:block;color:#9ca3af;font-size:13px;margin:6px 0}
|
||||
footer a:hover{color:#fff}
|
||||
footer .copy{border-top:1px solid #1f1f22;margin-top:34px;padding-top:18px;font-size:12px;color:#6b7280;display:flex;justify-content:space-between;flex-wrap:wrap;gap:8px}
|
||||
.steps{margin:6px 0 0;padding-left:20px;color:var(--muted);font-size:13.5px;line-height:1.9}
|
||||
.steps b{color:var(--fg)}
|
||||
pre.cmd{margin:10px 0 0;padding:10px 12px;background:var(--soft);border:1px solid var(--line);border-radius:8px;overflow-x:auto}
|
||||
pre.cmd code{font-size:12.5px}
|
||||
.note{margin:10px 0 0;color:var(--muted);font-size:12.5px;line-height:1.8}
|
||||
@media(max-width:900px){.hero h1{font-size:38px}.grid.c3,.dl{grid-template-columns:1fr 1fr}footer .cols{grid-template-columns:1fr 1fr}}
|
||||
@media(max-width:600px){.grid.c3,.grid.c2,.dl{grid-template-columns:1fr}nav .links{display:none}}
|
||||
|
||||
/* ── 油画主视觉 + 特效 ───────────────────────────────── */
|
||||
.artwrap{position:relative;max-width:1120px;margin:26px auto 0;padding:0 24px 72px}
|
||||
.art-glow{position:absolute;inset:-40px 0 auto 0;height:520px;pointer-events:none;
|
||||
background:
|
||||
radial-gradient(46% 60% at 22% 40%, rgba(255,178,92,.28), transparent 70%),
|
||||
radial-gradient(40% 55% at 78% 30%, rgba(58,120,140,.22), transparent 70%),
|
||||
radial-gradient(60% 70% at 50% 0%, rgba(255,214,150,.35), transparent 72%);
|
||||
filter:blur(10px);opacity:.9;animation:glowPulse 12s ease-in-out infinite alternate}
|
||||
.art-frame{position:relative;border-radius:22px;overflow:hidden;border:1px solid var(--line);
|
||||
box-shadow:0 40px 90px -40px rgba(15,23,42,.45)}
|
||||
.art-frame .art{display:block;width:100%;height:auto;transform:scale(1.02);animation:kenburns 28s ease-in-out infinite alternate}
|
||||
.art-frame .grain{position:absolute;inset:0;pointer-events:none;opacity:.14;mix-blend-mode:multiply;
|
||||
background-image:url("data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.55'/%3E%3C/svg%3E")}
|
||||
.art-frame:after{content:"";position:absolute;inset:0;pointer-events:none;border-radius:22px;box-shadow:inset 0 0 120px rgba(120,80,30,.16)}
|
||||
@keyframes kenburns{from{transform:scale(1.02) translate3d(0,0,0)}to{transform:scale(1.08) translate3d(-1.2%,-1%,0)}}
|
||||
@keyframes glowPulse{from{opacity:.72;transform:translateY(0)}to{opacity:1;transform:translateY(-10px)}}
|
||||
@keyframes rise{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
|
||||
.hero h1,.hero p.sub,.hero .cta,.hero .meta,.hero .kicker{animation:rise .7s cubic-bezier(.22,.61,.36,1) both}
|
||||
.hero h1{animation-delay:.04s}.hero p.sub{animation-delay:.1s}.hero .cta{animation-delay:.16s}.hero .meta{animation-delay:.22s}
|
||||
.artwrap{animation:rise .9s cubic-bezier(.22,.61,.36,1) .18s both}
|
||||
.card,.pcard,.dl a{transition:transform .18s ease, box-shadow .18s ease, border-color .18s ease}
|
||||
.card:hover,.pcard:hover{transform:translateY(-3px);box-shadow:0 16px 40px -24px rgba(15,23,42,.38);border-color:#dcdcdc}
|
||||
.dl a:hover{transform:translateY(-2px);box-shadow:0 16px 40px -24px rgba(15,23,42,.35)}
|
||||
.section h2:after{content:"";display:block;width:36px;height:3px;border-radius:2px;margin-top:12px;background:linear-gradient(90deg,#e8a735,#3a788c)}
|
||||
@media (prefers-reduced-motion:reduce){
|
||||
.hero h1,.hero p.sub,.hero .cta,.hero .meta,.hero .kicker,.artwrap,.art-frame .art,.art-glow{animation:none!important}
|
||||
.card:hover,.pcard:hover,.dl a:hover{transform:none}
|
||||
}
|
||||
|
||||
/* 主视觉改为宽幅裁切:突出画面中段的油彩笔触 */
|
||||
.art-frame{aspect-ratio:auto}
|
||||
.art-frame .art{width:100%;height:clamp(300px,40vw,540px);object-fit:cover;object-position:50% 62%}
|
||||
.art-frame:before{content:"";position:absolute;left:0;right:0;bottom:0;height:38%;pointer-events:none;z-index:2;
|
||||
background:linear-gradient(to top, rgba(255,255,255,.92), rgba(255,255,255,.35) 45%, transparent)}
|
||||
|
||||
/* ── 滚动入场 + 视差 ───────────────────────────────── */
|
||||
.reveal{opacity:0;transform:translateY(18px);transition:opacity .7s cubic-bezier(.22,.61,.36,1),transform .7s cubic-bezier(.22,.61,.36,1)}
|
||||
.reveal.in{opacity:1;transform:none}
|
||||
.section h2.reveal.in:after{animation:barIn .7s ease both}
|
||||
@keyframes barIn{from{width:0}to{width:36px}}
|
||||
.art-frame{will-change:transform}
|
||||
@media (prefers-reduced-motion:reduce){.reveal{opacity:1;transform:none;transition:none}}
|
||||
|
||||
/* 首屏露出更多油彩:裁切位置上移 + 收紧 hero 间距 */
|
||||
.hero{padding:64px 0 8px}
|
||||
.art-frame .art{object-position:50% 34%}
|
||||
.artwrap{margin-top:14px}
|
||||
|
||||
/* ── 首屏:油画做背景(白纱压一层,保证文字可读) ─────────── */
|
||||
.hero-art{position:relative;padding:76px 0 96px;overflow:hidden}
|
||||
.hero-bg{position:absolute;inset:0;z-index:0;overflow:hidden}
|
||||
.hero-bg img{width:100%;height:100%;object-fit:cover;object-position:50% 58%;transform:scale(1.06);animation:kenburns 30s ease-in-out infinite alternate;filter:saturate(1.05)}
|
||||
.hero-veil{position:absolute;inset:0;z-index:1;
|
||||
background:
|
||||
radial-gradient(70% 60% at 50% 38%, rgba(255,255,255,.92) 0%, rgba(255,255,255,.72) 42%, rgba(255,255,255,.1) 100%),
|
||||
linear-gradient(180deg, rgba(255,255,255,.92) 0%, rgba(255,255,255,.55) 46%, rgba(255,255,255,.28) 72%, #fff 100%)}
|
||||
.hero-art .wrap{position:relative;z-index:2}
|
||||
.art-strip{position:relative;height:150px;overflow:hidden;border-top:1px solid var(--line);border-bottom:1px solid var(--line);
|
||||
background:url('/assets/painting.jpg') center 62%/cover no-repeat}
|
||||
.art-strip:after{content:"";position:absolute;inset:0;background:linear-gradient(180deg,rgba(255,255,255,.85),rgba(255,255,255,.15) 40%,rgba(255,255,255,.85))}
|
||||
.art-strip .grain{position:absolute;inset:0;opacity:.12;mix-blend-mode:multiply;
|
||||
background-image:url("data:image/svg+xml;utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.55'/%3E%3C/svg%3E")}
|
||||
|
||||
/* 可读性微调:背景轻微模糊 + 更强的白纱,meta 加深 */
|
||||
.hero-bg img{filter:blur(1.5px) saturate(1.05)}
|
||||
.hero-veil{background:
|
||||
radial-gradient(62% 58% at 50% 40%, rgba(255,255,255,.96) 0%, rgba(255,255,255,.86) 46%, rgba(255,255,255,.32) 100%),
|
||||
linear-gradient(180deg, rgba(255,255,255,.94) 0%, rgba(255,255,255,.66) 50%, rgba(255,255,255,.35) 76%, #fff 100%)}
|
||||
.hero .meta{color:#6b7280}
|
||||
.hero-art{padding:72px 0 84px}
|
||||
|
||||
/* 头图白纱减淡:让油画色彩多透出来一点(文字仍保持可读) */
|
||||
.hero-bg img{filter:blur(1px) saturate(1.06)}
|
||||
.hero-veil{background:
|
||||
radial-gradient(62% 58% at 50% 40%, rgba(255,255,255,.86) 0%, rgba(255,255,255,.70) 46%, rgba(255,255,255,.16) 100%),
|
||||
linear-gradient(180deg, rgba(255,255,255,.84) 0%, rgba(255,255,255,.52) 50%, rgba(255,255,255,.20) 76%, #fff 100%)}
|
||||
@@ -0,0 +1,238 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Image Workbench · 下载</title>
|
||||
<link rel="stylesheet" href="/assets/style.css?v=" + encodeURIComponent(latest.version + '-' + Date.now().toString(36)) + "">
|
||||
<style>
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
|
||||
.dlwrap{max-width:760px;margin:0 auto;padding:48px 0 64px}
|
||||
h1{font-size:27px;margin:0 0 6px;letter-spacing:-.01em}
|
||||
.sub{color:var(--muted);margin:0 0 34px}
|
||||
h2{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);font-weight:600;margin:38px 0 2px}
|
||||
.row{display:flex;align-items:center;gap:16px;padding:15px 0;border-bottom:1px solid var(--line)}
|
||||
.row:first-of-type{border-top:1px solid var(--line)}
|
||||
.name{flex:1 1 auto;font-weight:550}
|
||||
.hint{color:var(--muted);font-size:12.5px;font-weight:400;margin-top:2px}
|
||||
.meta{flex:0 0 auto;text-align:right;color:var(--muted);font-size:13px}
|
||||
.hash{font-size:11.5px;opacity:.75;margin-top:2px;font-variant-numeric:tabular-nums}
|
||||
.btn{flex:0 0 auto;font-size:13px;padding:7px 18px;border-radius:8px;background:var(--brand);color:var(--bg);text-decoration:none}
|
||||
.btn:hover{opacity:.88}
|
||||
.muted{flex:0 0 auto;font-size:13px;color:var(--muted);opacity:.7}
|
||||
.foot{margin-top:46px;color:var(--muted);font-size:12.5px;line-height:1.8}
|
||||
.foot a{color:inherit}
|
||||
code{font-size:12.5px}
|
||||
.steps{margin:6px 0 0;padding-left:22px;color:var(--fg2);font-size:13.5px;line-height:1.9}
|
||||
.steps li{margin:2px 0}
|
||||
.steps b{color:var(--fg);font-weight:600}
|
||||
pre.cmd{margin:10px 0 0;padding:10px 12px;background:var(--bg2);border:1px solid var(--line);border-radius:8px;overflow-x:auto}
|
||||
pre.cmd code{font-size:12px;color:var(--fg)}
|
||||
.note{margin:10px 0 0;color:var(--muted);font-size:12.5px;line-height:1.8}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<nav><div class="wrap inner">
|
||||
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
|
||||
<div class="links">
|
||||
<a href="/">首页</a>
|
||||
<a href="/download/" class="on">下载</a>
|
||||
<a href="/plugins/">插件</a>
|
||||
<a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>
|
||||
</div>
|
||||
<div class="right">
|
||||
<a class="btn" href="/plugins/">插件市场</a>
|
||||
<a class="btn primary" href="/download/">下载</a>
|
||||
</div>
|
||||
</div></nav>
|
||||
|
||||
<div class="wrap"><div class="dlwrap">
|
||||
<h1>Image Workbench</h1>
|
||||
<p class="sub">本地优先的 AI 生图无限画布 · 桌面版(Tauri v2)</p>
|
||||
|
||||
<h2>下载</h2>
|
||||
<div class="row">
|
||||
<div class="name">macOS · Apple Silicon<div class="hint">M1 / M2 / M3 / M4</div></div>
|
||||
<div class="meta">版本 3.25.29 · 8.3 MB · .dmg<div class="hash">sha256 76e0815010e52248…</div></div>
|
||||
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.25.29_aarch64.dmg?h=76e0815010e5">下载</a>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">macOS · Intel<div class="hint">x86_64</div></div>
|
||||
<div class="meta"></div>
|
||||
<span class="muted">暂未提供</span>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">Windows · x64<div class="hint">需要 WebView2</div></div>
|
||||
<div class="meta"></div>
|
||||
<span class="muted">暂未提供</span>
|
||||
</div>
|
||||
|
||||
<h2>系统要求</h2>
|
||||
<div class="row">
|
||||
<div class="name">macOS 12 及以上 / Windows 10 1803 及以上(含 WebView2)
|
||||
<div class="hint">数据全部保存在本地目录 <code>~/Documents/ImageWorkbench</code>,可整目录备份与迁移。</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>安装步骤(macOS)</h2>
|
||||
<ol class="steps">
|
||||
<li>下载上面的 <b>.dmg</b>(Apple 芯片选 Apple Silicon;老 Intel 机器选 Intel)。</li>
|
||||
<li>双击打开 dmg,把 <b>Image Workbench</b> 图标拖进「应用程序」文件夹。</li>
|
||||
<li>第一次启动:打开「应用程序」,<b>右键点图标 → 打开</b>,弹窗里再点一次「打开」。</li>
|
||||
<li>如果提示「已损坏」或「无法验证开发者」:打开「终端」,粘贴执行下面这条命令,然后重新打开应用。</li>
|
||||
</ol>
|
||||
<pre class="cmd"><code>xattr -dr com.apple.quarantine "/Applications/image-workbench.app"</code></pre>
|
||||
<p class="note">说明:安装包未做 Apple 公证($99/年开发者账号),所以第一次需要手动放行;这一步只做一次。<br>
|
||||
之后有新版本时,应用内 <b>设置 → 通用 → 版本与更新 → 检查更新</b> 就能一键升级,不用再下载安装包。</p>
|
||||
|
||||
<h2>安装步骤(Windows)</h2>
|
||||
<ol class="steps">
|
||||
<li>下载 <b>.exe</b>(NSIS 安装包,按当前用户安装,不需要管理员权限)。</li>
|
||||
<li>双击运行;若出现「Windows 已保护你的电脑」,点「更多信息 → 仍要运行」。</li>
|
||||
<li>安装完成后从开始菜单启动;数据在 <code>%USERPROFILE%DocumentsImageWorkbench</code>。</li>
|
||||
</ol>
|
||||
|
||||
<h2>历史版本</h2>
|
||||
<div class="row">
|
||||
<div class="name">3.25.29<div class="hint">修画布网页压住地址栏(原生层与 DOM 的坐标原点差 32px)、内容跟随画布缩放;工具栏重做为可输入百分比的缩放设定框</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.28<div class="hint">恢复画布内网页节点并修好「一动就白」:取消动就藏与尺寸门槛,位置尺寸一次 set_bounds 推送</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.27<div class="hint">下线画布内网页节点:原生子 webview 在画布上修不干净,撤掉该功能;独立窗口浏览器不受影响</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.26<div class="hint">修第二个网页节点报「主窗口不存在」:get_webview_window 在有了子 webview 之后永久失效,改用 get_window</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.25<div class="hint">修画布内网页节点:子 webview 的 hide/show 静默失效导致一动画布网页就永久消失,改用移出窗口隐藏</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.24<div class="hint">画布内网页节点:网页长在画布上(原生子 webview),可拖动缩放、和参考图并排对照;browser 插件 1.1.1</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.23<div class="hint">应用内浏览器:独立窗口打开网页(插件 browser 1.0.0 上架市场),并修复浏览器窗口关不掉</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.22<div class="hint">Intel 版:外观自定义扩展</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.21<div class="hint">Intel 版:下载命名 + 面板穿透修复</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.20<div class="hint">Intel 版:导出目录三态 + 取色器修复</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.19<div class="hint">Windows:工单#3 六项 + 图库下拉紧凑化</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.18<div class="hint">Intel 版:工单#3 六项</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.17<div class="hint">Intel 版:图标细节修正</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.16<div class="hint">Intel 版:新图标</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.15<div class="hint">Windows:桌面客户端版(网页部署面移除 + 独立更新清单)</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.14<div class="hint">Intel 版:CSP 修复 + 外观 tab</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.13<div class="hint">Windows:图片目录自愈 + 启动补齐工作目录(修丢图)</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.12<div class="hint">Intel 版:图片目录自愈 + 不回退 Cache</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.11<div class="hint">Windows:单实例 + 外链系统浏览器 + 原生通知 + 窗口下限 + 仅 nsis 产物</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.10<div class="hint">Intel 版:图片持久化修复</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.9<div class="hint">Windows:图片登记立即落盘 + 清理前报数</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.8<div class="hint">Intel 版:同图导入与图片清理修复</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.7<div class="hint">Windows:剪贴板 PNG 传输 + 路径文本转图片 + 大图不卡</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.6<div class="hint">Intel 版:粘贴语义修正</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.5<div class="hint">Intel 版:库面板粘贴修复</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.4<div class="hint">Intel 版:剪贴板兜底</div></div>
|
||||
<div class="meta">2026-11-18<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.3<div class="hint">Windows:剪贴板修复(Cmd+C/V、粘贴图片/文本、复制图片)+ 可自动更新</div></div>
|
||||
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.2<div class="hint">Windows:无内置插件 + 市场安装 + 页内确认 + 在线更新(首次需手动安装)</div></div>
|
||||
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon / macOS · Intel / Windows · x64</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.1<div class="hint">Intel Mac 版:性能与数据卫生(图库清单去 base64、缩略图落盘、回收 20.2MB)</div></div>
|
||||
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon / macOS · Intel</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.25.0<div class="hint">应用不再内置插件(全部从市场安装);页内确认替代原生 confirm;插件市场与开发者模式</div></div>
|
||||
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.24.85<div class="hint">每张画布单独成文件、资源库分类、设置面板重构、下载改为按需落盘</div></div>
|
||||
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
|
||||
<div class="foot">
|
||||
本页由 <code>scripts/gen-release-page.js</code> 从 releases.json 生成 · 源码 <a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop">git.maqiart.eu.org</a> · 更新于 2026-11-18
|
||||
</div>
|
||||
</div></div>
|
||||
|
||||
<footer><div class="wrap">
|
||||
<div class="cols">
|
||||
<div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>
|
||||
<div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>
|
||||
<div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>
|
||||
<div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>
|
||||
<div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>
|
||||
</div>
|
||||
<div class="copy"><span>© Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>
|
||||
</div></footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,74 +1,145 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Image Workbench · 下载</title>
|
||||
<style>
|
||||
:root{--bg:#fafaf9;--fg:#1c1917;--muted:#78716c;--line:#e7e5e4;--card:#fff;--brand:#1c1917}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#17161a;--fg:#f5f5f4;--muted:#a8a29e;--line:#2f2d33;--card:#1f1e23;--brand:#f5f5f4}}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
|
||||
.wrap{max-width:760px;margin:0 auto;padding:56px 22px 72px}
|
||||
h1{font-size:27px;margin:0 0 6px;letter-spacing:-.01em}
|
||||
.sub{color:var(--muted);margin:0 0 34px}
|
||||
h2{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);font-weight:600;margin:38px 0 2px}
|
||||
.row{display:flex;align-items:center;gap:16px;padding:15px 0;border-bottom:1px solid var(--line)}
|
||||
.row:first-of-type{border-top:1px solid var(--line)}
|
||||
.name{flex:1 1 auto;font-weight:550}
|
||||
.hint{color:var(--muted);font-size:12.5px;font-weight:400;margin-top:2px}
|
||||
.meta{flex:0 0 auto;text-align:right;color:var(--muted);font-size:13px}
|
||||
.hash{font-size:11.5px;opacity:.75;margin-top:2px;font-variant-numeric:tabular-nums}
|
||||
.btn{flex:0 0 auto;font-size:13px;padding:7px 18px;border-radius:8px;background:var(--brand);color:var(--bg);text-decoration:none}
|
||||
.btn:hover{opacity:.88}
|
||||
.muted{flex:0 0 auto;font-size:13px;color:var(--muted);opacity:.7}
|
||||
.foot{margin-top:46px;color:var(--muted);font-size:12.5px;line-height:1.8}
|
||||
.foot a{color:inherit}
|
||||
code{font-size:12.5px}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<h1>Image Workbench</h1>
|
||||
<p class="sub">本地优先的 AI 生图无限画布 · 桌面版(Tauri v2)</p>
|
||||
|
||||
<h2>下载</h2>
|
||||
<div class="row">
|
||||
<div class="name">macOS · Apple Silicon<div class="hint">M1 / M2 / M3 / M4</div></div>
|
||||
<div class="meta">版本 3.25.0 · 6.2 MB · .dmg<div class="hash">sha256 60d88875b86a4673…</div></div>
|
||||
<a class="btn" href="/updates/darwin-aarch64/image-workbench_3.25.0_aarch64.dmg">下载</a>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">macOS · Intel<div class="hint">x86_64</div></div>
|
||||
<div class="meta"></div>
|
||||
<span class="muted">暂未提供</span>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">Windows · x64<div class="hint">需要 WebView2</div></div>
|
||||
<div class="meta"></div>
|
||||
<span class="muted">暂未提供</span>
|
||||
</div>
|
||||
|
||||
<h2>系统要求</h2>
|
||||
<div class="row">
|
||||
<div class="name">macOS 12 及以上 / Windows 10 1803 及以上(含 WebView2)
|
||||
<div class="hint">数据全部保存在本地目录 <code>~/Documents/ImageWorkbench</code>,可整目录备份与迁移。</div>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Image Workbench · 本地优先的 AI 生图工作台</title>
|
||||
<meta name="description" content="本地优先的 AI 生图无限画布:节点式工作流、插件按需安装、数据全部留在本机。">
|
||||
<link rel="stylesheet" href="/assets/style.css?v=3.25.29-mwmqrups">
|
||||
</head><body>
|
||||
<nav><div class="wrap inner">
|
||||
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
|
||||
<div class="links">
|
||||
<a href="/" class="on">首页</a>
|
||||
<a href="/download/">下载</a>
|
||||
<a href="/plugins/">插件</a>
|
||||
<a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>
|
||||
</div>
|
||||
<div class="right">
|
||||
<a class="btn" href="/plugins/">插件市场</a>
|
||||
<a class="btn primary" href="/download/">下载 v3.25.29</a>
|
||||
</div>
|
||||
</div></nav>
|
||||
<main>
|
||||
<section class="hero hero-art">
|
||||
<div class="hero-bg"><img src="/assets/painting.jpg?v=3.25.29-mwmqrups" alt=""></div>
|
||||
<div class="hero-veil"></div>
|
||||
<div class="wrap">
|
||||
<span class="kicker">v3.25.29 · macOS / Windows · 数据在本地</span>
|
||||
<h1>本地优先的<br>AI 生图无限画布</h1>
|
||||
<p class="sub">用节点把「参考图 → 提示词 → 批量生成 → 图库」串成一条生产线。<br>图片、提示词、模型配置全部留在你自己的电脑里,插件按需安装。</p>
|
||||
<div class="cta">
|
||||
<a class="btn primary lg" href="/download/">下载 v3.25.29</a>
|
||||
<a class="btn lg" href="/plugins/">浏览 8 个插件</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="meta">支持 macOS 12+ 与 Windows 10 1803+ · 安装包约 7 MB · 无需登录</div>
|
||||
</div></section>
|
||||
|
||||
<h2>历史版本</h2>
|
||||
<div class="row">
|
||||
<div class="name">3.25.0<div class="hint">应用不再内置插件(全部从市场安装);页内确认替代原生 confirm;插件市场与开发者模式</div></div>
|
||||
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="name">3.24.85<div class="hint">每张画布单独成文件、资源库分类、设置面板重构、下载改为按需落盘</div></div>
|
||||
<div class="meta">2026-11-17<div class="hint">macOS · Apple Silicon</div></div>
|
||||
</div>
|
||||
|
||||
<div class="foot">
|
||||
本页由 <code>scripts/gen-release-page.js</code> 从 releases.json 生成 · 源码 <a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop">git.maqiart.eu.org</a> · 更新于 2026-11-17
|
||||
<section class="section"><div class="wrap">
|
||||
<h2>为「一个人跑完整条产线」而做</h2>
|
||||
<p class="lead">不做又一个在线生图站点。它活在你的桌面上,把生图、修图、批量、图库和插件放在同一张画布上。</p>
|
||||
<div class="grid c3">
|
||||
<div class="card"><div class="ico" style="background:#eef2ff">💻</div>
|
||||
<h3>本地优先</h3><p>图片与数据保存在 ~/Documents/ImageWorkbench,不经服务器中转;可整目录备份、迁移到新电脑。</p></div>
|
||||
<div class="card"><div class="ico" style="background:#fff7ed">🕸️</div>
|
||||
<h3>节点式无限画布</h3><p>参考图 → 提示词 → 生成 → 图库,用连线把工作流串起来;一张画布容纳整条生产线。</p></div>
|
||||
<div class="card"><div class="ico" style="background:#ecfdf5">🧩</div>
|
||||
<h3>插件按需安装</h3><p>应用本体不含插件,需要什么装什么;可随时启停,关闭后入口自动隐藏。</p></div>
|
||||
</div>
|
||||
</div></section>
|
||||
|
||||
<section class="section"><div class="wrap">
|
||||
<h2>插件:本体不带,需要的自己装</h2>
|
||||
<p class="lead">应用本体不再内置插件。设置里打开市场,点「安装」,重启即可用;不需要的点一下就能关掉。</p>
|
||||
<div class="grid c3">
|
||||
<div class="pcard" data-name="批量出图 batch-export 资源中心勾选节点,串行批量生成并打包 zip 下载 出图 批处理" data-tags="出图,批处理">
|
||||
<div class="head"><span class="av" style="background:#e8f0fe">🗂️</span>
|
||||
<div><div class="nm">批量出图</div><div class="ver">v1.2.0 · 官方</div></div></div>
|
||||
<div class="desc">资源中心勾选节点,串行批量生成并打包 ZIP 下载</div>
|
||||
<div class="tags"><span class="tag">出图</span><span class="tag">批处理</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="空白画布 blank-canvas 新建空白画布节点,用于分区分组 画布 效率" data-tags="画布,效率">
|
||||
<div class="head"><span class="av" style="background:#eef2f6">⬜</span>
|
||||
<div><div class="nm">空白画布</div><div class="ver">v1.0.0 · 官方</div></div></div>
|
||||
<div class="desc">新建空白画布节点,用于分区分组</div>
|
||||
<div class="tags"><span class="tag">画布</span><span class="tag">效率</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="应用内浏览器 browser 独立窗口打开网页,或在画布节点里内嵌网页(跟随画布缩放,可调内容缩放) 浏览器 效率" data-tags="浏览器,效率">
|
||||
<div class="head"><span class="av" style="background:#eaf1fb">🌐</span>
|
||||
<div><div class="nm">应用内浏览器</div><div class="ver">v1.4.0 · 官方</div></div></div>
|
||||
<div class="desc">独立窗口打开网页,或在画布节点里内嵌网页(跟随画布缩放,可调内容缩放)</div>
|
||||
<div class="tags"><span class="tag">浏览器</span><span class="tag">效率</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="标注 / 修图 image-annotate 在画布内标注、涂抹、局部重绘 修图 标注" data-tags="修图,标注">
|
||||
<div class="head"><span class="av" style="background:#fdeaea">🖌️</span>
|
||||
<div><div class="nm">标注 / 修图</div><div class="ver">v1.20.6 · 官方</div></div></div>
|
||||
<div class="desc">在画布内标注、涂抹、局部重绘</div>
|
||||
<div class="tags"><span class="tag">修图</span><span class="tag">标注</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="位图转矢量 image-vectorize 把位图转成 svg 矢量路径 转换 矢量" data-tags="转换,矢量">
|
||||
<div class="head"><span class="av" style="background:#eaf3ea">✒️</span>
|
||||
<div><div class="nm">位图转矢量</div><div class="ver">v0.4.2 · 官方</div></div></div>
|
||||
<div class="desc">把位图转成 SVG 矢量路径</div>
|
||||
<div class="tags"><span class="tag">转换</span><span class="tag">矢量</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="风格库 style-source 风格提示词库与一键套用 提示词 风格" data-tags="提示词,风格">
|
||||
<div class="head"><span class="av" style="background:#fdf0e6">🎨</span>
|
||||
<div><div class="nm">风格库</div><div class="ver">v1.3.2 · 官方</div></div></div>
|
||||
<div class="desc">风格提示词库与一键套用</div>
|
||||
<div class="tags"><span class="tag">提示词</span><span class="tag">风格</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-top:22px"><a class="btn" href="/plugins/">查看全部 8 个插件</a></div>
|
||||
</div></section>
|
||||
|
||||
<section class="section"><div class="wrap">
|
||||
<h2>下载 Image Workbench</h2>
|
||||
<p class="lead">选你的平台。装过一次之后,以后在应用内「设置 → 通用 → 版本与更新」就能一键升级。</p>
|
||||
<div class="dl"><a href="/updates/darwin-aarch64/image-workbench_3.25.29_aarch64.dmg?h=76e0815010e5"><div class="n">macOS · Apple Silicon</div><div class="s">M1 / M2 / M3 / M4 · 8.3 MB · .dmg</div></a>
|
||||
<div class="none"><div class="n">macOS · Intel</div><div class="s">暂未提供</div></div>
|
||||
<div class="none"><div class="n">Windows · x64</div><div class="s">暂未提供</div></div></div>
|
||||
<div style="margin-top:20px;color:#9ca3af;font-size:12.5px">安装包未做 Apple 公证 / Windows 代码签名,首次打开需手动放行一次,细节见 <a href="/download/" style="text-decoration:underline">下载页</a>。</div>
|
||||
</div></section>
|
||||
</main>
|
||||
<footer><div class="wrap">
|
||||
<div class="cols">
|
||||
<div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>
|
||||
<div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>
|
||||
<div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>
|
||||
<div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>
|
||||
<div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
<div class="copy"><span>© 2026 Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>
|
||||
</div></footer>
|
||||
</body></html>
|
||||
<script>
|
||||
(function () {
|
||||
var reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
var targets = [].slice.call(document.querySelectorAll('.section h2, .section p.lead, .card, .pcard, .dl a'))
|
||||
targets.forEach(function (el) { el.classList.add('reveal') })
|
||||
if (!reduce && 'IntersectionObserver' in window) {
|
||||
var io = new IntersectionObserver(function (entries) {
|
||||
entries.forEach(function (e) {
|
||||
if (!e.isIntersecting) return
|
||||
var el = e.target
|
||||
var idx = targets.indexOf(el) % 4
|
||||
el.style.transitionDelay = (idx * 60) + 'ms'
|
||||
el.classList.add('in')
|
||||
io.unobserve(el)
|
||||
})
|
||||
}, { rootMargin: '0px 0px -8% 0px', threshold: 0.12 })
|
||||
targets.forEach(function (el) { io.observe(el) })
|
||||
} else { targets.forEach(function (el) { el.classList.add('in') }) }
|
||||
var art = document.querySelector('.art-frame')
|
||||
if (art && !reduce) {
|
||||
var raf = 0
|
||||
var onScroll = function () {
|
||||
if (raf) return
|
||||
raf = requestAnimationFrame(function () {
|
||||
raf = 0
|
||||
var y = Math.min(1, Math.max(0, window.scrollY / 700))
|
||||
art.style.transform = 'translate3d(0,' + (y * -14) + 'px,0)'
|
||||
})
|
||||
}
|
||||
window.addEventListener('scroll', onScroll, { passive: true }); onScroll()
|
||||
}
|
||||
})()
|
||||
</script>
|
||||
@@ -0,0 +1,150 @@
|
||||
{
|
||||
"version": 1,
|
||||
"updatedAt": "2026-11-18T23:14:16.914Z",
|
||||
"plugins": [
|
||||
{
|
||||
"id": "batch-export",
|
||||
"name": "批量出图",
|
||||
"desc": "资源中心勾选节点,串行批量生成并打包 ZIP 下载",
|
||||
"author": "official",
|
||||
"icon": "🗂️",
|
||||
"color": "#e8f0fe",
|
||||
"tags": [
|
||||
"出图",
|
||||
"批处理"
|
||||
],
|
||||
"version": "1.2.0",
|
||||
"apiVersion": 1,
|
||||
"file": "plugins/plugin-batch-export.b7d13ba66cf9.js",
|
||||
"size": 44329,
|
||||
"sha256": "b7d13ba66cf97ff65e94305328183a1a3b5a45b0393f3a63f77f6b7b46795389",
|
||||
"integrity": "sha256-t9E7pmz5f/ZelDBTKBg6GjtaRbA5Pzpj939re0Z5U4k="
|
||||
},
|
||||
{
|
||||
"id": "blank-canvas",
|
||||
"name": "空白画布",
|
||||
"desc": "新建空白画布节点,用于分区分组",
|
||||
"author": "official",
|
||||
"icon": "⬜",
|
||||
"color": "#eef2f6",
|
||||
"tags": [
|
||||
"画布",
|
||||
"效率"
|
||||
],
|
||||
"version": "1.0.0",
|
||||
"apiVersion": 1,
|
||||
"file": "plugins/plugin-blank-canvas.67763893fa99.js",
|
||||
"size": 6094,
|
||||
"sha256": "67763893fa99c8fe1d8bcf640426f5bbc576abd35bcdc84c910b7b08f79964f9",
|
||||
"integrity": "sha256-Z3Y4k/qZyP4di89kBCb1u8V2q9NbzchMkQt7CPeZZPk="
|
||||
},
|
||||
{
|
||||
"id": "browser",
|
||||
"name": "应用内浏览器",
|
||||
"desc": "独立窗口打开网页,或在画布节点里内嵌网页(跟随画布缩放,可调内容缩放)",
|
||||
"author": "official",
|
||||
"icon": "🌐",
|
||||
"color": "#eaf1fb",
|
||||
"tags": [
|
||||
"浏览器",
|
||||
"效率"
|
||||
],
|
||||
"version": "1.4.0",
|
||||
"apiVersion": 1,
|
||||
"file": "plugins/plugin-browser.9e43059c8eaf.js",
|
||||
"size": 32526,
|
||||
"sha256": "9e43059c8eaf1a7e54794a072b224e6e2fff8927c04ac703ecce635db03479b4",
|
||||
"integrity": "sha256-nkMFnI6vGn5UeUoHKyJObi//iSfASscD7M5jXbA0ebQ="
|
||||
},
|
||||
{
|
||||
"id": "image-annotate",
|
||||
"name": "标注 / 修图",
|
||||
"desc": "在画布内标注、涂抹、局部重绘",
|
||||
"author": "official",
|
||||
"icon": "🖌️",
|
||||
"color": "#fdeaea",
|
||||
"tags": [
|
||||
"修图",
|
||||
"标注"
|
||||
],
|
||||
"version": "1.20.6",
|
||||
"apiVersion": 1,
|
||||
"file": "plugins/plugin-image-annotate.7a865c7c353c.js",
|
||||
"size": 461523,
|
||||
"sha256": "7a865c7c353c3fbcaac551a8aeb5acd1bf624ca25f104db96fce493c3084b24f",
|
||||
"integrity": "sha256-eoZcfDU8P7yqxVGorrWs0b9iTKJfEE25b85JPDCEsk8="
|
||||
},
|
||||
{
|
||||
"id": "image-vectorize",
|
||||
"name": "位图转矢量",
|
||||
"desc": "把位图转成 SVG 矢量路径",
|
||||
"author": "official",
|
||||
"icon": "✒️",
|
||||
"color": "#eaf3ea",
|
||||
"tags": [
|
||||
"转换",
|
||||
"矢量"
|
||||
],
|
||||
"version": "0.4.2",
|
||||
"apiVersion": 1,
|
||||
"file": "plugins/plugin-image-vectorize.03b5fc850c34.js",
|
||||
"size": 144780,
|
||||
"sha256": "03b5fc850c34ddc0996bafc367798fb60aecc9bb23b92990dd5ccc59ed74bfc9",
|
||||
"integrity": "sha256-A7X8hQw03cCZa6/DZ3mPtgrsybsjuSmQ3VzMWe10v8k="
|
||||
},
|
||||
{
|
||||
"id": "style-source",
|
||||
"name": "风格库",
|
||||
"desc": "风格提示词库与一键套用",
|
||||
"author": "official",
|
||||
"icon": "🎨",
|
||||
"color": "#fdf0e6",
|
||||
"tags": [
|
||||
"提示词",
|
||||
"风格"
|
||||
],
|
||||
"version": "1.3.2",
|
||||
"apiVersion": 1,
|
||||
"file": "plugins/plugin-style-source.ee7168565a44.js",
|
||||
"size": 69925,
|
||||
"sha256": "ee7168565a44d49daaf300f62d5c7a106e60fba29a9e4888ff8bfd9abd2e3178",
|
||||
"integrity": "sha256-7nFoVlpE1J2q8wD2LVx6EG5g+6KankiI/4v9mr0uMXg="
|
||||
},
|
||||
{
|
||||
"id": "white-bg-800",
|
||||
"name": "白底图",
|
||||
"desc": "批量生成电商白底图(800px)",
|
||||
"author": "official",
|
||||
"icon": "🧾",
|
||||
"color": "#eef7fb",
|
||||
"tags": [
|
||||
"电商",
|
||||
"出图"
|
||||
],
|
||||
"version": "1.2.1",
|
||||
"apiVersion": 1,
|
||||
"file": "plugins/plugin-white-bg-800.a5a92f045c0d.js",
|
||||
"size": 14957,
|
||||
"sha256": "a5a92f045c0d4046b205562019b2a6354afd14aa92375b78559d48f2ce9b74ee",
|
||||
"integrity": "sha256-pakvBFwNQEayBVYgGbKmNUr9FKqSN1t4VZ1I8s6bdO4="
|
||||
},
|
||||
{
|
||||
"id": "xianyi-cutout",
|
||||
"name": "鲜艺抠图",
|
||||
"desc": "接入鲜艺抠图模型的一键去背景",
|
||||
"author": "official",
|
||||
"icon": "✂️",
|
||||
"color": "#f3eafd",
|
||||
"tags": [
|
||||
"抠图",
|
||||
"去背景"
|
||||
],
|
||||
"version": "1.0.3",
|
||||
"apiVersion": 1,
|
||||
"file": "plugins/plugin-xianyi-cutout.79c8c47dfc61.js",
|
||||
"size": 4488,
|
||||
"sha256": "79c8c47dfc6187b8af2688763e7f63034bb26867ccefbf135ed76d3745d6e24d",
|
||||
"integrity": "sha256-ecjEffxhh7ivJoh2Pn9jA0uyaGfM778TXtdtN0XW4k0="
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>插件市场 · Image Workbench</title>
|
||||
<link rel="stylesheet" href="/assets/style.css?v=3.25.29-mwmqrups">
|
||||
</head><body>
|
||||
<nav><div class="wrap inner">
|
||||
<a class="brand" href="/"><span class="dot">IW</span>Image Workbench</a>
|
||||
<div class="links">
|
||||
<a href="/">首页</a>
|
||||
<a href="/download/">下载</a>
|
||||
<a href="/plugins/" class="on">插件</a>
|
||||
<a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码</a>
|
||||
</div>
|
||||
<div class="right">
|
||||
<a class="btn" href="/plugins/">插件市场</a>
|
||||
<a class="btn primary" href="/download/">下载 v3.25.29</a>
|
||||
</div>
|
||||
</div></nav>
|
||||
<main>
|
||||
<section class="hero" style="padding:64px 0 8px;text-align:left"><div class="wrap">
|
||||
<h1 style="font-size:40px;margin:0">插件市场</h1>
|
||||
<p class="sub" style="margin:14px 0 0;text-align:left;max-width:720px">共 8 个插件。安装方式:应用内 <b>设置 → 插件 → 浏览</b>,点「安装」后重启生效。</p>
|
||||
</div></section>
|
||||
<section class="section" style="border-top:0;padding-top:24px"><div class="wrap">
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap;margin:0 0 18px" id="chips">
|
||||
<button class="tag on" data-tag="" style="cursor:pointer;background:#111;color:#fff;border-color:#111;padding:5px 12px">全部</button>
|
||||
<button class="tag" data-tag="出图" style="cursor:pointer;padding:5px 12px">出图</button>
|
||||
<button class="tag" data-tag="批处理" style="cursor:pointer;padding:5px 12px">批处理</button>
|
||||
<button class="tag" data-tag="画布" style="cursor:pointer;padding:5px 12px">画布</button>
|
||||
<button class="tag" data-tag="效率" style="cursor:pointer;padding:5px 12px">效率</button>
|
||||
<button class="tag" data-tag="浏览器" style="cursor:pointer;padding:5px 12px">浏览器</button>
|
||||
<button class="tag" data-tag="修图" style="cursor:pointer;padding:5px 12px">修图</button>
|
||||
<button class="tag" data-tag="标注" style="cursor:pointer;padding:5px 12px">标注</button>
|
||||
<button class="tag" data-tag="转换" style="cursor:pointer;padding:5px 12px">转换</button>
|
||||
<button class="tag" data-tag="矢量" style="cursor:pointer;padding:5px 12px">矢量</button>
|
||||
<button class="tag" data-tag="提示词" style="cursor:pointer;padding:5px 12px">提示词</button>
|
||||
<button class="tag" data-tag="风格" style="cursor:pointer;padding:5px 12px">风格</button>
|
||||
<button class="tag" data-tag="电商" style="cursor:pointer;padding:5px 12px">电商</button>
|
||||
<button class="tag" data-tag="抠图" style="cursor:pointer;padding:5px 12px">抠图</button>
|
||||
<button class="tag" data-tag="去背景" style="cursor:pointer;padding:5px 12px">去背景</button>
|
||||
</div>
|
||||
<input id="q" placeholder="搜索插件,例如:出图、抠图、矢量…" style="width:100%;max-width:420px;height:40px;padding:0 14px;border:1px solid var(--line);border-radius:10px;font-size:14px;outline:none;margin-bottom:22px">
|
||||
<div class="grid c3" id="list">
|
||||
<div class="pcard" data-name="批量出图 batch-export 资源中心勾选节点,串行批量生成并打包 zip 下载 出图 批处理" data-tags="出图,批处理">
|
||||
<div class="head"><span class="av" style="background:#e8f0fe">🗂️</span>
|
||||
<div><div class="nm">批量出图</div><div class="ver">v1.2.0 · 官方</div></div></div>
|
||||
<div class="desc">资源中心勾选节点,串行批量生成并打包 ZIP 下载</div>
|
||||
<div class="tags"><span class="tag">出图</span><span class="tag">批处理</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="空白画布 blank-canvas 新建空白画布节点,用于分区分组 画布 效率" data-tags="画布,效率">
|
||||
<div class="head"><span class="av" style="background:#eef2f6">⬜</span>
|
||||
<div><div class="nm">空白画布</div><div class="ver">v1.0.0 · 官方</div></div></div>
|
||||
<div class="desc">新建空白画布节点,用于分区分组</div>
|
||||
<div class="tags"><span class="tag">画布</span><span class="tag">效率</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="应用内浏览器 browser 独立窗口打开网页,或在画布节点里内嵌网页(跟随画布缩放,可调内容缩放) 浏览器 效率" data-tags="浏览器,效率">
|
||||
<div class="head"><span class="av" style="background:#eaf1fb">🌐</span>
|
||||
<div><div class="nm">应用内浏览器</div><div class="ver">v1.4.0 · 官方</div></div></div>
|
||||
<div class="desc">独立窗口打开网页,或在画布节点里内嵌网页(跟随画布缩放,可调内容缩放)</div>
|
||||
<div class="tags"><span class="tag">浏览器</span><span class="tag">效率</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="标注 / 修图 image-annotate 在画布内标注、涂抹、局部重绘 修图 标注" data-tags="修图,标注">
|
||||
<div class="head"><span class="av" style="background:#fdeaea">🖌️</span>
|
||||
<div><div class="nm">标注 / 修图</div><div class="ver">v1.20.6 · 官方</div></div></div>
|
||||
<div class="desc">在画布内标注、涂抹、局部重绘</div>
|
||||
<div class="tags"><span class="tag">修图</span><span class="tag">标注</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="位图转矢量 image-vectorize 把位图转成 svg 矢量路径 转换 矢量" data-tags="转换,矢量">
|
||||
<div class="head"><span class="av" style="background:#eaf3ea">✒️</span>
|
||||
<div><div class="nm">位图转矢量</div><div class="ver">v0.4.2 · 官方</div></div></div>
|
||||
<div class="desc">把位图转成 SVG 矢量路径</div>
|
||||
<div class="tags"><span class="tag">转换</span><span class="tag">矢量</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="风格库 style-source 风格提示词库与一键套用 提示词 风格" data-tags="提示词,风格">
|
||||
<div class="head"><span class="av" style="background:#fdf0e6">🎨</span>
|
||||
<div><div class="nm">风格库</div><div class="ver">v1.3.2 · 官方</div></div></div>
|
||||
<div class="desc">风格提示词库与一键套用</div>
|
||||
<div class="tags"><span class="tag">提示词</span><span class="tag">风格</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="白底图 white-bg-800 批量生成电商白底图(800px) 电商 出图" data-tags="电商,出图">
|
||||
<div class="head"><span class="av" style="background:#eef7fb">🧾</span>
|
||||
<div><div class="nm">白底图</div><div class="ver">v1.2.1 · 官方</div></div></div>
|
||||
<div class="desc">批量生成电商白底图(800px)</div>
|
||||
<div class="tags"><span class="tag">电商</span><span class="tag">出图</span></div>
|
||||
</div>
|
||||
<div class="pcard" data-name="鲜艺抠图 xianyi-cutout 接入鲜艺抠图模型的一键去背景 抠图 去背景" data-tags="抠图,去背景">
|
||||
<div class="head"><span class="av" style="background:#f3eafd">✂️</span>
|
||||
<div><div class="nm">鲜艺抠图</div><div class="ver">v1.0.3 · 官方</div></div></div>
|
||||
<div class="desc">接入鲜艺抠图模型的一键去背景</div>
|
||||
<div class="tags"><span class="tag">抠图</span><span class="tag">去背景</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="note" style="margin-top:26px">插件安装后会写进你的资料目录 <code>~/Documents/ImageWorkbench/plugins/</code>;卸载只删插件文件,不动画布与图库。</div>
|
||||
</div></section>
|
||||
</main>
|
||||
<footer><div class="wrap">
|
||||
<div class="cols">
|
||||
<div><div style="color:#fff;font-weight:640;margin-bottom:8px">Image Workbench</div>
|
||||
<div style="font-size:13px;line-height:1.8">本地优先的 AI 生图无限画布。图片、提示词与模型配置全部留在你自己的电脑里。</div></div>
|
||||
<div><h4>产品</h4><a href="/">首页</a><a href="/download/">下载</a><a href="/plugins/">插件市场</a></div>
|
||||
<div><h4>资源</h4><a href="https://git.maqiart.eu.org/malongan/image-workbench-desktop" target="_blank" rel="noopener">源码仓库</a><a href="https://git.maqiart.eu.org/malongan/iwb-plugins-desktop" target="_blank" rel="noopener">插件仓库</a><a href="/updates/latest.json" target="_blank" rel="noopener">更新源</a></div>
|
||||
<div><h4>说明</h4><a href="/download/">安装步骤</a><a href="/plugins/">插件安装</a></div>
|
||||
</div>
|
||||
<div class="copy"><span>© 2026 Image Workbench</span><span>数据保存在本地 · 不上传任何图片</span></div>
|
||||
</div></footer>
|
||||
<script>
|
||||
var q = document.getElementById('q'), list = document.getElementById('list'), chips = document.getElementById('chips'), activeTag = ''
|
||||
function apply () {
|
||||
var kw = (q.value || '').trim().toLowerCase()
|
||||
Array.prototype.forEach.call(list.children, function (el) {
|
||||
var okKw = !kw || el.dataset.name.indexOf(kw) >= 0
|
||||
var okTag = !activeTag || (',' + el.dataset.tags + ',').indexOf(',' + activeTag + ',') >= 0
|
||||
var ok = okKw && okTag
|
||||
el.style.display = ok ? '' : 'none'
|
||||
})
|
||||
}
|
||||
q.addEventListener('input', apply)
|
||||
chips.addEventListener('click', function (e) {
|
||||
var b = e.target.closest('button[data-tag]'); if (!b) return
|
||||
Array.prototype.forEach.call(chips.children, function (x) { x.style.background = ''; x.style.color = ''; x.style.borderColor = 'transparent' })
|
||||
b.style.background = '#111'; b.style.color = '#fff'; b.style.borderColor = '#111'
|
||||
activeTag = b.dataset.tag || ''
|
||||
apply()
|
||||
})
|
||||
</script>
|
||||
</body></html>
|
||||
@@ -1,8 +1,572 @@
|
||||
{
|
||||
"app": "Image Workbench",
|
||||
"subtitle": "本地优先的 AI 生图无限画布 · 桌面版(Tauri v2)",
|
||||
"updatedAt": "2026-11-17T06:25:27.704Z",
|
||||
"updatedAt": "2026-11-18T23:17:50.206Z",
|
||||
"releases": [
|
||||
{
|
||||
"version": "3.25.29",
|
||||
"date": "2026-11-18",
|
||||
"notes": "修画布网页压住地址栏(原生层与 DOM 的坐标原点差 32px)、内容跟随画布缩放;工具栏重做为可输入百分比的缩放设定框",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.29_aarch64.dmg",
|
||||
"size": 8709846,
|
||||
"sha256": "76e0815010e52248d4c71c32d845a388b64034c110599b5a269fed47da513058",
|
||||
"h": "76e0815010e5",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.28",
|
||||
"date": "2026-11-18",
|
||||
"notes": "恢复画布内网页节点并修好「一动就白」:取消动就藏与尺寸门槛,位置尺寸一次 set_bounds 推送",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.28_aarch64.dmg",
|
||||
"size": 8696941,
|
||||
"sha256": "e583a578ee55a507f61cf6080c7b235b9c6f3512a5f92c502f6efedf1f5928ce",
|
||||
"h": "e583a578ee55",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.27",
|
||||
"date": "2026-11-18",
|
||||
"notes": "下线画布内网页节点:原生子 webview 在画布上修不干净,撤掉该功能;独立窗口浏览器不受影响",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.27_aarch64.dmg",
|
||||
"size": 8682861,
|
||||
"sha256": "34a9569d415963d317532051202f94d2d0ce4c3d9763e9dfa929bb724011014d",
|
||||
"h": "34a9569d4159",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.26",
|
||||
"date": "2026-11-18",
|
||||
"notes": "修第二个网页节点报「主窗口不存在」:get_webview_window 在有了子 webview 之后永久失效,改用 get_window",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.26_aarch64.dmg",
|
||||
"size": 8704898,
|
||||
"sha256": "7839dbea23614146e7a9aebebf349fce5a66ebc5d2e22aaa2474098146a9b6c6",
|
||||
"h": "7839dbea2361",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.25",
|
||||
"date": "2026-11-18",
|
||||
"notes": "修画布内网页节点:子 webview 的 hide/show 静默失效导致一动画布网页就永久消失,改用移出窗口隐藏",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.25_aarch64.dmg",
|
||||
"size": 8708579,
|
||||
"sha256": "5c0ea530116d0ce6f12c1b84fc978b7090d50560e73202b1840098ed807d1868",
|
||||
"h": "5c0ea530116d",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.24",
|
||||
"date": "2026-11-18",
|
||||
"notes": "画布内网页节点:网页长在画布上(原生子 webview),可拖动缩放、和参考图并排对照;browser 插件 1.1.1",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.24_aarch64.dmg",
|
||||
"size": 8718818,
|
||||
"sha256": "d03b4e174dd9c5945f37dc7c28ddf06ef6cf00a48a07869c39cc0ef859f52973",
|
||||
"h": "d03b4e174dd9",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.23",
|
||||
"date": "2026-11-18",
|
||||
"notes": "应用内浏览器:独立窗口打开网页(插件 browser 1.0.0 上架市场),并修复浏览器窗口关不掉",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.23_aarch64.dmg",
|
||||
"size": 8696185,
|
||||
"sha256": "774a56bb022ff076b453ad3da16750527a8f2ca409795b611a3943d5058448eb",
|
||||
"h": "774a56bb022f",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.22",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:外观自定义扩展",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.22_aarch64.dmg",
|
||||
"size": 7834603,
|
||||
"sha256": "c6f17efa3e0cd720f1e3baa188dfd17a0af81fa7854c37e7f8d00e4998ba8021",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.22_x64.dmg",
|
||||
"size": 8133263,
|
||||
"sha256": "2ff7fc9c196052b700991e92f7926de4a10b313df5319e7363559a7c72c0eb73",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.21",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:下载命名 + 面板穿透修复",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.21_aarch64.dmg",
|
||||
"size": 7830585,
|
||||
"sha256": "d32b73bca38d783fd09a73cc1b70b849aafcac08a4a5d4ce95f5b8c29776fcc3",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.21_x64.dmg",
|
||||
"size": 8129401,
|
||||
"sha256": "ae39c772fffb688da7c3a911285b1c52b17c30b1cc7702ef3cc18d7d6a188e5c",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.20",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:导出目录三态 + 取色器修复",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.20_aarch64.dmg",
|
||||
"size": 7829876,
|
||||
"sha256": "15cacf28ff8d1f83914d31a363ecdc8be3779a8e0478ad27e3be63a4899a0bd9",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.20_x64.dmg",
|
||||
"size": 8126817,
|
||||
"sha256": "da173bf6a428173713c63177dfa45a351766e4b156911a503272a5f339a2f2e9",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.19",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Windows:工单#3 六项 + 图库下拉紧凑化",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.19_aarch64.dmg",
|
||||
"size": 7832598,
|
||||
"sha256": "2d56def2dc519dd78e2c1d819d698fbc1cf26649b0a6143005564e40eaa11b11",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.19_x64.dmg",
|
||||
"size": 8128508,
|
||||
"sha256": "7d091178ed1f1dcfef2e50d834bb1ec3e4cb0a5b7d7d994fdaf9b2e1b46dbc95",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"file": "updates/windows-x86_64/image-workbench_3.25.19_x64-setup.exe",
|
||||
"size": 4923387,
|
||||
"sha256": "5ccf97653479fe4b7ba604c3abf5cdcdd778cd658d34783cec4b21c7395f35dd",
|
||||
"kind": "exe"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.18",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:工单#3 六项",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.18_aarch64.dmg",
|
||||
"size": 7832387,
|
||||
"sha256": "a603a033a91afa5b3f941ba4912ad24e424f031d230a0b5a158695512161b0fb",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.18_x64.dmg",
|
||||
"size": 8131102,
|
||||
"sha256": "35b1b4a2acaea7134209e433b23d70bbc0d56d1ad149b80e5f0758afc2e6ef89",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.17",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:图标细节修正",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.17_aarch64.dmg",
|
||||
"size": 7827715,
|
||||
"sha256": "b0eb338adafbbcba3355ae7fc669be5456a11174d2c2e2bd2d289426665c39ec",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.17_x64.dmg",
|
||||
"size": 8127899,
|
||||
"sha256": "543cd456ef75211172795da38c166ccb29dce42254d599f3d442b6ce641a4753",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.16",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:新图标",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.16_aarch64.dmg",
|
||||
"size": 7876955,
|
||||
"sha256": "fdc3e93711d765022c4725340bbbb0cbac33ef0c854d2547b9a036f1b13d8e10",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.16_x64.dmg",
|
||||
"size": 8174517,
|
||||
"sha256": "f0948b377b9bd872b206227f46d21e81927914350d538e9ac16c4699da31850e",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.15",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Windows:桌面客户端版(网页部署面移除 + 独立更新清单)",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.15_aarch64.dmg",
|
||||
"size": 7935920,
|
||||
"sha256": "b256cc50733e10307afdc18454b567965dc5c85ce60342424feedb2815a2af54",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.15_x64.dmg",
|
||||
"size": 8233792,
|
||||
"sha256": "8b1c0c38b2981b6272ed22a77f73cc145c5e2c0152ec8bd8e2ee3958f15792d1",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"file": "updates/windows-x86_64/image-workbench_3.25.15_x64-setup.exe",
|
||||
"size": 4911427,
|
||||
"sha256": "030dc4660880d494c92052d97b2e23ee0dbf178261550cb3b232631cfd9b48f3",
|
||||
"kind": "exe"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.14",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:CSP 修复 + 外观 tab",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.14_aarch64.dmg",
|
||||
"size": 7936466,
|
||||
"sha256": "87e908b98900ff1b48cb70344d14c17b37149c8dd9716d53361d12fbf509c096",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.14_x64.dmg",
|
||||
"size": 8237874,
|
||||
"sha256": "2cfadfad91399c53b1b2fbf42d0c0ac521b0ebaec1ee481911c9af3d15c3bbba",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.13",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Windows:图片目录自愈 + 启动补齐工作目录(修丢图)",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.13_aarch64.dmg",
|
||||
"size": 7935763,
|
||||
"sha256": "863a5ff87a1debc0baf2dbe5033d8313c90649a6f48577408a23846d2b106e23",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.13_x64.dmg",
|
||||
"size": 8235328,
|
||||
"sha256": "25b4ad7237058ddd06d2a8f361114304ff03a37dd841d8c54a31d9d9e4d7d0e6",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"file": "updates/windows-x86_64/image-workbench_3.25.13_x64-setup.exe",
|
||||
"size": 4912010,
|
||||
"sha256": "669b1dfa58c4785c11c906b70e2cb4319d2743a40c1b7b9b4dbd8e9ceaf4f47c",
|
||||
"kind": "exe"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.12",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:图片目录自愈 + 不回退 Cache",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.12_aarch64.dmg",
|
||||
"size": 7935223,
|
||||
"sha256": "ddea5bf24ddfab943afce8d4a9eeb744c09fd15a204d0c359149025ecda4c0d8",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.12_x64.dmg",
|
||||
"size": 8232027,
|
||||
"sha256": "87d69fb85ce19c5e7993cf02ee35568352f0c6c4b026892e0a0d49e1505aa432",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.11",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Windows:单实例 + 外链系统浏览器 + 原生通知 + 窗口下限 + 仅 nsis 产物",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.11_aarch64.dmg",
|
||||
"size": 7931660,
|
||||
"sha256": "4d6d589d87b5a463310d73bd84da06186e2a291e536e75fadcce047cb2f86c49",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.11_x64.dmg",
|
||||
"size": 8234268,
|
||||
"sha256": "13ccf3b80e0162524c1d73cdae96c914288adcb5649b7d082d260649123d4970",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"file": "updates/windows-x86_64/image-workbench_3.25.11_x64-setup.exe",
|
||||
"size": 4905095,
|
||||
"sha256": "17702145cff43a02a4e7b50cdccded050d44819a9d6b80b539ae8997c7f4f0d4",
|
||||
"kind": "exe"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.10",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:图片持久化修复",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.10_aarch64.dmg",
|
||||
"size": 7671575,
|
||||
"sha256": "1882ed66713df4cfd0839a6d5220e717c297d31b050bfcbfb45efff33e660e61",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.10_x64.dmg",
|
||||
"size": 7978877,
|
||||
"sha256": "bca63766b951756228d513b1dc6d6c9e76d8bc5c4cc898171a24178b9f2e23ff",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.9",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Windows:图片登记立即落盘 + 清理前报数",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.9_aarch64.dmg",
|
||||
"size": 7674858,
|
||||
"sha256": "030b18cc29dd8f5e65b1906ef141a99ea34daadfacf827c10b75a2b0c957c94a",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.9_x64.dmg",
|
||||
"size": 7977320,
|
||||
"sha256": "06fd92df7fa6adf762d62450338f2f005c7c77cc9379bda4feaf49f27791f191",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"file": "updates/windows-x86_64/image-workbench_3.25.9_x64-setup.exe",
|
||||
"size": 4771479,
|
||||
"sha256": "d065e2a00eb59aeb55d101d9c22d39fb1298833b3782403379a72041ceb78230",
|
||||
"kind": "exe"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.8",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:同图导入与图片清理修复",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.8_aarch64.dmg",
|
||||
"size": 7673011,
|
||||
"sha256": "a3f6293d099f5624705138a342a8e95517e9e9bf1c7a8f88e84a573e9fd87955",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.8_x64.dmg",
|
||||
"size": 7978802,
|
||||
"sha256": "5716570a8d6bed248df66e2b1d82946265df2d5293c23753e3b2ae4ee3a810d9",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.7",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Windows:剪贴板 PNG 传输 + 路径文本转图片 + 大图不卡",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.7_aarch64.dmg",
|
||||
"size": 7669562,
|
||||
"sha256": "e4b6b7561391631130a91f0dd408ac03823f5c46963c3a7e5464a75210935af6",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.7_x64.dmg",
|
||||
"size": 7978666,
|
||||
"sha256": "63288e85748e0d360afae76009e6e44a668b9755b270883387380774468a4f33",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"file": "updates/windows-x86_64/image-workbench_3.25.7_x64-setup.exe",
|
||||
"size": 4776945,
|
||||
"sha256": "7ada5360e52ddd0c1f0a00d124c00612b5a03a34a6c8e128e74178cda8e52a2d",
|
||||
"kind": "exe"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.6",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:粘贴语义修正",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.6_aarch64.dmg",
|
||||
"size": 7657949,
|
||||
"sha256": "e92264a47106317b7125184ace097873d3c85cede9668137a7392b355e2afa3c",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.6_x64.dmg",
|
||||
"size": 7942814,
|
||||
"sha256": "88e143e4e76849226d24dadd8c7ec7f53a3940399cc5173df68330645fa7a33a",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.5",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:库面板粘贴修复",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.5_aarch64.dmg",
|
||||
"size": 7657153,
|
||||
"sha256": "1506b4ab5b77df7d98bf69fe29de586abbbdcc36f4a01163c8d86e3a75093c0d",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.5_x64.dmg",
|
||||
"size": 7944240,
|
||||
"sha256": "97b05edd949987669bfd57b97bc55379d9d0eb676914401e006046632148a352",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.4",
|
||||
"date": "2026-11-18",
|
||||
"notes": "Intel 版:剪贴板兜底",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.4_aarch64.dmg",
|
||||
"size": 7658606,
|
||||
"sha256": "0c02574f197fac4839bf937390425786ec872b36d9f8c529f122ee1349e855af",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.4_x64.dmg",
|
||||
"size": 7940457,
|
||||
"sha256": "f04664f6e051ae20e07bfb073ff675bbb83493f791ff4651120cdd00e9b0e103",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.3",
|
||||
"date": "2026-11-17",
|
||||
"notes": "Windows:剪贴板修复(Cmd+C/V、粘贴图片/文本、复制图片)+ 可自动更新",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.3_aarch64.dmg",
|
||||
"size": 7654670,
|
||||
"sha256": "fd05bf1a186574c611b166693b05a7531e5ec932bbc7cf75391bcd44a0c9eb5f",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.3_x64.dmg",
|
||||
"size": 7938826,
|
||||
"sha256": "00388a79069f9a78c48d491f366f73f1ee1500468f9970c8f657e25eb7c4e786",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"file": "updates/windows-x86_64/image-workbench_3.25.3_x64-setup.exe",
|
||||
"size": 4749572,
|
||||
"sha256": "e2a8cedc3aaaf61528edcf58c648079f618051cb6a4cf655b346315ad6424ba4",
|
||||
"kind": "exe"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.2",
|
||||
"date": "2026-11-17",
|
||||
"notes": "Windows:无内置插件 + 市场安装 + 页内确认 + 在线更新(首次需手动安装)",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.2_aarch64.dmg",
|
||||
"size": 7360220,
|
||||
"sha256": "6fb859f2e24d765308a6a97b3c72912d361eb71afb12ec385f2d72cef9cfef2e",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.2_x64.dmg",
|
||||
"size": 7626433,
|
||||
"sha256": "07027d97cffde7c0c46b65b2ec875a9fd4dfbdce4494d937e93d46169f61b3f8",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"file": "updates/windows-x86_64/image-workbench_3.25.2_x64-setup.exe",
|
||||
"size": 4681055,
|
||||
"sha256": "dda001a15e4aa8b25ef6200936884f5d78783309338a9979aadc175c8cc965af",
|
||||
"kind": "exe"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.1",
|
||||
"date": "2026-11-17",
|
||||
"notes": "Intel Mac 版:性能与数据卫生(图库清单去 base64、缩略图落盘、回收 20.2MB)",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"file": "updates/darwin-aarch64/image-workbench_3.25.1_aarch64.dmg",
|
||||
"size": 6545041,
|
||||
"sha256": "5b711840b36a10ba2983ad48923c662897d25e55ea30de9fb7ea944694648124",
|
||||
"kind": "dmg"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"file": "updates/darwin-x86_64/image-workbench_3.25.1_x64.dmg",
|
||||
"size": 6772292,
|
||||
"sha256": "7863e4a3257d15a42d698ca79d0edbfb86496f20e67be7389c1de498c01f471b",
|
||||
"kind": "dmg"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"version": "3.25.0",
|
||||
"date": "2026-11-17",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "image-workbench"
|
||||
version = "3.25.0"
|
||||
version = "3.25.30"
|
||||
description = "无限画布 · 生图工作台桌面版"
|
||||
authors = ["malongan"]
|
||||
license = ""
|
||||
@@ -23,8 +23,24 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
log = "0.4"
|
||||
# tray-icon:系统托盘(关闭窗口收进托盘而不是退出)
|
||||
# tray-icon:系统托盘;image-png:托盘用单色 PNG 模板图标
|
||||
tauri = { version = "2.12.5", features = ["tray-icon", "image-png"] }
|
||||
# unstable:`Manager::get_window`(窗口级句柄,不受子 webview 影响)与 Window::add_child 都在它下面。
|
||||
# 画布内嵌网页已下线(v3.25.27),但 get_window 仍要留着 —— save_geom/托盘/单实例都靠它,
|
||||
# 且它比 get_webview_window 更稳(后者一旦窗口里有非同名 webview 就返回 None,见 v3.25.26)。
|
||||
tauri = { version = "2.12.5", features = ["tray-icon", "image-png", "unstable"] }
|
||||
url = "2"
|
||||
tauri-plugin-log = "2"
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-fs = "2"
|
||||
tauri-plugin-http = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
tauri-plugin-single-instance = "2"
|
||||
tauri-plugin-notification = "2"
|
||||
arboard = "3"
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
base64 = "0.22"
|
||||
|
||||
# 画布内嵌网页的圆角(2026-11-19):WKWebView 是矩形,要给它 backing layer 设
|
||||
# cornerRadius/masksToBounds 只能走 Objective-C 消息。objc2 0.6 已由 tauri/wry 引入
|
||||
# (Cargo.lock 里是同一个 0.6.x),这里显式依赖不会多编译一份。
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = "0.6"
|
||||
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 8.6 KiB After Width: | Height: | Size: 8.0 KiB |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.1 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 4.3 KiB |
|
Before Width: | Height: | Size: 4.6 KiB After Width: | Height: | Size: 4.5 KiB |
|
Before Width: | Height: | Size: 9.8 KiB After Width: | Height: | Size: 9.1 KiB |
|
Before Width: | Height: | Size: 1006 B After Width: | Height: | Size: 1013 B |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 2.1 KiB After Width: | Height: | Size: 2.3 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 214 B After Width: | Height: | Size: 1.3 KiB |
@@ -1,7 +1,7 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use tauri::menu::{Menu, MenuItem};
|
||||
use tauri::tray::TrayIconBuilder;
|
||||
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, WebviewWindow, WindowEvent};
|
||||
use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, WebviewUrl, WebviewWindowBuilder, WindowEvent};
|
||||
use tauri_plugin_fs::FsExt; // 提供 fs_scope():运行时给「资料目录」授权
|
||||
|
||||
// 「是否正在真正退出」:托盘菜单的「退出」或 Cmd+Q 才会置位,
|
||||
@@ -16,15 +16,21 @@ struct WindowGeom {
|
||||
h: u32,
|
||||
}
|
||||
|
||||
fn geom_file(app: &AppHandle) -> Option<std::path::PathBuf> {
|
||||
app.path()
|
||||
.app_config_dir()
|
||||
.ok()
|
||||
.map(|d| d.join("window-geom.json"))
|
||||
fn geom_file(app: &AppHandle, label: &str) -> Option<std::path::PathBuf> {
|
||||
app.path().app_config_dir().ok().map(|d| {
|
||||
// 主窗口沿用历史文件名,避免升级后把已记住的位置丢掉一次
|
||||
if label == "main" {
|
||||
d.join("window-geom.json")
|
||||
} else {
|
||||
d.join(format!("{}-geom.json", label))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 只在窗口处于普通状态时记录:最大化/全屏时的尺寸不是用户想恢复的那个尺寸
|
||||
fn save_geom(win: &WebviewWindow) {
|
||||
// 只在窗口处于普通状态时记录:最大化/全屏时的尺寸不是用户想恢复的那个尺寸。
|
||||
// 按 label 取窗口,主窗口与浏览器窗口共用同一套机制,各自存各自的文件。
|
||||
fn save_geom(app: &AppHandle, label: &str) {
|
||||
let Some(win) = app.get_window(label) else { return };
|
||||
if win.is_maximized().unwrap_or(false) || win.is_fullscreen().unwrap_or(false) {
|
||||
return;
|
||||
}
|
||||
@@ -32,8 +38,7 @@ fn save_geom(win: &WebviewWindow) {
|
||||
return;
|
||||
};
|
||||
let g = WindowGeom { x: pos.x, y: pos.y, w: size.width, h: size.height };
|
||||
let app = win.app_handle();
|
||||
if let Some(p) = geom_file(app) {
|
||||
if let Some(p) = geom_file(app, label) {
|
||||
if let Some(dir) = p.parent() {
|
||||
let _ = std::fs::create_dir_all(dir);
|
||||
}
|
||||
@@ -44,16 +49,18 @@ fn save_geom(win: &WebviewWindow) {
|
||||
}
|
||||
|
||||
// 恢复上次窗口大小与位置;中心点不在任何显示器内就只恢复尺寸(换过显示器不至于把窗口丢到屏幕外)
|
||||
fn restore_geom(win: &WebviewWindow, app: &AppHandle) {
|
||||
let Some(p) = geom_file(app) else { return };
|
||||
fn restore_geom(app: &AppHandle, label: &str, min_w: u32, min_h: u32) {
|
||||
let Some(win) = app.get_window(label) else { return };
|
||||
let Some(p) = geom_file(app, label) else { return };
|
||||
let Ok(txt) = std::fs::read_to_string(p) else { return };
|
||||
let Ok(g) = serde_json::from_str::<WindowGeom>(&txt) else { return };
|
||||
if g.w < 800 || g.h < 500 {
|
||||
return;
|
||||
}
|
||||
let _ = win.set_size(PhysicalSize::new(g.w, g.h));
|
||||
let cx = g.x + (g.w as i32) / 2;
|
||||
let cy = g.y + (g.h as i32) / 2;
|
||||
// 最小尺寸与窗口下限对齐:否则会恢复出一个比下限还小的窗口
|
||||
// (曾实测 1051x488 时画布渲染成空白)
|
||||
let w = g.w.max(min_w);
|
||||
let h = g.h.max(min_h);
|
||||
let _ = win.set_size(PhysicalSize::new(w, h));
|
||||
let cx = g.x + (w as i32) / 2;
|
||||
let cy = g.y + (h as i32) / 2;
|
||||
let visible = win
|
||||
.available_monitors()
|
||||
.map(|ms| {
|
||||
@@ -70,7 +77,7 @@ fn restore_geom(win: &WebviewWindow, app: &AppHandle) {
|
||||
}
|
||||
|
||||
fn show_main(app: &AppHandle) {
|
||||
if let Some(w) = app.get_webview_window("main") {
|
||||
if let Some(w) = app.get_window("main") {
|
||||
let _ = w.show();
|
||||
let _ = w.unminimize();
|
||||
let _ = w.set_focus();
|
||||
@@ -92,7 +99,7 @@ fn build_tray(app: &AppHandle) -> tauri::Result<()> {
|
||||
.on_menu_event(|app, e| match e.id().as_ref() {
|
||||
"show" => show_main(app),
|
||||
"hide" => {
|
||||
if let Some(w) = app.get_webview_window("main") {
|
||||
if let Some(w) = app.get_window("main") {
|
||||
let _ = w.hide();
|
||||
}
|
||||
}
|
||||
@@ -205,13 +212,626 @@ fn open_app_data_dir(app: AppHandle) -> Result<String, String> {
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
use tauri_plugin_updater::UpdaterExt;
|
||||
|
||||
#[tauri::command]
|
||||
fn clipboard_write_text(text: String) -> Result<bool, String> {
|
||||
let mut cb = Clipboard::new().map_err(|e| e.to_string())?;
|
||||
cb.set_text(text).map_err(|e| e.to_string())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn clipboard_read_text() -> Result<String, String> {
|
||||
let mut cb = Clipboard::new().map_err(|e| e.to_string())?;
|
||||
Ok(cb.get_text().unwrap_or_default())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn check_update(app: tauri::AppHandle) -> Result<Option<serde_json::Value>, String> {
|
||||
let updater = app.updater().map_err(|e| e.to_string())?;
|
||||
match updater.check().await {
|
||||
Ok(Some(update)) => Ok(Some(serde_json::json!({
|
||||
"version": update.version,
|
||||
"currentVersion": update.current_version,
|
||||
"notes": update.body.unwrap_or_default(),
|
||||
"date": update.date.map(|d| d.to_string()).unwrap_or_default()
|
||||
}))),
|
||||
Ok(None) => Ok(None),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn install_update(app: tauri::AppHandle) -> Result<bool, String> {
|
||||
let updater = app.updater().map_err(|e| e.to_string())?;
|
||||
let found = updater.check().await.map_err(|e| e.to_string())?;
|
||||
let Some(update) = found else { return Ok(false) };
|
||||
update
|
||||
.download_and_install(|_chunk, _total| {}, || {})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
app.restart();
|
||||
}
|
||||
|
||||
use arboard::Clipboard;
|
||||
|
||||
fn b64_encode(bytes: &[u8]) -> String {
|
||||
use base64::Engine;
|
||||
base64::engine::general_purpose::STANDARD.encode(bytes)
|
||||
}
|
||||
|
||||
fn b64_decode(s: &str) -> Result<Vec<u8>, String> {
|
||||
use base64::Engine;
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(s.as_bytes())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ClipImagePayload {
|
||||
width: u32,
|
||||
height: u32,
|
||||
png_base64: String,
|
||||
}
|
||||
|
||||
/// 读系统剪贴板图片 → PNG(base64)
|
||||
///
|
||||
/// 为什么返回 PNG 而不是裸 RGBA:12MP 照片的 RGBA 是 46MB,base64 后 62MB,
|
||||
/// 穿过 IPC 会卡住前端好几秒;PNG 通常只有几 MB。
|
||||
#[tauri::command]
|
||||
fn clipboard_read_image() -> Result<Option<ClipImagePayload>, String> {
|
||||
let mut cb = Clipboard::new().map_err(|e| e.to_string())?;
|
||||
let img = match cb.get_image() {
|
||||
Ok(v) => v,
|
||||
Err(_) => return Ok(None),
|
||||
};
|
||||
let w = img.width as u32;
|
||||
let h = img.height as u32;
|
||||
if w == 0 || h == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let raw = img.bytes.into_owned();
|
||||
let buf = image::RgbaImage::from_raw(w, h, raw)
|
||||
.ok_or_else(|| "剪贴板图片像素数据不完整".to_string())?;
|
||||
let mut png: Vec<u8> = Vec::new();
|
||||
{
|
||||
use image::ImageEncoder;
|
||||
let enc = image::codecs::png::PngEncoder::new(&mut png);
|
||||
enc.write_image(buf.as_raw(), w, h, image::ExtendedColorType::Rgba8)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(Some(ClipImagePayload {
|
||||
width: w,
|
||||
height: h,
|
||||
png_base64: b64_encode(&png),
|
||||
}))
|
||||
}
|
||||
|
||||
/// 把 PNG(base64)写进系统剪贴板
|
||||
#[tauri::command]
|
||||
fn clipboard_write_image(png_base64: String) -> Result<bool, String> {
|
||||
let bytes = b64_decode(&png_base64)?;
|
||||
let img = image::load_from_memory(&bytes).map_err(|e| e.to_string())?.to_rgba8();
|
||||
let (w, h) = (img.width() as usize, img.height() as usize);
|
||||
let mut cb = Clipboard::new().map_err(|e| e.to_string())?;
|
||||
cb.set_image(arboard::ImageData {
|
||||
width: w,
|
||||
height: h,
|
||||
bytes: std::borrow::Cow::Owned(img.into_raw()),
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
|
||||
fn open_external(url: &str) -> Result<(), String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
std::process::Command::new("open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
std::process::Command::new("cmd")
|
||||
.args(["/C", "start", "", url])
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
{
|
||||
std::process::Command::new("xdg-open").arg(url).spawn().map(|_| ()).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn open_external_url(url: String) -> Result<bool, String> {
|
||||
if !(url.starts_with("http://") || url.starts_with("https://")) {
|
||||
return Err("只允许 http/https".into());
|
||||
}
|
||||
open_external(&url)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// 应用内打开网页:固定 label `browser` 复用同一个窗口,重复打开就聚焦并导航到新地址。
|
||||
// 加载的是外部网站自己的页面,不受主窗口 CSP 约束(Tauri 的 CSP 只注入自身的 HTML 页面),
|
||||
// 这也是官方推荐的「加载不可信远程内容」方式,避免 iframe 被对方 X-Frame-Options 拒绝。
|
||||
// 浏览器窗口不在 capabilities 里 ⇒ 无 IPC 权限,正好不该让它碰到宿主 API。
|
||||
//
|
||||
// 保留 async(内部无 await):让命令跑在 Tauri 的异步运行时里,不占 IPC 主线程;
|
||||
// 建窗/导航都是同步 API,不需要 await 也不需要额外 yield。
|
||||
#[tauri::command]
|
||||
async fn open_browser_window(app: AppHandle, url: String) -> Result<bool, String> {
|
||||
let parsed = url::Url::parse(&url).map_err(|_| "网址格式不合法".to_string())?;
|
||||
if parsed.scheme() != "http" && parsed.scheme() != "https" {
|
||||
return Err("只允许 http/https".into());
|
||||
}
|
||||
|
||||
let label = "browser";
|
||||
// 窗口标题跟着目标站点走,复用窗口时也要更新,否则标题永远是第一次打开的那个站。
|
||||
let title = parsed
|
||||
.host_str()
|
||||
.filter(|h| !h.is_empty())
|
||||
.unwrap_or("浏览器")
|
||||
.to_string();
|
||||
|
||||
if let Some(win) = app.get_webview_window(label) {
|
||||
// 已存在:显示、取消最小化、聚焦,再导航到新地址。
|
||||
let _ = win.show();
|
||||
let _ = win.unminimize();
|
||||
let _ = win.set_focus();
|
||||
let _ = win.set_title(&title);
|
||||
// 用原生命令导航,不在外部页面的 JS 上下文里执行字符串。
|
||||
win.navigate(parsed).map_err(|e| e.to_string())?;
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
WebviewWindowBuilder::new(&app, label, WebviewUrl::External(parsed))
|
||||
.title(&title)
|
||||
.inner_size(1200.0, 820.0)
|
||||
.min_inner_size(800.0, 600.0)
|
||||
.center()
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
// 恢复上次浏览器窗口的位置/大小;没有记录时保持上面的居中默认值。
|
||||
restore_geom(&app, label, 800, 600);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// 浏览器窗口控制:由主窗口(有 IPC 权限)驱动,browser 窗口自身仍然无 IPC 权限。
|
||||
// back/forward 用固定字符串且不拼接任何外部输入,不构成注入面。
|
||||
#[tauri::command]
|
||||
fn browser_control(app: AppHandle, action: String) -> Result<bool, String> {
|
||||
let win = app
|
||||
.get_webview_window("browser")
|
||||
.ok_or_else(|| "浏览器窗口未打开".to_string())?;
|
||||
match action.as_str() {
|
||||
"back" => win.eval("history.back()").map_err(|e| e.to_string())?,
|
||||
"forward" => win.eval("history.forward()").map_err(|e| e.to_string())?,
|
||||
"reload" => win.reload().map_err(|e| e.to_string())?,
|
||||
// 关闭走正常 CloseRequested 路径;主窗口以外不再 prevent_close,会真正销毁。
|
||||
"close" => win.close().map_err(|e| e.to_string())?,
|
||||
_ => return Err("未知操作".into()),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
// 面板用来显示「当前打开的是哪个站」以及窗口是否还活着。
|
||||
#[tauri::command]
|
||||
fn browser_state(app: AppHandle) -> Result<serde_json::Value, String> {
|
||||
match app.get_webview_window("browser") {
|
||||
Some(win) => Ok(serde_json::json!({
|
||||
"open": true,
|
||||
"url": win.url().map(|u| u.to_string()).unwrap_or_default()
|
||||
})),
|
||||
None => Ok(serde_json::json!({ "open": false, "url": "" })),
|
||||
}
|
||||
}
|
||||
|
||||
// ── 画布内嵌浏览器(主窗口的**子 webview**)────────────────────────────────────
|
||||
// 与上面「独立窗口」是两条完全不同的路:这里用 `Window::add_child` 把 webview 作为
|
||||
// 主窗口的子视图挂在画布节点上,网页真正长在画布里面(跟着平移、缩放)。
|
||||
//
|
||||
// 为什么不用 iframe:GitHub / 站酷 / Figma / Pinterest 这些站用 X-Frame-Options 或
|
||||
// CSP frame-ancestors 明确拒绝被嵌,且主窗口 CSP 没有 frame-src。
|
||||
//
|
||||
// 三条硬约束(2026-11-19 重做时定下,都是踩坑换来的):
|
||||
// 1) **永不调 show()/hide()**。macOS 上对子 webview `hide()` 之后再 `show()`,
|
||||
// 两个调用都返回 Ok、网页却永久不再绘制(v3.25.24 用户实测:一动画布就白)。
|
||||
// 需要隐藏时用 set_bounds 把视图停到窗口外(CWV_PARK)——NSView 在父视图外
|
||||
// 既不绘制也不收事件,效果等价且可以移回来。
|
||||
// 2) 位置与尺寸**用一次 set_bounds 推**(一条消息),不要 set_size + set_position
|
||||
// 两条消息:两条消息之间视图会短暂处于「新尺寸 + 旧位置」的中间态。
|
||||
// 3) 尺寸只在渲染层判定「静止」时推;位置可以随时跟。实测连续 60 帧改尺寸、
|
||||
// 1×1 极值、连续移动都不会白(最小工程逐帧截图验证),但静止推送能把 WebKit
|
||||
// 的重排次数压到最少,拖动/缩放过程更稳。
|
||||
//
|
||||
// `add_child` 与 `Manager::get_window` 都需要 tauri 的 `unstable` feature(见 Cargo.toml)。
|
||||
// 子 webview 不在 capabilities 里 ⇒ 被它加载的外部页面拿不到宿主 IPC。
|
||||
const CWV_PREFIX: &str = "cwv-";
|
||||
const CWV_PARK: f64 = -20000.0;
|
||||
|
||||
// 热路径采样计数器:bounds 每秒可能推几十次,不能每次都写盘。
|
||||
static CWV_BOUNDS_CALLS: AtomicU64 = AtomicU64::new(0);
|
||||
// 圆角设置次数(只用于日志节流)
|
||||
static CWV_ROUND_CALLS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
// 画布网页的运行时诊断日志(_cwv.log,落在 app_config_dir)。
|
||||
// 子 webview 建不起来时,渲染层只拿到一个 Err 字符串,落盘日志能还原「哪一步断的」。
|
||||
fn cwv_log(app: &AppHandle, msg: &str) {
|
||||
let Ok(dir) = app.path().app_config_dir() else { return };
|
||||
let p = dir.join("_cwv.log");
|
||||
// 超过 256KB 只留尾部 32KB:长跑时不能无上限增长
|
||||
if let Ok(meta) = std::fs::metadata(&p) {
|
||||
if meta.len() > 256 * 1024 {
|
||||
if let Ok(bytes) = std::fs::read(&p) {
|
||||
let keep = bytes.len().saturating_sub(32 * 1024);
|
||||
let _ = std::fs::write(&p, &bytes[keep..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let ts = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis())
|
||||
.unwrap_or(0);
|
||||
use std::io::Write;
|
||||
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) {
|
||||
let _ = f.write_all(format!("[{}] {}\n", ts, msg).as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
// 节点 id → 子 webview label。只保留安全字符:label 会进系统标识符,不能被节点 id 里的
|
||||
// 任意字符污染(旧存档里可能有空格/中文)。
|
||||
fn cwv_label(id: &str) -> String {
|
||||
let cleaned: String = id
|
||||
.chars()
|
||||
.filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
|
||||
.take(40)
|
||||
.collect();
|
||||
format!("{}{}", CWV_PREFIX, if cleaned.is_empty() { "x".into() } else { cleaned })
|
||||
}
|
||||
|
||||
fn cwv_parse(url: &str) -> Result<url::Url, String> {
|
||||
let raw = url.trim();
|
||||
if raw.is_empty() {
|
||||
return Err("没有网址".into());
|
||||
}
|
||||
let with_scheme = if raw.contains("://") {
|
||||
raw.to_string()
|
||||
} else {
|
||||
format!("https://{}", raw)
|
||||
};
|
||||
let parsed = url::Url::parse(&with_scheme).map_err(|_| "网址格式不合法".to_string())?;
|
||||
if parsed.scheme() != "http" && parsed.scheme() != "https" {
|
||||
return Err("只允许 http/https".into());
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
// 位置 + 尺寸打包成一次 set_bounds 的入参。
|
||||
//
|
||||
// ox/oy 是「原生层坐标原点到 DOM 坐标原点」的差值(见 canvas_webview_metrics 的注释)。
|
||||
// 渲染层量到的是内容视图坐标,而 add_child/set_bounds 用的是**窗口边框**坐标,
|
||||
// 两者相差一个标题栏高度 —— 不补这一下,网页会整体上浮盖住地址栏。
|
||||
fn cwv_rect(x: f64, y: f64, w: f64, h: f64, ox: f64, oy: f64) -> tauri::Rect {
|
||||
tauri::Rect {
|
||||
position: tauri::Position::Logical(tauri::LogicalPosition::new(x + ox, y + oy)),
|
||||
// 下限 2px:wry/WebKit 对 0 尺寸视图的处理不稳定,1px 也没有任何显示价值
|
||||
size: tauri::Size::Logical(tauri::LogicalSize::new(w.max(2.0), h.max(2.0))),
|
||||
}
|
||||
}
|
||||
|
||||
// ── 圆角(2026-11-19 用户要求)──────────────────────────────────────────────
|
||||
// 原生子 webview 本身是矩形,盖在节点卡片上时四角会从卡片的圆角(--iwb-node-radius,
|
||||
// 默认 14px)里「顶」出来——看起来像网页没有跟着节点外形走。
|
||||
// 做法:直接给 WKWebView 的 backing layer 设 cornerRadius + masksToBounds。
|
||||
// WebKit 把渲染内容放在它的 sublayer 里,父 layer 的 masksToBounds 会把四角裁掉。
|
||||
// 半径按画布缩放同比缩放(zoom 即「画布缩放 × 节点自身缩放」),否则缩到 25% 时
|
||||
// 14px 圆角相对节点会显得巨大、缩放到 300% 又几乎看不见。
|
||||
//
|
||||
// 2026-11-19 二次:半径不再写死,由渲染层把「外观设置 → 节点圆角」的当前值
|
||||
// (CSS 变量 --iwb-node-radius,6~20px)随 bounds 一起送进来,用户改设置即时生效;
|
||||
// 传 null 时才退回默认 14。
|
||||
const CWV_RADIUS: f64 = 14.0;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn cwv_round(app: &AppHandle, wv: &tauri::webview::Webview<tauri::Wry>, zoom: f64, base: Option<f64>) {
|
||||
let base = match base {
|
||||
Some(b) if b.is_finite() && b > 0.0 => b.clamp(2.0, 40.0),
|
||||
_ => CWV_RADIUS,
|
||||
};
|
||||
// 上限 60:圆角设置 20px × 300% 缩放;下限 0.5:缩到 20% 时不至于变成直角。
|
||||
let r = (base * zoom).clamp(0.5, 60.0);
|
||||
let app2 = app.clone();
|
||||
// 失败不致命(视图可能正在销毁):忽略即可,不要中断 bounds 推送
|
||||
let _ = wv.with_webview(move |p| {
|
||||
let view = p.inner();
|
||||
if view.is_null() {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
use objc2::msg_send;
|
||||
use objc2::runtime::{AnyObject, Bool};
|
||||
let v = view as *mut AnyObject;
|
||||
// 子 webview 通常已经是 layer-backed,这一句幂等,只是为了拿到非空 layer
|
||||
let _: () = msg_send![v, setWantsLayer: Bool::YES];
|
||||
let layer: *mut AnyObject = msg_send![v, layer];
|
||||
if layer.is_null() {
|
||||
cwv_log(&app2, &format!("round:no-layer r={:.1}", r));
|
||||
return;
|
||||
}
|
||||
let _: () = msg_send![layer, setCornerRadius: r];
|
||||
let _: () = msg_send![layer, setMasksToBounds: Bool::YES];
|
||||
// 只记前几次:确认「圆角到底有没有落到 layer 上」,避免日志刷屏
|
||||
let n = CWV_ROUND_CALLS.fetch_add(1, Ordering::Relaxed);
|
||||
if n < 4 {
|
||||
cwv_log(&app2, &format!("round:ok n={} r={:.1}", n, r));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn cwv_round(_app: &AppHandle, _wv: &tauri::webview::Webview<tauri::Wry>, _zoom: f64, _base: Option<f64>) {}
|
||||
|
||||
// 窗口边框尺寸 vs 内容视图尺寸。
|
||||
//
|
||||
// **为什么需要它(v3.25.29 实测)**:`add_child` / `set_bounds` 的 LogicalPosition
|
||||
// 以**窗口边框左上角**为原点,而 `getBoundingClientRect()` 以**内容视图左上角**为原点。
|
||||
// macOS 标准标题栏下两者差 32pt,于是每个画布网页都整体上移 32px —— 正好把地址栏、
|
||||
// 前进/后退/刷新按钮全部盖住(用户看到的就是「按钮被遮住了」)。
|
||||
// 最小工程实测:窗口 frame=1000x760,DOM innerHeight=728,子视图 y 传 200 实际落在 168。
|
||||
//
|
||||
// 这里只回报「窗口边框」尺寸,差值由渲染层用 window.innerHeight 算 —— 全屏时标题栏消失,
|
||||
// 差值自然回到 0,不需要额外分支。
|
||||
#[tauri::command]
|
||||
fn canvas_webview_metrics(app: AppHandle) -> Result<serde_json::Value, String> {
|
||||
let win = app.get_window("main").ok_or_else(|| "主窗口不存在".to_string())?;
|
||||
let size = win.inner_size().map_err(|e| e.to_string())?;
|
||||
let scale = win.scale_factor().unwrap_or(1.0);
|
||||
Ok(serde_json::json!({
|
||||
"frameW": size.width as f64 / scale,
|
||||
"frameH": size.height as f64 / scale,
|
||||
"scale": scale,
|
||||
}))
|
||||
}
|
||||
|
||||
// 确保某节点对应的子 webview 存在。返回 true = 这次真的新建了。
|
||||
#[tauri::command]
|
||||
fn canvas_webview_ensure(
|
||||
app: AppHandle,
|
||||
id: String,
|
||||
url: String,
|
||||
x: f64,
|
||||
y: f64,
|
||||
w: f64,
|
||||
h: f64,
|
||||
ox: f64,
|
||||
oy: f64,
|
||||
zoom: Option<f64>,
|
||||
radius: Option<f64>,
|
||||
) -> Result<bool, String> {
|
||||
let parsed = cwv_parse(&url)?;
|
||||
let label = cwv_label(&id);
|
||||
if let Some(wv) = app.get_webview(&label) {
|
||||
// 已存在:只校正 bounds(不 show/hide —— 见文件头约束 1)
|
||||
if let Err(e) = wv.set_bounds(cwv_rect(x, y, w, h, ox, oy)) {
|
||||
cwv_log(&app, &format!("ensure:bounds-err label={} err={}", label, e));
|
||||
}
|
||||
if let Some(z) = zoom {
|
||||
let _ = wv.set_zoom(z);
|
||||
}
|
||||
// 圆角:视图可能刚被重建(画布切换/暂停恢复),每次 ensure 都补一次,幂等
|
||||
cwv_round(&app, &wv, zoom.unwrap_or(1.0), radius);
|
||||
return Ok(false);
|
||||
}
|
||||
// 必须用 get_window 而不是 get_webview_window:后者要求 `is_webview_window()`,
|
||||
// 即该窗口下所有 webview 的 label 都等于窗口 label。一旦 add_child 建出 cwv-xxx,
|
||||
// 这个条件永久为假,get_webview_window("main") 从此永远返回 None(v3.25.26 实测)。
|
||||
let Some(window) = app.get_window("main") else {
|
||||
cwv_log(&app, "ensure:fail 取不到 main 窗口的 Window 句柄");
|
||||
return Err("主窗口不存在".into());
|
||||
};
|
||||
let built = window.add_child(
|
||||
tauri::webview::WebviewBuilder::new(&label, WebviewUrl::External(parsed.clone()))
|
||||
.on_page_load(|wv, payload| {
|
||||
use tauri::webview::PageLoadEvent;
|
||||
use tauri::Emitter;
|
||||
let kind = match payload.event() {
|
||||
PageLoadEvent::Started => "started",
|
||||
PageLoadEvent::Finished => "finished",
|
||||
};
|
||||
let label = wv.label().to_string();
|
||||
let id = label.strip_prefix(CWV_PREFIX).unwrap_or(&label).to_string();
|
||||
// 子 webview 没有 IPC 权限,只能由它自己的 app_handle 往主窗口广播
|
||||
let _ = wv.app_handle().emit(
|
||||
"cwv-page",
|
||||
serde_json::json!({ "id": id, "kind": kind, "url": payload.url().to_string() }),
|
||||
);
|
||||
}),
|
||||
tauri::LogicalPosition::new(x + ox, y + oy),
|
||||
tauri::LogicalSize::new(w.max(2.0), h.max(2.0)),
|
||||
);
|
||||
match built {
|
||||
Ok(wv) => {
|
||||
// add_child 传入的 bounds 在部分 macOS 版本上不立刻生效,用 set_bounds 再摆一次
|
||||
if let Err(e) = wv.set_bounds(cwv_rect(x, y, w, h, ox, oy)) {
|
||||
cwv_log(&app, &format!("ensure:post-bounds-err label={} err={}", label, e));
|
||||
}
|
||||
// 缩放:页面 CSS 像素按 zoom 放大/缩小,配合「矩形随画布缩放」就能让网页
|
||||
// 像图片一样跟着画布一起缩放,而不是一直按原宽度重排。
|
||||
if let Some(z) = zoom {
|
||||
if let Err(e) = wv.set_zoom(z) {
|
||||
cwv_log(&app, &format!("ensure:zoom-err label={} zoom={} err={}", label, z, e));
|
||||
}
|
||||
}
|
||||
// 新建后立刻上一次圆角(zoom 缺省按 1 倍)。放 here 而不是等首帧 bounds:
|
||||
// 首帧前视图已经贴到卡片上,直角会闪一下;先设好就不会看到方角。
|
||||
cwv_round(&app, &wv, zoom.unwrap_or(1.0), radius);
|
||||
cwv_log(
|
||||
&app,
|
||||
&format!(
|
||||
"ensure:ok label={} url={} rect=({:.0},{:.0} {:.0}x{:.0}) off=({:.0},{:.0}) zoom={:?}",
|
||||
label, parsed, x, y, w, h, ox, oy, zoom
|
||||
),
|
||||
);
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
cwv_log(&app, &format!("ensure:err label={} err={}", label, e));
|
||||
Err(e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染层推送位置/尺寸/可见性。
|
||||
// 返回 false = Rust 侧没有这个 webview(被 close / 进程重启),前端应回滚并重建。
|
||||
#[tauri::command]
|
||||
fn canvas_webview_bounds(
|
||||
app: AppHandle,
|
||||
id: String,
|
||||
x: f64,
|
||||
y: f64,
|
||||
w: f64,
|
||||
h: f64,
|
||||
visible: bool,
|
||||
zoom: Option<f64>,
|
||||
ox: f64,
|
||||
oy: f64,
|
||||
radius: Option<f64>,
|
||||
) -> Result<bool, String> {
|
||||
let label = cwv_label(&id);
|
||||
let Some(wv) = app.get_webview(&label) else {
|
||||
return Ok(false);
|
||||
};
|
||||
// 隐藏 = 停到窗口外,尺寸保持不变(别裁到 1px:那会触发 WebKit 重排)
|
||||
let rect = if visible {
|
||||
cwv_rect(x, y, w, h, ox, oy)
|
||||
} else {
|
||||
cwv_rect(CWV_PARK, CWV_PARK, w, h, 0.0, 0.0)
|
||||
};
|
||||
if let Err(e) = wv.set_bounds(rect) {
|
||||
cwv_log(&app, &format!("bounds:err label={} err={}", label, e));
|
||||
return Err(e.to_string());
|
||||
}
|
||||
// 页面缩放:只在渲染层判定「该改了」时才带过来,避免每条消息都重排一次
|
||||
if let Some(z) = zoom {
|
||||
if let Err(e) = wv.set_zoom(z) {
|
||||
cwv_log(&app, &format!("bounds:zoom-err label={} zoom={} err={}", label, z, e));
|
||||
}
|
||||
}
|
||||
// 圆角:缩放变了(半径要同比缩放)或用户改了「外观设置 → 节点圆角」时重设。
|
||||
// 两个条件都由渲染层判定,正常拖动时这里是 None,不会每帧跨线程投递。
|
||||
if zoom.is_some() || radius.is_some() {
|
||||
cwv_round(&app, &wv, zoom.unwrap_or(1.0), radius);
|
||||
}
|
||||
let n = CWV_BOUNDS_CALLS.fetch_add(1, Ordering::Relaxed);
|
||||
if n < 8 || n % 400 == 0 {
|
||||
cwv_log(
|
||||
&app,
|
||||
&format!(
|
||||
"bounds label={} n={} rect=({:.0},{:.0} {:.0}x{:.0}) visible={} zoom={:?} off=({:.0},{:.0})",
|
||||
label, n, x, y, w, h, visible, zoom, ox, oy
|
||||
),
|
||||
);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn canvas_webview_navigate(app: AppHandle, id: String, url: String) -> Result<bool, String> {
|
||||
let parsed = cwv_parse(&url)?;
|
||||
let label = cwv_label(&id);
|
||||
let Some(wv) = app.get_webview(&label) else {
|
||||
return Err("该节点还没有浏览器".into());
|
||||
};
|
||||
cwv_log(&app, &format!("navigate label={} url={}", label, parsed));
|
||||
wv.navigate(parsed).map_err(|e| e.to_string())?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn canvas_webview_action(app: AppHandle, id: String, action: String) -> Result<bool, String> {
|
||||
let label = cwv_label(&id);
|
||||
let Some(wv) = app.get_webview(&label) else {
|
||||
return Err("该节点还没有浏览器".into());
|
||||
};
|
||||
// 用 eval 而不是注入脚本到页面:这些是宿主发起的历史操作,外部页面无需配合
|
||||
match action.as_str() {
|
||||
"back" => wv.eval("history.back()").map_err(|e| e.to_string())?,
|
||||
"forward" => wv.eval("history.forward()").map_err(|e| e.to_string())?,
|
||||
"reload" => wv.eval("location.reload()").map_err(|e| e.to_string())?,
|
||||
// 加载中把 ⟳ 变成「停止」:只中断当前请求,不销毁视图(销毁会丢滚动位置)
|
||||
"stop" => wv.eval("window.stop()").map_err(|e| e.to_string())?,
|
||||
"close" => {
|
||||
let _ = wv.close();
|
||||
}
|
||||
other => return Err(format!("未知操作:{}", other)),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn canvas_webview_state(app: AppHandle, id: String) -> Result<serde_json::Value, String> {
|
||||
match app.get_webview(&cwv_label(&id)) {
|
||||
Some(wv) => Ok(serde_json::json!({
|
||||
"open": true,
|
||||
"url": wv.url().map(|u| u.to_string()).unwrap_or_default()
|
||||
})),
|
||||
None => Ok(serde_json::json!({ "open": false, "url": "" })),
|
||||
}
|
||||
}
|
||||
|
||||
// 退出 / 切工作区时回收所有子 webview(label 前缀 cwv-)。
|
||||
#[tauri::command]
|
||||
fn canvas_webview_close_all(app: AppHandle) -> Result<u32, String> {
|
||||
let labels: Vec<String> = app
|
||||
.webviews()
|
||||
.keys()
|
||||
.filter(|k| k.starts_with(CWV_PREFIX))
|
||||
.cloned()
|
||||
.collect();
|
||||
let mut n = 0u32;
|
||||
for label in labels {
|
||||
if let Some(wv) = app.get_webview(&label) {
|
||||
if wv.close().is_ok() {
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
cwv_log(&app, &format!("close_all closed={}", n));
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn notify_desktop(app: tauri::AppHandle, title: String, body: String) -> Result<bool, String> {
|
||||
use tauri_plugin_notification::NotificationExt;
|
||||
match app.notification().builder().title(title).body(body).show() {
|
||||
Ok(_) => Ok(true),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
let app = tauri::Builder::default()
|
||||
.plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| {
|
||||
// 第二次启动:聚焦已有窗口(多实例同时写同一个资料目录会把 data.json 写坏)
|
||||
if let Some(w) = app.get_window("main") {
|
||||
let _ = w.show();
|
||||
let _ = w.unminimize();
|
||||
let _ = w.set_focus();
|
||||
}
|
||||
}))
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.plugin(tauri_plugin_http::init())
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.invoke_handler(tauri::generate_handler![open_app_data_dir, grant_dir, copy_tree])
|
||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
||||
.invoke_handler(tauri::generate_handler![open_app_data_dir, grant_dir, copy_tree, check_update, install_update, clipboard_read_image, clipboard_write_image, clipboard_write_text, clipboard_read_text, open_external_url, open_browser_window, browser_control, browser_state, canvas_webview_ensure, canvas_webview_bounds, canvas_webview_navigate, canvas_webview_action, canvas_webview_state, canvas_webview_close_all, canvas_webview_metrics, notify_desktop])
|
||||
.setup(|app| {
|
||||
if cfg!(debug_assertions) {
|
||||
app.handle().plugin(
|
||||
@@ -220,20 +840,30 @@ pub fn run() {
|
||||
.build(),
|
||||
)?;
|
||||
}
|
||||
// 恢复上次窗口大小/位置
|
||||
if let Some(win) = app.get_webview_window("main") {
|
||||
restore_geom(&win, app.handle());
|
||||
}
|
||||
// 恢复上次窗口大小/位置(主窗口下限与 tauri.conf 的 minWidth/minHeight 对齐)
|
||||
restore_geom(app.handle(), "main", 1024, 640);
|
||||
build_tray(app.handle())?;
|
||||
// macOS 必须有应用菜单,否则 Cmd+C / Cmd+V / Cmd+X 根本不会进 WebView(Tauri 已知问题)
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let menu = tauri::menu::Menu::default(app.handle())?;
|
||||
app.set_menu(menu)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
// 点关闭按钮 ⇒ 记住窗口尺寸后收进托盘(不退出,后台任务继续)
|
||||
.on_window_event(|window, event| {
|
||||
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||
let label = window.label();
|
||||
// 主窗口之外(browser 等)正常关闭:先记几何,再放行销毁。
|
||||
// 这一步不能省 —— 否则外部网页会「点 ✕ 只是隐藏」,在后台继续跑,
|
||||
// 用户再也关不掉,只能 Cmd+Q 退整个应用。
|
||||
if label != "main" {
|
||||
save_geom(window.app_handle(), label);
|
||||
return;
|
||||
}
|
||||
save_geom(window.app_handle(), "main");
|
||||
if !QUITTING.load(Ordering::SeqCst) {
|
||||
if let Some(w) = window.app_handle().get_webview_window("main") {
|
||||
save_geom(&w);
|
||||
}
|
||||
api.prevent_close();
|
||||
let _ = window.hide();
|
||||
}
|
||||
@@ -245,9 +875,7 @@ pub fn run() {
|
||||
app.run(|app_handle, event| {
|
||||
// Cmd+Q / 系统退出时也把当前窗口尺寸落盘
|
||||
if let tauri::RunEvent::ExitRequested { .. } = event {
|
||||
if let Some(w) = app_handle.get_webview_window("main") {
|
||||
save_geom(&w);
|
||||
}
|
||||
save_geom(app_handle, "main");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "image-workbench",
|
||||
"version": "3.25.0",
|
||||
"version": "3.25.30",
|
||||
"identifier": "com.malongan.imageworkbench",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
@@ -25,7 +25,7 @@
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; script-src 'self' blob:; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost https: blob: data: http://127.0.0.1:30092 http://localhost:30092 http://127.0.0.1:3425 http://localhost:3425; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"
|
||||
"csp": "default-src 'self'; script-src 'self' blob:; worker-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; font-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost https: blob: data: http://127.0.0.1:30092 http://localhost:30092; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
@@ -40,6 +40,15 @@
|
||||
"icons/[email protected]",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
],
|
||||
"createUpdaterArtifacts": true
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"endpoints": [
|
||||
"https://download.maqiart.eu.org/updates/latest.json"
|
||||
],
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDE3QUU1N0QwQUM5RjE1RjEKUldUeEZaK3MwRmV1RnhjNVhhSlhaSHkvbVRXNDdscHpOa0s0VHF4NHBBQVJBdDQ0dEVlck5FeEsK"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"bundle": {
|
||||
"targets": [
|
||||
"app",
|
||||
"dmg"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"bundle": {
|
||||
"targets": [
|
||||
"nsis"
|
||||
]
|
||||
},
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"endpoints": [
|
||||
"https://download.maqiart.eu.org/updates/latest-windows.json"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,713 @@
|
||||
/* canvas-webview.js — 画布内嵌浏览器(原生子 webview)的位置同步引擎
|
||||
*
|
||||
* 为什么需要它:网页由 Tauri 的 `Window::add_child` 创建为**主窗口的原生子视图**,
|
||||
* 完全不受 CSS 约束 —— 画布平移/缩放、节点被拖动时它自己不会动,必须由渲染层把
|
||||
* 「节点内容区在窗口里的矩形」算出来推给 Rust。
|
||||
*
|
||||
* 契约:插件节点在内容区放一个空 div:
|
||||
* <div data-iwb-cwv="<nodeId>" data-iwb-cwv-url="https://..." data-iwb-cwv-zoom="1">
|
||||
* 本模块自己发现它(MutationObserver + isConnected 双保险),宿主零侵入。
|
||||
*
|
||||
* ── v3.25.29:坐标原点差(这一版最关键的修复)────────────────────────────────
|
||||
* `add_child`/`set_bounds` 的 LogicalPosition 以**窗口边框**左上角为原点,
|
||||
* 而 `getBoundingClientRect()` 以**内容视图**左上角为原点。macOS 标准标题栏下差 32pt
|
||||
* ⇒ 每个画布网页都整体上浮 32px,正好盖住地址栏与前进/后退/刷新按钮。
|
||||
* 修法:向 Rust 要窗口边框尺寸,减去 `window.innerHeight` 得到偏移,推 rect 时补上
|
||||
* (全屏时标题栏消失,差值自动回到 0)。
|
||||
*
|
||||
* ── v3.25.28:不再「动就藏」────────────────────────────────────────────────────
|
||||
* 老实现只要单帧变化 > 18px 就先隐藏、停 140ms 再显示;交集 < 64×48 也整块隐藏。
|
||||
* 于是「缩放画布 / 拖缩放手柄 / 移动节点」必然白屏,且只有某个缩放区间能看见。
|
||||
* 现在只有三种情况隐藏:画布被切走、模态遮罩、节点完全离开画布(交集 < 2px)。
|
||||
*
|
||||
* 隐藏 = 把视图停到窗口外(Rust 侧 CWV_PARK),**绝不调 show()/hide()** ——
|
||||
* macOS 上子 webview hide 之后再 show 会静默失效(两个调用都返回 Ok,网页永久不绘制)。
|
||||
*
|
||||
* 缩放:页面 zoom = 画布缩放 × 用户缩放。页面 CSS 像素随之缩放,网页就像图片一样
|
||||
* 跟着画布一起放大缩小,而不是一直按原宽度重排(用户反馈「缩小后内容不缩小」)。
|
||||
*/
|
||||
(function (global) {
|
||||
'use strict'
|
||||
if (!global || global.IWBCanvasWebview) return
|
||||
|
||||
var ATTR = 'data-iwb-cwv'
|
||||
var ATTR_URL = 'data-iwb-cwv-url'
|
||||
var ATTR_ZOOM = 'data-iwb-cwv-zoom'
|
||||
var EPS = 0.5 // 与已推值比较的浮点容差
|
||||
var OBS_EPS = 0.2 // 判断「rect 真的变了」的容差
|
||||
var PUSH_GAP_MS = 40 // 同一节点两次推送的最小间隔(≈25fps,跟手又不洪泛)
|
||||
var SIZE_IDLE_MS = 100 // 尺寸变化后静止多久就推最终值
|
||||
var ZOOM_GAP_MS = 120 // 缩放变化的最小推送间隔(每次 set_zoom 都会让页面重排)
|
||||
var MIN_EDGE = 2 // 交集小于这个视为完全离开画布
|
||||
// 右/下各留 6px:节点缩放手柄(.iwb-resize,right/bottom:-6px)要露出来才点得到。
|
||||
// 做成常量而不是「选中时内缩」,否则每次点选都会让网页重排一次。
|
||||
var GUTTER = 6
|
||||
var BLOCK_SELECTOR = '.iwb-modal-mask,.iwb-imgpreview,.iwb-prompt-modal'
|
||||
var CLOSE_GRACE_MS = 900
|
||||
var LOAD_TIMEOUT_MS = 15000
|
||||
var TICK_MS = 32
|
||||
var ZOOM_MIN = 0.2
|
||||
var ZOOM_MAX = 3
|
||||
// 休眠:每个网页节点是一个独立 WebKit 进程(几十~几百 MB)。开过几个节点后它们会一直
|
||||
// 挂在后台,哪怕节点早已滚出画布。持续不可见超过这个时长就释放视图(回来时按原地址
|
||||
// 重建,代价是网页重新加载)。5 分钟:切去别的画布干一会儿再回来不受影响,
|
||||
// 真正放着不看的才会被回收。
|
||||
var SLEEP_MS = 300000
|
||||
|
||||
var invoke
|
||||
function inv() {
|
||||
if (invoke !== undefined) return invoke
|
||||
var T = global.__TAURI__
|
||||
invoke = (T && T.core && typeof T.core.invoke === 'function') ? T.core.invoke : null
|
||||
return invoke
|
||||
}
|
||||
|
||||
function log() {
|
||||
if (global.console && global.console.debug) {
|
||||
try { global.console.debug.apply(global.console, arguments) } catch (e) { /* 忽略 */ }
|
||||
}
|
||||
}
|
||||
|
||||
// 命令失败原因(命令名 → 文案)。Tauri 的拒约值就是 Rust 侧 Err(String) 原文,
|
||||
// 正好可以贴进节点当诊断信息。
|
||||
var lastErr = {}
|
||||
function errText(e) {
|
||||
if (!e) return '未知错误'
|
||||
if (typeof e === 'string') return e
|
||||
if (e.message) return String(e.message)
|
||||
return String(e)
|
||||
}
|
||||
function call(cmd, args) {
|
||||
var f = inv()
|
||||
if (!f) return Promise.resolve(null)
|
||||
try {
|
||||
return Promise.resolve(f(cmd, args)).then(function (v) {
|
||||
delete lastErr[cmd]
|
||||
return v
|
||||
}).catch(function (e) {
|
||||
lastErr[cmd] = errText(e)
|
||||
log('[canvas-webview]', cmd, 'failed:', lastErr[cmd])
|
||||
return null
|
||||
})
|
||||
} catch (e) {
|
||||
lastErr[cmd] = errText(e)
|
||||
log('[canvas-webview]', cmd, 'threw:', lastErr[cmd])
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
}
|
||||
|
||||
var anchors = new Map()
|
||||
var pendingClose = new Map()
|
||||
var rafId = 0
|
||||
var lastTick = 0
|
||||
var started = false
|
||||
|
||||
// ── 原生层与 DOM 的坐标原点差 ────────────────────────────────────────────────
|
||||
// 只在拿到窗口边框尺寸后才能算,没算出来之前不建视图(否则会先闪一下错位)。
|
||||
var off = { x: 0, y: 0, ready: false, askedAt: 0 }
|
||||
|
||||
function refreshOffsets() {
|
||||
off.askedAt = Date.now()
|
||||
return call('canvas_webview_metrics', {}).then(function (m) {
|
||||
if (!m || !isFinite(m.frameH)) return
|
||||
var iw = global.innerWidth || 0
|
||||
var ih = global.innerHeight || 0
|
||||
// 边框 - 内容 = 标题栏(全屏时为 0)。容差 2px:macOS 边框有 0.5pt 的取整
|
||||
var dx = Math.round(m.frameW - iw)
|
||||
var dy = Math.round(m.frameH - ih)
|
||||
if (!(dx >= 0 && dx < 40)) dx = 0
|
||||
if (!(dy >= 0 && dy < 120)) dy = 0
|
||||
var changed = (dx !== off.x || dy !== off.y)
|
||||
off.x = dx
|
||||
off.y = dy
|
||||
off.ready = true
|
||||
if (changed) {
|
||||
log('[canvas-webview] 坐标补偿', dx, dy)
|
||||
// 偏移变了:所有视图按旧偏移摆着,必须强制重推一次
|
||||
anchors.forEach(function (st) {
|
||||
st.px = NaN; st.py = NaN; st.pw = NaN; st.ph = NaN; st.shown = null
|
||||
st.pz = NaN
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 画布当前缩放:.iwb-world 上是 transform: translate(...) scale(s)
|
||||
function canvasScale() {
|
||||
var wl
|
||||
try { wl = document.querySelector('.iwb-world') } catch (e) { return 1 }
|
||||
if (!wl) return 1
|
||||
var t
|
||||
try { t = global.getComputedStyle(wl).transform } catch (e) { return 1 }
|
||||
if (!t || t === 'none') return 1
|
||||
// matrix(a,b,c,d,e,f) 或 matrix3d(...),第一个分量都是 x 方向缩放
|
||||
var m = /^matrix(3d)?\(([^)]+)\)/.exec(t)
|
||||
if (!m) return 1
|
||||
var a = parseFloat(m[2].split(',')[0])
|
||||
return (a > 0.02 && a < 8) ? a : 1
|
||||
}
|
||||
|
||||
// 节点圆角的当前值:「外观设置 → 节点圆角」由 ui-appearance 直接写到 documentElement
|
||||
// 的内联样式上(--iwb-node-radius)。读内联 style 不触发样式重算,每帧问一次也没成本;
|
||||
// 只有内联还没写过(首次启动,值来自样式表)时才走一次 getComputedStyle 并缓存。
|
||||
var radiusCached = 0
|
||||
function radiusNow() {
|
||||
var root = document.documentElement
|
||||
var v = ''
|
||||
try { v = (root.style && root.style.getPropertyValue('--iwb-node-radius')) || '' } catch (e) { v = '' }
|
||||
if (!v) {
|
||||
if (radiusCached) return radiusCached
|
||||
try { v = global.getComputedStyle(root).getPropertyValue('--iwb-node-radius') || '' } catch (e) { v = '' }
|
||||
}
|
||||
var n = parseFloat(v)
|
||||
if (!(isFinite(n) && n > 0)) return 14
|
||||
if (!radiusCached) radiusCached = n
|
||||
return n
|
||||
}
|
||||
|
||||
function canvasRect() {
|
||||
var el = document.querySelector('.iwb-canvas')
|
||||
if (!el) return null
|
||||
// 画布被工作区切走时是 visibility:hidden,rect 还在但内容不可见
|
||||
if (el.classList && el.classList.contains('iwb-canvas-hidden')) return null
|
||||
var r = el.getBoundingClientRect()
|
||||
if (r.width < MIN_EDGE || r.height < MIN_EDGE) return null
|
||||
return r
|
||||
}
|
||||
|
||||
// 模态/预览挡在画布上时把网页藏起来。只认「真的可见」的遮罩:
|
||||
// 这类元素关闭后常以 display:none 留在 DOM 里,按存在判断会让网页永远不显示。
|
||||
function blocked() {
|
||||
var list
|
||||
try {
|
||||
list = document.querySelectorAll(BLOCK_SELECTOR)
|
||||
} catch (e) {
|
||||
return false
|
||||
}
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
var n = list[i]
|
||||
if (!n || !n.isConnected) continue
|
||||
var r = n.getBoundingClientRect()
|
||||
if (r.width >= 8 && r.height >= 8) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 原生层没建起来时那块区域本来是一片空白,用户分不清「在加载」和「坏了」。
|
||||
// 把原因直接写在锚点里,问题就能自解释。
|
||||
function hint(st, msg, color) {
|
||||
var el = st.el
|
||||
if (!el) return
|
||||
if (!msg) {
|
||||
if (st.hintEl && st.hintEl.parentNode) st.hintEl.parentNode.removeChild(st.hintEl)
|
||||
st.hintEl = null
|
||||
return
|
||||
}
|
||||
if (!st.hintEl || st.hintEl.parentNode !== el) {
|
||||
var d = document.createElement('div')
|
||||
d.setAttribute('data-iwb-cwv-hint', '')
|
||||
d.style.cssText = 'position:absolute;inset:0;display:flex;align-items:center;justify-content:center;'
|
||||
+ 'padding:16px;text-align:center;font-size:12px;line-height:1.7;white-space:pre-line;'
|
||||
+ 'background:rgba(128,128,128,.08);pointer-events:none;z-index:2'
|
||||
st.hintEl = d
|
||||
el.appendChild(d)
|
||||
}
|
||||
st.hintEl.style.color = color || '#e05252'
|
||||
st.hintEl.textContent = msg
|
||||
}
|
||||
|
||||
// 把网页状态(加载中 / 当前地址 / 失败)广播给插件节点,让它更新地址栏与按钮。
|
||||
// 插件拿不到子 webview 的任何事件,这是唯一的通道;监听不到就只是不显示加载态。
|
||||
function emitState(st, extra) {
|
||||
var detail = {
|
||||
id: st.id,
|
||||
loading: !!st.loading,
|
||||
url: st.pageUrl || st.openUrl || '',
|
||||
failed: !!st.failed,
|
||||
}
|
||||
if (extra) for (var k in extra) detail[k] = extra[k]
|
||||
try {
|
||||
var ev = new global.CustomEvent('iwb-cwv-state', { detail: detail })
|
||||
document.dispatchEvent(ev)
|
||||
} catch (e) { /* 老环境没有 CustomEvent:忽略 */ }
|
||||
}
|
||||
|
||||
function readOf(el) {
|
||||
return {
|
||||
id: el.getAttribute(ATTR) || '',
|
||||
url: el.getAttribute(ATTR_URL) || '',
|
||||
zoom: parseFloat(el.getAttribute(ATTR_ZOOM) || '1'),
|
||||
// 2026-11-19:面板内嵌浏览器。scope=panel 的锚点不吃画布裁剪、不乘画布缩放 ——
|
||||
// 它就是面板里的一个普通容器(库面板「浏览器」页签)。
|
||||
scope: el.getAttribute('data-iwb-cwv-scope') === 'panel' ? 'panel' : 'canvas',
|
||||
}
|
||||
}
|
||||
|
||||
function makeState(el) {
|
||||
return {
|
||||
id: '',
|
||||
scope: 'canvas',
|
||||
el: el,
|
||||
open: false, // Rust 侧子 webview 是否已创建
|
||||
pending: false, // ensure 请求在飞
|
||||
retryAt: 0, // 创建失败后的重试时刻
|
||||
shown: null, // 上一次推的 visible(null = 还没推过)
|
||||
url: '', // 锚点上的地址(用户想要的)
|
||||
openUrl: '', // 已生效到 webview 的地址
|
||||
pageUrl: '', // 网页自己报告的当前地址(跟随站内跳转)
|
||||
loading: false,
|
||||
failed: false,
|
||||
px: NaN, py: NaN, pw: NaN, ph: NaN, // 上一次推的矩形
|
||||
pz: NaN, // 上一次推的页面缩放
|
||||
pr: NaN, // 上一次推的圆角基数(外观设置里的节点圆角)
|
||||
hiddenAt: 0, // 从哪一刻起持续不可见(0 = 当前可见)
|
||||
lastZoomPush: 0,
|
||||
obsX: NaN, obsY: NaN, obsW: NaN, obsH: NaN, // 上一次观察到的实际矩形
|
||||
changedAt: 0, // 实际矩形最后一次变化的时间
|
||||
lastPush: 0,
|
||||
hintEl: null,
|
||||
openedAt: 0,
|
||||
loaded: false,
|
||||
warned: false,
|
||||
}
|
||||
}
|
||||
|
||||
function attach(el) {
|
||||
var info = readOf(el)
|
||||
if (!info.id) return
|
||||
var prev = anchors.get(info.id)
|
||||
if (prev && prev.el === el) return
|
||||
var pc = pendingClose.get(info.id)
|
||||
if (pc) { clearTimeout(pc); pendingClose.delete(info.id) }
|
||||
// 同一个节点换了 DOM(React 重建节点体):沿用旧状态,避免重复建 webview、丢滚动位置
|
||||
var st = makeState(el)
|
||||
st.id = info.id
|
||||
st.scope = info.scope
|
||||
if (prev) {
|
||||
st.open = prev.open
|
||||
st.url = prev.url
|
||||
st.openUrl = prev.openUrl
|
||||
st.pageUrl = prev.pageUrl
|
||||
st.shown = prev.shown
|
||||
st.px = prev.px; st.py = prev.py; st.pw = prev.pw; st.ph = prev.ph
|
||||
st.pz = prev.pz; st.lastZoomPush = prev.lastZoomPush
|
||||
st.pr = prev.pr
|
||||
st.hiddenAt = prev.hiddenAt
|
||||
st.obsX = prev.obsX; st.obsY = prev.obsY; st.obsW = prev.obsW; st.obsH = prev.obsH
|
||||
st.changedAt = prev.changedAt
|
||||
st.lastPush = prev.lastPush
|
||||
st.openedAt = prev.openedAt
|
||||
st.loaded = prev.loaded
|
||||
st.loading = prev.loading
|
||||
}
|
||||
anchors.set(info.id, st)
|
||||
}
|
||||
|
||||
function detach(id, st) {
|
||||
if (!st) return
|
||||
anchors.delete(id)
|
||||
if (!st.open) return
|
||||
var prev = pendingClose.get(id)
|
||||
if (prev) clearTimeout(prev)
|
||||
// 宽限窗口:LOD 降级 / React 重建节点体会让锚点短暂消失,立刻 close 会导致
|
||||
// 「缩远一点再缩回来,网页重新加载、滚动位置丢光」。
|
||||
var t = setTimeout(function () {
|
||||
pendingClose.delete(id)
|
||||
if (anchors.has(id)) return
|
||||
call('canvas_webview_action', { id: id, action: 'close' })
|
||||
}, CLOSE_GRACE_MS)
|
||||
pendingClose.set(id, t)
|
||||
}
|
||||
|
||||
function push(st, x, y, w, h, visible, zoom) {
|
||||
st.px = x; st.py = y; st.pw = w; st.ph = h; st.shown = visible
|
||||
st.lastPush = Date.now()
|
||||
if (zoom != null) { st.pz = zoom; st.lastZoomPush = st.lastPush }
|
||||
// 圆角只在「值真的变了」时才带:用户拖了「外观设置 → 节点圆角」立刻生效,
|
||||
// 平时移动/缩放节点这里是 null,不额外投递跨线程调用。
|
||||
// 只在可见时推 —— 半径要乘 zoom 才有意义,park 状态下没有可信的 zoom。
|
||||
var sendR = null
|
||||
if (visible) {
|
||||
var rad = radiusNow()
|
||||
if (!isFinite(st.pr) || Math.abs(rad - st.pr) > 0.5) { sendR = rad; st.pr = rad }
|
||||
}
|
||||
// 半径要乘 zoom 才有意义,所以「只有半径变了」时把当前 zoom 一起带上
|
||||
var z = zoom
|
||||
if (z == null && sendR != null) z = isFinite(st.pz) ? st.pz : 1
|
||||
call('canvas_webview_bounds', {
|
||||
id: st.id, x: x, y: y, w: w, h: h, visible: visible,
|
||||
zoom: z == null ? null : z, radius: sendR, ox: off.x, oy: off.y,
|
||||
}).then(function (r) {
|
||||
// Rust 侧没有这个 webview(被 close / 进程重建)⇒ 回滚,让下一轮重新 ensure
|
||||
if (r === false) {
|
||||
st.open = false
|
||||
st.shown = null
|
||||
st.px = NaN; st.py = NaN; st.pw = NaN; st.ph = NaN
|
||||
st.pz = NaN
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 释放视图但保留 URL:不可见太久(休眠)或用户主动关闭时用。
|
||||
// 下一次可见时 tick 会走 ensure 按 st.url 重建。
|
||||
function dropView(st) {
|
||||
call('canvas_webview_action', { id: st.id, action: 'close' })
|
||||
st.open = false
|
||||
st.shown = null
|
||||
st.pending = false
|
||||
st.pz = NaN
|
||||
st.pr = NaN
|
||||
st.px = NaN; st.py = NaN; st.pw = NaN; st.ph = NaN
|
||||
st.loaded = false
|
||||
st.loading = false
|
||||
st.openedAt = 0
|
||||
st.hiddenAt = 0
|
||||
}
|
||||
|
||||
function ensure(st, x, y, w, h, zoom) {
|
||||
if (!st.url || st.pending) return
|
||||
if (st.retryAt && Date.now() < st.retryAt) return
|
||||
st.pending = true
|
||||
var want = st.url
|
||||
var rad = radiusNow()
|
||||
call('canvas_webview_ensure', {
|
||||
id: st.id, url: want, x: x, y: y, w: w, h: h,
|
||||
ox: off.x, oy: off.y, zoom: zoom, radius: rad,
|
||||
}).then(function (r) {
|
||||
st.pending = false
|
||||
if (r === null) {
|
||||
// 失败必须回滚 open(早先的实现先置 open=true 再请求,一次失败就永久卡在
|
||||
// 「已创建」,之后只推 bounds,而 Rust 侧根本没有 webview ⇒ 重启才恢复)
|
||||
st.open = false
|
||||
st.shown = null
|
||||
st.pz = NaN
|
||||
st.retryAt = Date.now() + 1500
|
||||
st.failed = true
|
||||
hint(st, '画布网页启动失败:' + (lastErr.canvas_webview_ensure || '未知原因') + '\n(1.5 秒后自动重试)')
|
||||
emitState(st)
|
||||
return
|
||||
}
|
||||
st.open = true
|
||||
st.shown = true
|
||||
st.openUrl = want
|
||||
st.px = x; st.py = y; st.pw = w; st.ph = h
|
||||
st.pz = zoom
|
||||
st.pr = rad
|
||||
st.lastPush = Date.now()
|
||||
st.lastZoomPush = st.lastPush
|
||||
st.openedAt = Date.now()
|
||||
st.loaded = false
|
||||
st.warned = false
|
||||
st.failed = false
|
||||
st.loading = true
|
||||
hint(st, '')
|
||||
emitState(st)
|
||||
})
|
||||
}
|
||||
|
||||
// 长时间不可见 ⇒ 释放视图省内存。返回 true 表示这一帧已经释放,调用方不必再推 bounds。
|
||||
function sleepIfIdle(st, now) {
|
||||
if (!st.open) return false
|
||||
if (!st.hiddenAt) { st.hiddenAt = now; return false }
|
||||
if (now - st.hiddenAt > SLEEP_MS) { dropView(st); return true }
|
||||
return false
|
||||
}
|
||||
|
||||
// Rust 侧 page load 事件:判断网页到底有没有加载出来,并把站内跳转同步到地址栏
|
||||
function onPage(ev) {
|
||||
var p = (ev && ev.payload) || {}
|
||||
var st = anchors.get(p.id)
|
||||
if (!st) return
|
||||
if (p.kind === 'started') {
|
||||
st.loading = true
|
||||
st.pageUrl = p.url || st.pageUrl
|
||||
st.openedAt = Date.now()
|
||||
emitState(st)
|
||||
return
|
||||
}
|
||||
if (p.kind === 'finished') {
|
||||
st.loaded = true
|
||||
st.loading = false
|
||||
st.warned = false
|
||||
st.failed = false
|
||||
if (p.url) st.pageUrl = p.url
|
||||
hint(st, '')
|
||||
emitState(st)
|
||||
}
|
||||
}
|
||||
|
||||
// 把锚点矩形收敛到「节点内容区」:上不能压地址栏,四边不能出节点框。
|
||||
// 原生层压在所有 DOM 之上,一旦算大了就会吃掉工具栏的点击 —— 这里兜住,
|
||||
// 即使插件布局将来变了也不会把按钮盖死。
|
||||
function contentOf(el, r) {
|
||||
var node = null
|
||||
try { node = el.closest && el.closest('.iwb-node') } catch (e) { node = null }
|
||||
if (!node) return r
|
||||
var nr = node.getBoundingClientRect()
|
||||
var top = nr.top + 1
|
||||
var bar = null
|
||||
try { bar = node.querySelector('.iwb-cwv-bar') } catch (e) { bar = null }
|
||||
if (bar) {
|
||||
var br = bar.getBoundingClientRect()
|
||||
if (br.height >= 4) top = Math.max(top, br.bottom + 1)
|
||||
}
|
||||
var left = Math.max(r.left, nr.left + 1)
|
||||
var right = Math.min(Math.max(r.right, left), nr.right - GUTTER)
|
||||
var bottom = Math.min(Math.max(r.bottom, top), nr.bottom - GUTTER)
|
||||
return {
|
||||
left: left,
|
||||
top: Math.max(r.top, top),
|
||||
right: right,
|
||||
bottom: bottom,
|
||||
width: Math.max(0, right - left),
|
||||
height: Math.max(0, bottom - Math.max(r.top, top)),
|
||||
}
|
||||
}
|
||||
|
||||
function tick(ts) {
|
||||
rafId = global.requestAnimationFrame(tick)
|
||||
if (!anchors.size) return
|
||||
if (ts - lastTick < TICK_MS) return
|
||||
lastTick = ts
|
||||
// 偏移还没算出来就不建视图:宁可晚两帧,也不要先闪一下错位
|
||||
if (!off.ready) {
|
||||
if (Date.now() - off.askedAt > 500) refreshOffsets()
|
||||
return
|
||||
}
|
||||
// 窗口尺寸变化 / 全屏切换会让标题栏高度变,定期对一次(成本是一条 IPC)
|
||||
if (Date.now() - off.askedAt > 3000) refreshOffsets()
|
||||
|
||||
var cr = canvasRect()
|
||||
var hide = blocked()
|
||||
var now = Date.now()
|
||||
var cs = canvasScale()
|
||||
// 圆角设置(全局一个值):每帧算一次,循环里各节点比对
|
||||
var rad = radiusNow()
|
||||
|
||||
// 面板内嵌浏览器:它是普通 DOM 浮层,而原生网页视图永远在主窗口最上层 ⇒
|
||||
// 与面板矩形**相交**的画布节点必须 park,否则节点会盖在面板上。
|
||||
// 只按相交判断(2026-11-19 改):面板在左侧栏,画布节点多数在右侧,早先「有一个
|
||||
// 面板就整体 park」会让面板里点「↗ 放到画布」后新节点一片空白,看起来像失败了。
|
||||
var panelRect = null
|
||||
anchors.forEach(function (s) {
|
||||
if (s.scope !== 'panel' || !s.el || !s.el.isConnected) return
|
||||
var rr = s.el.getBoundingClientRect()
|
||||
if (rr.width >= MIN_EDGE && rr.height >= MIN_EDGE) panelRect = rr
|
||||
})
|
||||
function overPanel(r) {
|
||||
if (!panelRect) return false
|
||||
return r.left < panelRect.right && r.right > panelRect.left && r.top < panelRect.bottom && r.bottom > panelRect.top
|
||||
}
|
||||
|
||||
anchors.forEach(function (st, id) {
|
||||
var el = st.el
|
||||
st.id = id
|
||||
if (!el || !el.isConnected) {
|
||||
var fresh = document.querySelector('[' + ATTR + '="' + id + '"]')
|
||||
if (fresh) { st.el = fresh; el = fresh; st.hintEl = null } else { detach(id, st); return }
|
||||
}
|
||||
|
||||
var info = readOf(el)
|
||||
st.url = info.url
|
||||
|
||||
// 用户点了 ✕(插件把 paused 写到锚点上):关掉视图并保持关闭,
|
||||
// 否则宿主会因为「没有视图」立刻重建,✕ 等于点了没反应。
|
||||
if (el.getAttribute('data-iwb-cwv-paused') === '1') {
|
||||
st.url = ''
|
||||
st.hiddenAt = 0
|
||||
if (st.open) dropView(st)
|
||||
return
|
||||
}
|
||||
var uz = (isFinite(info.zoom) && info.zoom > 0) ? info.zoom : 1
|
||||
var isPanel = st.scope === 'panel'
|
||||
// 画布锚点:页面缩放 = 用户缩放 × 画布缩放;面板锚点:只有用户缩放(面板不跟画布缩放)
|
||||
var zoom = Math.round(Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, isPanel ? uz : uz * cs)) * 1000) / 1000
|
||||
|
||||
// 画布不可见(切工作区等):park 一次就够,不要每帧发
|
||||
if (!isPanel && !cr) {
|
||||
if (st.open && !sleepIfIdle(st, now) && st.shown !== false) {
|
||||
push(st,
|
||||
isFinite(st.px) ? st.px : 0, isFinite(st.py) ? st.py : 0,
|
||||
isFinite(st.pw) ? st.pw : MIN_EDGE, isFinite(st.ph) ? st.ph : MIN_EDGE, false, null)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var base = el.getBoundingClientRect()
|
||||
var r = isPanel ? base : contentOf(el, base)
|
||||
|
||||
// 与面板重叠的部分会被面板挡住,整块 park(原生层没法做部分遮挡)
|
||||
if (!isPanel && overPanel(r)) {
|
||||
if (st.open && !sleepIfIdle(st, now) && st.shown !== false) {
|
||||
push(st,
|
||||
isFinite(st.px) ? st.px : r.left, isFinite(st.py) ? st.py : r.top,
|
||||
isFinite(st.pw) ? st.pw : MIN_EDGE, isFinite(st.ph) ? st.ph : MIN_EDGE, false, null)
|
||||
}
|
||||
return
|
||||
}
|
||||
var vw = global.innerWidth || 0
|
||||
var vh = global.innerHeight || 0
|
||||
|
||||
// 裁到「节点 ∩ 画布」/「面板 ∩ 视口」:子 webview 是原生层,容器的 overflow:hidden
|
||||
// 对它无效,不裁会直接盖住侧边栏并吃掉那边的鼠标事件。裁剪只改矩形,不做任何隐藏。
|
||||
var x, y, w, h
|
||||
if (isPanel) {
|
||||
x = Math.max(r.left, 0)
|
||||
y = Math.max(r.top, 0)
|
||||
w = Math.min(r.right, vw) - x
|
||||
h = Math.min(r.bottom, vh) - y
|
||||
} else {
|
||||
x = Math.max(r.left, cr.left)
|
||||
y = Math.max(r.top, cr.top)
|
||||
w = Math.min(r.right, cr.right) - x
|
||||
h = Math.min(r.bottom, cr.bottom) - y
|
||||
}
|
||||
var visible = !hide && w >= MIN_EDGE && h >= MIN_EDGE
|
||||
|
||||
// 记录「实际矩形最后一次变化」的时刻——尺寸推送要等它静止
|
||||
if (!isFinite(st.obsW) || Math.abs(w - st.obsW) > OBS_EPS || Math.abs(h - st.obsH) > OBS_EPS
|
||||
|| Math.abs(x - st.obsX) > OBS_EPS || Math.abs(y - st.obsY) > OBS_EPS) {
|
||||
st.obsX = x; st.obsY = y; st.obsW = w; st.obsH = h
|
||||
st.changedAt = now
|
||||
}
|
||||
|
||||
if (!visible) {
|
||||
if (st.open && !sleepIfIdle(st, now) && st.shown !== false) {
|
||||
push(st, isFinite(st.px) ? st.px : x, isFinite(st.py) ? st.py : y,
|
||||
isFinite(st.pw) ? st.pw : w, isFinite(st.ph) ? st.ph : h, false, null)
|
||||
}
|
||||
return
|
||||
}
|
||||
st.hiddenAt = 0
|
||||
|
||||
// 用户改了「外观设置 → 节点圆角」:位置/尺寸/缩放都没动,但半径只随 bounds 下发,
|
||||
// 必须主动重推一次才能立刻看到四角变化(否则要等下一次拖动节点)。
|
||||
if (st.open && (!isFinite(st.pr) || Math.abs(rad - st.pr) > 0.5)) {
|
||||
push(st, x, y, w, h, true, null)
|
||||
return
|
||||
}
|
||||
|
||||
// 用户在节点里换了网址:地址变了才导航
|
||||
if (st.open && st.url && st.openUrl && st.url !== st.openUrl) {
|
||||
st.openUrl = st.url
|
||||
st.pageUrl = st.url
|
||||
st.loaded = false
|
||||
st.warned = false
|
||||
st.failed = false
|
||||
st.loading = true
|
||||
st.openedAt = Date.now()
|
||||
call('canvas_webview_navigate', { id: id, url: st.url })
|
||||
emitState(st)
|
||||
}
|
||||
|
||||
if (!st.open) {
|
||||
ensure(st, x, y, w, h, zoom)
|
||||
return
|
||||
}
|
||||
|
||||
var dPos = !isFinite(st.px) || Math.abs(x - st.px) > EPS || Math.abs(y - st.py) > EPS
|
||||
var dSize = !isFinite(st.pw) || Math.abs(w - st.pw) > EPS || Math.abs(h - st.ph) > EPS
|
||||
var dZoom = !isFinite(st.pz) || Math.abs(zoom - st.pz) > 0.01
|
||||
var zoomOk = dZoom && (now - st.lastZoomPush >= ZOOM_GAP_MS)
|
||||
var gapOk = now - st.lastPush >= PUSH_GAP_MS
|
||||
var idle = now - st.changedAt >= SIZE_IDLE_MS
|
||||
|
||||
if (!gapOk) return
|
||||
if (dSize || dZoom) {
|
||||
// 缩放变化 = 用户在缩放画布/节点,位置尺寸一起推,网页才能跟着画布一起缩
|
||||
if (zoomOk || (dSize && idle)) push(st, x, y, w, h, true, zoomOk ? zoom : null)
|
||||
else if (dPos) push(st, x, y, st.pw, st.ph, true, null)
|
||||
} else if (dPos || st.shown !== true) {
|
||||
push(st, x, y, w, h, true, zoomOk ? zoom : null)
|
||||
}
|
||||
|
||||
// 建起来了但网页一直没加载完:给出可操作提示,而不是让用户盯着一块空白
|
||||
if (st.open && !st.loaded && !st.warned && st.openedAt
|
||||
&& (Date.now() - st.openedAt) > LOAD_TIMEOUT_MS) {
|
||||
st.warned = true
|
||||
st.failed = true
|
||||
st.loading = false
|
||||
hint(st, '网页 15 秒内没有加载完成。\n可能被站点拒绝、证书异常或网络不通。\n可以点上方 ⟳ 重试,或改用左侧「浏览器」面板。', '#e0a252')
|
||||
emitState(st)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function scan(root) {
|
||||
var list
|
||||
try {
|
||||
list = root.querySelectorAll('[' + ATTR + ']')
|
||||
} catch (e) {
|
||||
return
|
||||
}
|
||||
for (var i = 0; i < list.length; i++) attach(list[i])
|
||||
}
|
||||
|
||||
function onMutations(muts) {
|
||||
for (var i = 0; i < muts.length; i++) {
|
||||
var m = muts[i]
|
||||
if (m.type === 'attributes') {
|
||||
if (m.attributeName === ATTR && m.target) attach(m.target)
|
||||
continue
|
||||
}
|
||||
for (var j = 0; j < m.addedNodes.length; j++) {
|
||||
var n = m.addedNodes[j]
|
||||
if (n.nodeType !== 1) continue
|
||||
if (n.hasAttribute && n.hasAttribute(ATTR)) attach(n)
|
||||
if (n.querySelectorAll) scan(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function install() {
|
||||
if (started) return
|
||||
started = true
|
||||
if (!inv()) {
|
||||
// Web 版没有子 webview:模块静默退出,节点里会看到插件的降级提示
|
||||
log('[canvas-webview] 非桌面环境,跳过')
|
||||
return
|
||||
}
|
||||
refreshOffsets()
|
||||
scan(document)
|
||||
var ev = global.__TAURI__ && global.__TAURI__.event
|
||||
if (ev && typeof ev.listen === 'function') {
|
||||
try {
|
||||
var sub = ev.listen('cwv-page', onPage)
|
||||
if (sub && typeof sub.catch === 'function') sub.catch(function () { /* 事件通道不可用就只靠超时提示 */ })
|
||||
} catch (e) { /* 旧客户端没有事件 API */ }
|
||||
}
|
||||
if (global.MutationObserver) {
|
||||
var mo = new MutationObserver(onMutations)
|
||||
mo.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: [ATTR] })
|
||||
}
|
||||
global.addEventListener('resize', function () { refreshOffsets() })
|
||||
rafId = global.requestAnimationFrame(tick)
|
||||
global.addEventListener('beforeunload', function () {
|
||||
if (rafId) global.cancelAnimationFrame(rafId)
|
||||
rafId = 0
|
||||
call('canvas_webview_close_all', {})
|
||||
})
|
||||
}
|
||||
|
||||
global.IWBCanvasWebview = {
|
||||
install: install,
|
||||
// 诊断:锚点数 / 已创建 / 当前可见 / 坐标补偿
|
||||
stats: function () {
|
||||
var open = 0
|
||||
var shown = 0
|
||||
anchors.forEach(function (st) { if (st.open) open++; if (st.shown) shown++ })
|
||||
return { anchors: anchors.size, open: open, shown: shown, offset: { x: off.x, y: off.y }, scale: canvasScale() }
|
||||
},
|
||||
closeAll: function () { return call('canvas_webview_close_all', {}) },
|
||||
}
|
||||
|
||||
// 自启动:invoke 从 __TAURI__ 取,画布与锚点都从 DOM 查,不需要宿主注入依赖
|
||||
// (app.js 有行数棘轮,这样对宿主零侵入)。延到首帧之后再扫,等 React 画出画布。
|
||||
function boot() {
|
||||
if (global.requestAnimationFrame) global.requestAnimationFrame(install)
|
||||
else setTimeout(install, 16)
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot)
|
||||
else boot()
|
||||
|
||||
})(typeof window !== 'undefined' ? window : this)
|
||||
@@ -102,20 +102,50 @@
|
||||
/* 写系统剪贴板。返回 Promise<boolean>:false 表示这个环境写不了
|
||||
* (非 HTTPS / 老浏览器 / 无 ClipboardItem)→ 调用方降级到内部剪贴板 + Ctrl+Shift+V。
|
||||
* 绝不 reject:复制是高频动作,不能因为剪贴板权限在控制台刷错误。 */
|
||||
/* 桌面端兜底:WKWebView 里 ClipboardItem 写 text/html 常失败(返回 false),
|
||||
* 于是复制节点等于「什么都没写」,Ctrl+V 会贴出上一次的文本。
|
||||
* 这里改成:写不了富文本就写纯文本摘要,并记住这份摘要属于哪个 clip。
|
||||
* 粘贴侧用 matchPlain() 精确比对(文字完全相等才算命中),不会把用户随手复制的文本误判成节点。 */
|
||||
let lastPlain = null
|
||||
function notePlain(plain, clip) {
|
||||
lastPlain = { plain: str(plain), clip: clip || null, at: Date.now() }
|
||||
}
|
||||
function matchPlain(text) {
|
||||
if (!lastPlain || !lastPlain.clip) return null
|
||||
if (Date.now() - lastPlain.at > 10 * 60 * 1000) return null
|
||||
return str(text) === lastPlain.plain ? lastPlain.clip : null
|
||||
}
|
||||
function write(clip) {
|
||||
const plain = plainFor(clip)
|
||||
const cb = (g.navigator && g.navigator.clipboard) || null
|
||||
// 先记账:即使写剪贴板失败,内部匹配(matchPlain)也能让 Ctrl+V 贴回节点组
|
||||
notePlain(plain, clip)
|
||||
try {
|
||||
const cb = g.navigator && g.navigator.clipboard
|
||||
if (!cb || typeof cb.write !== 'function') return Promise.resolve(false)
|
||||
if (typeof g.ClipboardItem !== 'function' || typeof g.Blob !== 'function') return Promise.resolve(false)
|
||||
const html = htmlFor(clip)
|
||||
const plain = plainFor(clip)
|
||||
const item = new g.ClipboardItem({
|
||||
'text/html': new g.Blob([html], { type: 'text/html' }),
|
||||
'text/plain': new g.Blob([plain], { type: 'text/plain' }),
|
||||
})
|
||||
return Promise.resolve(cb.write([item])).then(() => true).catch(() => false)
|
||||
} catch (e) { return Promise.resolve(false) }
|
||||
if (cb && typeof cb.write === 'function' && typeof g.ClipboardItem === 'function' && typeof g.Blob === 'function') {
|
||||
const item = new g.ClipboardItem({
|
||||
'text/html': new g.Blob([htmlFor(clip)], { type: 'text/html' }),
|
||||
'text/plain': new g.Blob([plain], { type: 'text/plain' }),
|
||||
})
|
||||
return Promise.resolve(cb.write([item])).then(() => true).catch(() => writePlainFallback(cb, plain, clip))
|
||||
}
|
||||
} catch (e) { /* 落到纯文本兜底 */ }
|
||||
// WKWebView:没有 clipboard.write ⇒ 直接走纯文本兜底(旧实现这里直接 return false,等于什么都没写)
|
||||
return writePlainFallback(cb, plain, clip)
|
||||
}
|
||||
|
||||
g.IWBClipboardGraph = Object.freeze({ MARK, encodeText, decodeText, htmlFor, plainFor, decode, write })
|
||||
/** 纯文本兜底:优先 navigator.clipboard.writeText,再退到 Rust arboard */
|
||||
function writePlainFallback(cb, plain, clip) {
|
||||
notePlain(plain, clip)
|
||||
const T = g.__TAURI__
|
||||
if (cb && typeof cb.writeText === 'function') {
|
||||
return Promise.resolve(cb.writeText(plain)).then(() => true).catch(() => writeNativeText(T, plain))
|
||||
}
|
||||
return writeNativeText(T, plain)
|
||||
}
|
||||
function writeNativeText(T, plain) {
|
||||
if (!T || !T.core || typeof T.core.invoke !== 'function') return Promise.resolve(false)
|
||||
return Promise.resolve(T.core.invoke('clipboard_write_text', { text: str(plain) })).then(() => true).catch(() => false)
|
||||
}
|
||||
|
||||
g.IWBClipboardGraph = Object.freeze({ MARK, encodeText, decodeText, htmlFor, plainFor, decode, write, matchPlain })
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -0,0 +1,74 @@
|
||||
/* clipboard-native.js —— 桌面端原生剪贴板(2026-11-18)
|
||||
*
|
||||
* 为什么单独一个模块:
|
||||
* WKWebView 的 paste 事件拿不到「从 Finder/预览复制的图片」,
|
||||
* navigator.clipboard.write([ClipboardItem]) 在部分 macOS 版本也不可用。
|
||||
* 图片读写统一走 Rust 侧 arboard(命令 clipboard_read_image / clipboard_write_image)。
|
||||
*
|
||||
* 为什么 IPC 传 PNG 而不是裸 RGBA:
|
||||
* 12MP 照片的 RGBA 是 46MB,base64 后 62MB,穿过 IPC 会卡住前端好几秒;
|
||||
* PNG 通常只有几 MB。读方向由 Rust 编码 PNG,写方向直接把 Blob 的 PNG 字节发过去。
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
function tauri() {
|
||||
const T = global && global.__TAURI__
|
||||
return (T && T.core && typeof T.core.invoke === 'function') ? T : null
|
||||
}
|
||||
|
||||
function b64FromU8(u8) {
|
||||
let s = ''
|
||||
const CH = 0x8000
|
||||
for (let i = 0; i < u8.length; i += CH) s += String.fromCharCode.apply(null, u8.subarray(i, i + CH))
|
||||
return global.btoa(s)
|
||||
}
|
||||
|
||||
function u8FromB64(b64) {
|
||||
const s = global.atob(b64)
|
||||
const u8 = new Uint8Array(s.length)
|
||||
for (let i = 0; i < s.length; i++) u8[i] = s.charCodeAt(i)
|
||||
return u8
|
||||
}
|
||||
|
||||
/** Blob/File → PNG Blob(其它格式统一转一次,避免写进剪贴板后别人贴出来是 HEIC) */
|
||||
function toPngBlob(blobOrFile) {
|
||||
if (blobOrFile && blobOrFile.type === 'image/png') return Promise.resolve(blobOrFile)
|
||||
const C = global.IWBImageBlob
|
||||
if (C && typeof C.toPng === 'function') return Promise.resolve(C.toPng(blobOrFile))
|
||||
return Promise.resolve(blobOrFile)
|
||||
}
|
||||
|
||||
/** 读系统剪贴板里的图片 → PNG File(读不到返回 null) */
|
||||
async function readImage() {
|
||||
const T = tauri()
|
||||
if (!T) return null
|
||||
try {
|
||||
const r = await T.core.invoke('clipboard_read_image')
|
||||
const b64 = r && (r.pngBase64 || r.png_base64)
|
||||
if (!b64) return null
|
||||
const u8 = u8FromB64(b64)
|
||||
const blob = new global.Blob([u8], { type: 'image/png' })
|
||||
const name = 'clipboard-' + Date.now() + '.png'
|
||||
try { return new global.File([blob], name, { type: 'image/png' }) } catch (e) {
|
||||
const named = /** @type {any} */ (blob)
|
||||
named.name = name
|
||||
return named
|
||||
}
|
||||
} catch (e) { return null }
|
||||
}
|
||||
|
||||
/** 把图片写进系统剪贴板(Blob/File 均可) */
|
||||
async function writeImage(blobOrFile) {
|
||||
const T = tauri()
|
||||
if (!T || !blobOrFile) return false
|
||||
try {
|
||||
const png = await toPngBlob(blobOrFile)
|
||||
const buf = new Uint8Array(await png.arrayBuffer())
|
||||
await T.core.invoke('clipboard_write_image', { pngBase64: b64FromU8(buf) })
|
||||
return true
|
||||
} catch (e) { return false }
|
||||
}
|
||||
|
||||
global.IWBNativeClipboard = Object.freeze({ readImage, writeImage, available: () => !!tauri() })
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -25,13 +25,23 @@
|
||||
|
||||
/* 浮层打开时不接管画布粘贴:用户看不见画布,粘出来的节点会被盖住,
|
||||
* 关掉浮层才发现多了一堆。优先读 state(ctx.ui),补一刀 DOM 判定覆盖放大编辑/插件面板。 */
|
||||
function overlayOpen(ui) {
|
||||
if (ui && (ui.settingOpen || ui.drawerOpen || ui.helpOpen || ui.wsMoreOpen || ui.ctxMenu || ui.connMenu)) return true
|
||||
try {
|
||||
return !!document.querySelector('.iwb-md-expand, .iwb-fullmask')
|
||||
} catch (e) { return false }
|
||||
/* 真模态:粘贴会落到用户看不见的画布上,直接不接管。 */
|
||||
function modalOpen(ui) {
|
||||
if (ui && (ui.settingOpen || ui.helpOpen || ui.wsMoreOpen || ui.ctxMenu || ui.connMenu)) return true
|
||||
try { return !!document.querySelector('.iwb-md-expand') } catch (e) { return false }
|
||||
}
|
||||
|
||||
/* 库面板(左侧资源抽屉 / 资源中心全屏):**不再禁止粘贴**。
|
||||
* 旧行为是「浮层打开时不接管」,用户实测反馈「打开库面板粘贴就失效」,因为这两块面板
|
||||
* 常驻打开、并不阻断画布操作(拖拽/连线都还能用),只有粘贴被单独拦掉,像 bug。
|
||||
* 现在的取舍:粘贴前先把库面板关掉(调用方注入 closeLibrary),让落点可见、不产生「贴了
|
||||
* 但看不见」的困惑;调用方没注入就退回旧行为(不接管)。 */
|
||||
function libraryOpen(ui) {
|
||||
if (ui && ui.drawerOpen) return true
|
||||
try { return !!document.querySelector('.iwb-fullmask') } catch (e) { return false }
|
||||
}
|
||||
const overlayOpen = (ui) => modalOpen(ui) || libraryOpen(ui)
|
||||
|
||||
const nameOf = (f, i) => str(f && f.name) || ('pasted-' + (i + 1) + '.png')
|
||||
|
||||
/* ── 粘贴落点跟随指针(v3.24.69,用户裁定)───────────────────────────────
|
||||
@@ -70,6 +80,10 @@
|
||||
let hit = null
|
||||
try { hit = document.elementFromPoint ? document.elementFromPoint(ptr.x, ptr.y) : null } catch (e) { hit = null }
|
||||
if (hit && hit !== el && el.contains && !el.contains(hit)) return null
|
||||
// 面板本身可能挂在画布子树里(左抽屉),单独再判一次
|
||||
try {
|
||||
if (hit && hit.closest && hit.closest('.iwb-fullmask, .iwb-lib, .iwb-lib-embedded, .iwb-drawer, .iwb-fullpanel')) return null
|
||||
} catch (e) { /* ignore */ }
|
||||
const vp = (ctx && ctx.refs && ctx.refs.viewport) || { x: 0, y: 0, scale: 1 }
|
||||
const G = g.IWBCanvasGeometry
|
||||
const w = (G && typeof G.clientToWorld === 'function')
|
||||
@@ -120,42 +134,43 @@
|
||||
* (prompt 216 vs 实测 ~90)⇒ 贴出来的节点视觉中心恒定偏上 63px。改成左上角之后
|
||||
* 落点不再依赖任何高度估算:高度只决定"往下延伸多少"。
|
||||
* ctx.findSpot(type, seed, opts) 的 opts.corner === 'tl' 就是这件事的开关。 */
|
||||
const spotOf = (ctx, type) => ctx.findSpot(type, anchor(ctx) || undefined, { corner: 'tl' })
|
||||
|
||||
/* 同图去重(v3.24.75):把这一批里画布上**已有**的图剔掉,只排布剩下的。
|
||||
* 返回 { kept, dupIds, dupCount }:
|
||||
* dupIds —— 命中的已有节点 id(用来"选中原节点",用户才知道东西在哪)
|
||||
* dupCount —— 连同一批内部的重复也算上(粘两张一样的图时,第二张没有"原节点"可选中)
|
||||
* 判据与语义边界见 src/image-dedupe.js(远程链接、复制节点组都**不**去重)。 */
|
||||
function rejectDup(items, ctx) {
|
||||
const D = g.IWBImageDedupe
|
||||
if (!D || typeof D.index !== 'function') return { kept: items, dupIds: [], dupCount: 0 }
|
||||
const idx = D.index(ctx.nodes())
|
||||
const seen = new Set()
|
||||
const kept = []
|
||||
const dupIds = []
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const v = items[i].data
|
||||
const k = idx.keyOf(v)
|
||||
const hitId = k ? idx.hit(v) : ''
|
||||
if (hitId) { if (dupIds.indexOf(hitId) < 0) dupIds.push(hitId); continue }
|
||||
if (k && seen.has(k)) continue // 同一批里的重复:没有原节点可指,只计数
|
||||
if (k) seen.add(k)
|
||||
kept.push(items[i])
|
||||
/* 指针不在画布上(停在面板/工具栏)时的兜底落点:
|
||||
* 取视口中心,若中心被库面板盖住就往面板旁边挪,避免「贴了但看不见」。 */
|
||||
function safeSeed(ctx) {
|
||||
const box = boxOf(ctx)
|
||||
if (!box) return null
|
||||
const r = box.r
|
||||
let movedOut = false
|
||||
let cx = r.left + r.width / 2
|
||||
const cy = r.top + r.height / 2
|
||||
let moved = false
|
||||
let rects = []
|
||||
try { rects = Array.prototype.slice.call(document.querySelectorAll('.iwb-fullmask, .iwb-lib, .iwb-drawer, .iwb-lib-embedded')) } catch (e) { rects = [] }
|
||||
for (let i = 0; i < rects.length; i++) {
|
||||
const pr = rects[i].getBoundingClientRect ? rects[i].getBoundingClientRect() : null
|
||||
if (!pr || !pr.width) continue
|
||||
if (cx < pr.left || cx > pr.right || cy < pr.top || cy > pr.bottom) continue
|
||||
if (pr.right + 90 < r.right) cx = pr.right + 90
|
||||
else if (pr.left - 90 > r.left) cx = pr.left - 90
|
||||
movedOut = true
|
||||
break
|
||||
}
|
||||
return { kept: kept, dupIds: dupIds, dupCount: items.length - kept.length }
|
||||
// 中心没被面板挡住 ⇒ 返回 null,交回 findSpot 的原行为
|
||||
if (!movedOut) return null
|
||||
const vp = (ctx && ctx.refs && ctx.refs.viewport) || { x: 0, y: 0, scale: 1 }
|
||||
const G = g.IWBCanvasGeometry
|
||||
const w = (G && typeof G.clientToWorld === 'function')
|
||||
? G.clientToWorld(cx, cy, r, vp)
|
||||
: { x: (cx - r.left - (vp.x || 0)) / (vp.scale || 1), y: (cy - r.top - (vp.y || 0)) / (vp.scale || 1) }
|
||||
return (Number.isFinite(w.x) && Number.isFinite(w.y)) ? { x: Math.round(w.x), y: Math.round(w.y) } : null
|
||||
}
|
||||
const spotOf = (ctx, type) => ctx.findSpot(type, anchor(ctx) || safeSeed(ctx) || undefined, { corner: 'tl' })
|
||||
|
||||
function addRefs(items, ctx, label) {
|
||||
if (ctx.wsId !== ctx.activeWsId()) { ctx.setNotice({ type: 'err', text: '工作台已切换,已取消粘贴图片' }); return }
|
||||
const dedup = rejectDup(items, ctx)
|
||||
if (!dedup.kept.length) {
|
||||
// 一张都没落:**必须**说清发生了什么并把原节点选中,否则用户看到的是「按了没反应」。
|
||||
if (dedup.dupIds.length) ctx.setSel(dedup.dupIds)
|
||||
ctx.setNotice({ type: 'ok', text: '这 ' + dedup.dupCount + ' 张图已经在画布上了' + (dedup.dupIds.length ? '(已选中原来的节点)' : '') + ',没有重复粘贴' })
|
||||
return
|
||||
}
|
||||
items = dedup.kept
|
||||
// v3.25.6(用户裁定):同一张图允许重复粘贴 —— 粘贴是显式动作,被去重挡掉像「按键没反应」。
|
||||
// 同图去重仍服务于「拖拽 / 批量导入」等被动路径(src/image-dedupe.js 的其它调用方)。
|
||||
if (!items || !items.length) return
|
||||
const stepX = ctx.nodeW('ref') + 24
|
||||
const stepY = ctx.nodeH('ref') + 24
|
||||
let base = spotOf(ctx, 'ref')
|
||||
@@ -177,7 +192,7 @@
|
||||
ctx.pushHistory()
|
||||
ctx.commitCanvas(ctx.nodes().concat(made), undefined, undefined)
|
||||
ctx.setSel(made.map((n) => n.id))
|
||||
ctx.setNotice({ type: 'ok', text: label + (dedup.dupCount ? '(跳过 ' + dedup.dupCount + ' 张重复的)' : '') })
|
||||
ctx.setNotice({ type: 'ok', text: label })
|
||||
}
|
||||
|
||||
/* 多图:并行导入、**一次落盘** —— 撤销一次就回到粘之前(旧实现分 N 次 commit 要按 N 次) */
|
||||
@@ -250,14 +265,16 @@
|
||||
}
|
||||
return false
|
||||
}
|
||||
if (overlayOpen(ctx.ui)) return false
|
||||
if (modalOpen(ctx.ui)) return false
|
||||
// 库面板(资源抽屉 / 资源中心)不做任何拦截:用户明确要求「粘贴不要关闭库面板」。
|
||||
// 落点问题交给 anchor(指针在画布可见区就贴指针处)与 safeSeed(指针压在面板上时挪开)。
|
||||
if (c.kind === 'graph') {
|
||||
// 复制节点时已把节点组写进系统剪贴板(text/html 带标记)→ 这里直接贴,不用再记 Ctrl+Shift+V。
|
||||
e.preventDefault()
|
||||
// 先摘掉「粘贴替换」的待命监听:此刻用户要贴的是节点组,不是替换某张参考图。
|
||||
// 不摘的话,点过「粘贴替换」按钮后再贴节点组,会把那张图顺手替换掉(v3.24.67 修过一次同类问题)。
|
||||
try { const PO = g.IWBPasteOnce; if (PO) PO.disarm() } catch (err) { /* ignore */ }
|
||||
if (!ctx.pasteGraph(c.clip, anchor(ctx))) ctx.setNotice({ type: 'err', text: '粘贴节点组失败:剪贴板内容无法识别' })
|
||||
if (!ctx.pasteGraph(c.clip, anchor(ctx) || safeSeed(ctx))) ctx.setNotice({ type: 'err', text: '粘贴节点组失败:剪贴板内容无法识别' })
|
||||
return true
|
||||
}
|
||||
if (c.kind === 'empty') {
|
||||
@@ -266,6 +283,16 @@
|
||||
// 复制只进了内部那份;用户从旧版本带过来的复制内容也靠它。
|
||||
// 每个 paste 事件独立处理 → 连按 N 次贴 N 份,不会像旧的定时器方案那样只贴一份。
|
||||
e.preventDefault()
|
||||
// 桌面端:Finder/预览复制的图片在 WKWebView 的 paste 事件里读不到,先问原生剪贴板
|
||||
if (typeof ctx.readNativeImage === 'function') {
|
||||
ctx.setNotice({ type: 'info', text: '正在读取剪贴板图片…' })
|
||||
ctx.readNativeImage().then((f) => {
|
||||
if (f) { pasteImages([f], ctx); ctx.setNotice(null) }
|
||||
else if (ctx.pasteCopiedNodes()) { ctx.setNotice(null) }
|
||||
else ctx.setNotice({ type: 'err', text: ctx.refs.clipExpired ? '内部剪贴板已过期(10 分钟),请重新复制节点' : '剪贴板里没有可粘贴的内容' })
|
||||
})
|
||||
return true
|
||||
}
|
||||
if (ctx.pasteCopiedNodes()) return true
|
||||
ctx.setNotice({
|
||||
type: 'err',
|
||||
@@ -280,6 +307,10 @@
|
||||
// 用户没法照着做(他粘的可能本来就是 PNG,只是 MIME 没填)。
|
||||
const A = g.IWBImageAdmit
|
||||
const list = c.files || []
|
||||
if (typeof ctx.readNativeImage === 'function') {
|
||||
ctx.readNativeImage().then((f) => { if (f) { pasteImages([f], ctx); ctx.setNotice(null) } })
|
||||
return true
|
||||
}
|
||||
const why = (A && typeof A.why === 'function' && list[0]) ? A.why(list[0])
|
||||
: ('暂不支持粘贴文件(' + ((list[0] && list[0].name) || '该文件') + ')')
|
||||
ctx.setNotice({ type: 'err', text: (why || '暂不支持粘贴该文件') + (list.length > 1 ? '(另有 ' + (list.length - 1) + ' 个文件未处理)' : '') })
|
||||
@@ -300,6 +331,26 @@
|
||||
createRefFromUrl(c.text.trim(), ctx)
|
||||
return true
|
||||
}
|
||||
// 桌面端:Finder/预览里「复制图片」经常同时给出 file:// 文本,classify 会当成普通文本,
|
||||
// 结果贴出来是一个写着路径的提示词节点。这里遇到路径样式的文本先问原生剪贴板要图片。
|
||||
const looksPath = /^(file:\/\/|\/|[A-Za-z]:[\/])/.test(c.text.trim())
|
||||
if (looksPath && typeof ctx.readNativeImage === 'function') {
|
||||
e.preventDefault()
|
||||
ctx.readNativeImage().then((f) => {
|
||||
if (f) pasteImages([f], ctx)
|
||||
else createPrompt(c.text, ctx)
|
||||
})
|
||||
return true
|
||||
}
|
||||
// 桌面端:复制节点写不进 text/html 时会退化成「纯文本摘要 + 记住的 clip」。
|
||||
// 文字与刚才写的摘要完全一致 ⇒ 认为用户贴的是节点组,而不是新提示词。
|
||||
const G = g.IWBClipboardGraph
|
||||
const matched = (G && typeof G.matchPlain === 'function') ? G.matchPlain(c.text) : null
|
||||
if (matched) {
|
||||
e.preventDefault()
|
||||
try { const PO = g.IWBPasteOnce; if (PO) PO.disarm() } catch (err) { /* ignore */ }
|
||||
if (ctx.pasteGraph(matched, anchor(ctx) || safeSeed(ctx))) return true
|
||||
}
|
||||
e.preventDefault()
|
||||
createPrompt(c.text, ctx)
|
||||
return true
|
||||
@@ -325,5 +376,29 @@ function probe(ctx) {
|
||||
}, 420)
|
||||
}
|
||||
|
||||
g.IWBClipboardPaste = Object.freeze({ handle, probe, overlayOpen, anchor })
|
||||
/* Cmd/Ctrl+V 兜底(桌面端):菜单缺失或 WebView 不派发 paste 时,160ms 内没收到
|
||||
* 真实 paste 事件就主动读一次原生剪贴板图片。getCtx 由 app.js 注入(懒取,避免闭包过期)。 */
|
||||
let hotkeyBound = false
|
||||
function bindHotkeyFallback(getCtx) {
|
||||
if (hotkeyBound || typeof window === 'undefined') return
|
||||
hotkeyBound = true
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (!(e.metaKey || e.ctrlKey) || e.shiftKey || e.altKey) return
|
||||
if (String(e.key || '').toLowerCase() !== 'v') return
|
||||
const t = /** @type {any} */ (e.target)
|
||||
if (t && t.tagName && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return
|
||||
const D = g.IWBDesktop
|
||||
if (!D || !D.clipboardReadImage) return
|
||||
const ctx = (typeof getCtx === 'function') ? getCtx() : null
|
||||
if (ctx && modalOpen(ctx.ui)) return
|
||||
const stamp = ctx && ctx.refs ? (ctx.refs.pasteStamp || 0) : 0
|
||||
setTimeout(() => {
|
||||
const now = ctx && ctx.refs ? (ctx.refs.pasteStamp || 0) : 0
|
||||
if (now !== stamp) return
|
||||
D.clipboardReadImage().then((f) => { if (f) pasteImages([f], ctx) })
|
||||
}, 160)
|
||||
})
|
||||
}
|
||||
|
||||
g.IWBClipboardPaste = Object.freeze({ handle, probe, overlayOpen, modalOpen, libraryOpen, anchor, bindHotkeyFallback, pasteFiles: (files, ctx) => pasteImages(files || [], ctx) })
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -4,6 +4,8 @@
|
||||
function createHydrator(options) {
|
||||
const opt = options || {}
|
||||
const get = typeof opt.get === 'function' ? opt.get : (() => Promise.resolve(null))
|
||||
// 文件存储:清单只留 thumbHash,缩略图按需从 images/thumbs/ 读
|
||||
const thumb = typeof opt.thumb === 'function' ? opt.thumb : null
|
||||
let sequence = 0
|
||||
let disposed = false
|
||||
async function hydrate(items, requestId) {
|
||||
@@ -11,7 +13,12 @@
|
||||
if (id > sequence) sequence = id
|
||||
const list = Array.isArray(items) ? items : []
|
||||
const values = await Promise.all(list.map(async (item) => {
|
||||
if (!item || !item.idb) return item
|
||||
if (!item) return item
|
||||
if (item.data) return item
|
||||
if (thumb && item.thumbHash) {
|
||||
try { const v = await thumb(item.thumbHash); if (v) return Object.assign({}, item, { data: v }) } catch (e) { /* 读文件失败退回 idb */ }
|
||||
}
|
||||
if (!item.idb) return item
|
||||
try {
|
||||
const value = await get(item.idb)
|
||||
return value == null ? item : Object.assign({}, item, { data: value })
|
||||
|
||||
@@ -192,7 +192,19 @@
|
||||
mainThreadCompress(dataUrl, c, cb)
|
||||
}
|
||||
|
||||
return { estimateBytes, wBlobFromDataUrl, wImgBlobToDataUrl, withDecodedImage, mainThreadCompress, compressDataUrl }
|
||||
/** 把 dataURL 等比缩到 maxEdge 以内(Promise,8s 超时兜底返回原图)。
|
||||
* 用途:图库「插入」的尺寸档(原图/2k/1k/0.5k)—— 传原图到画布太重,按档位先压。 */
|
||||
function toMaxEdge (dataUrl, maxEdge, quality) {
|
||||
return new Promise((resolve) => {
|
||||
if (!dataUrl || String(dataUrl).indexOf('data:') !== 0) { resolve(dataUrl); return }
|
||||
let done = false
|
||||
const fin = (out) => { if (!done) { done = true; resolve(out || dataUrl) } }
|
||||
try { compressDataUrl(dataUrl, { force: true, maxEdge: Number(maxEdge) || 2048, quality: Number(quality) || 0.9 }, fin) } catch (e) { fin(dataUrl) }
|
||||
setTimeout(() => fin(dataUrl), 8000)
|
||||
})
|
||||
}
|
||||
|
||||
return { estimateBytes, wBlobFromDataUrl, wImgBlobToDataUrl, withDecodedImage, mainThreadCompress, compressDataUrl, toMaxEdge }
|
||||
}
|
||||
|
||||
global.IWBImageCompress = Object.freeze({ WORKER_CODE, createWorkerManager, create })
|
||||
|
||||
@@ -105,6 +105,27 @@
|
||||
return (m ? raw.slice(0, -m[0].length) : raw) + '.' + want
|
||||
}
|
||||
|
||||
/** 重名保护(v3.25.18):目标目录里已有同名文件时,自动加 -1/-2 … 后缀。
|
||||
* 为什么需要:批量下载同名图以前是「后写覆盖前写」,最后只剩一张。
|
||||
* existsFn(path) → Promise<boolean>;joinFn(dir, name) → path。任一缺失则按原名返回。 */
|
||||
async function uniqueName (dir, name, joinFn, existsFn) {
|
||||
const raw = strOf(name) || 'image.png'
|
||||
if (!joinFn || !existsFn) return raw
|
||||
const dot = raw.lastIndexOf('.')
|
||||
const stem = dot > 0 ? raw.slice(0, dot) : raw
|
||||
const ext = dot > 0 ? raw.slice(dot) : ''
|
||||
try {
|
||||
const first = await joinFn(dir, raw)
|
||||
if (!(await existsFn(first))) return raw
|
||||
for (let i = 1; i < 1000; i++) {
|
||||
const cand = stem + '-' + i + ext
|
||||
const p = await joinFn(dir, cand)
|
||||
if (!(await existsFn(p))) return cand
|
||||
}
|
||||
} catch (e) { /* 探测失败就按原名写,交给写盘报错 */ }
|
||||
return raw
|
||||
}
|
||||
|
||||
// SVG 文本里的固有尺寸(<svg width/height> 或 viewBox)。只认纯数字/px,判不出返回 null。
|
||||
function svgSizeOf(text) {
|
||||
const s = strOf(text)
|
||||
@@ -192,6 +213,7 @@
|
||||
extOf,
|
||||
isSvg,
|
||||
fileNameFor,
|
||||
uniqueName,
|
||||
svgSizeOf,
|
||||
svgToPngDataUrl,
|
||||
})
|
||||
|
||||
@@ -229,8 +229,11 @@
|
||||
|
||||
function isEnabled(id) {
|
||||
if (plugins.has(id)) return Boolean(recordOf(id).enabled)
|
||||
// 未注册:直接读持久化开关(不得走 recordOf——那会为陌生 id 创建 state 条目)
|
||||
return Boolean(state[id] && state[id].enabled)
|
||||
// 未注册:有持久化记录就按记录;**没有记录 ⇒ 默认启用**
|
||||
// (否则启动早期 state 还没读到时,所有插件都会被判成「已停用」而进 idle)
|
||||
const rec = state[id]
|
||||
if (!rec) return true
|
||||
return Boolean(rec.enabled)
|
||||
}
|
||||
|
||||
function init(nextDeps) {
|
||||
|
||||
@@ -22,7 +22,14 @@
|
||||
pickDownloadDir() { return state.impl ? state.impl.pickDownloadDir() : Promise.resolve('') },
|
||||
getSilentSave() { return !!(state.impl && state.impl.getSilentSave()) },
|
||||
setSilentSave(on) { if (state.impl) state.impl.setSilentSave(on) },
|
||||
// 自动下载(v3.25.20):与「点下载是否弹框」解耦,只决定出图后是否自动落盘
|
||||
getAutoDownload() { return !!(state.impl && state.impl.getAutoDownload && state.impl.getAutoDownload()) },
|
||||
setAutoDownload(on) { if (state.impl && state.impl.setAutoDownload) state.impl.setAutoDownload(on) },
|
||||
openDataDir() { return state.impl ? state.impl.openDataDir() : Promise.reject(new Error('仅桌面端可用')) },
|
||||
// 原生剪贴板图片(v3.26):WKWebView 里 paste 事件拿不到 Finder 复制的图片,
|
||||
// navigator.clipboard.write 也常不可用,统一走 Rust 侧 arboard。
|
||||
clipboardReadImage() { return state.impl && state.impl.clipboardReadImage ? state.impl.clipboardReadImage() : Promise.resolve(null) },
|
||||
clipboardWriteImage(blob) { return state.impl && state.impl.clipboardWriteImage ? state.impl.clipboardWriteImage(blob) : Promise.resolve(false) },
|
||||
market: {
|
||||
list() { return state.impl && state.impl.marketList ? state.impl.marketList() : Promise.resolve([]) },
|
||||
installed() { return state.impl && state.impl.marketInstalled ? state.impl.marketInstalled() : Promise.resolve([]) },
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/* download-auto.js —— 「出图后自动下载」(v3.25.20)
|
||||
*
|
||||
* 三态逻辑(用户裁定):
|
||||
* 目录 + 自动下载勾选 → 出图完成后自动保存到该目录
|
||||
* 目录 + 未勾选 → 不自动保存;点「下载」直接存该目录(不弹框)
|
||||
* 无目录 → 点「下载」时弹出目录/另存为选择
|
||||
*
|
||||
* 命名:gen_<时间戳>.png;同名不覆盖(DedupeName 由调用方注入,内部只负责取字节与落盘)。
|
||||
* 落盘失败只记录、不抛错:自动下载是附加行为,绝不能影响生图本身。
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
const g = /** @type {any} */ (global || {})
|
||||
|
||||
/**
|
||||
* @param {object} deps
|
||||
* getDir() → 当前下载目录(空串表示未设置)
|
||||
* isOn() → 自动下载开关
|
||||
* resolveSrc(item) → Promise<dataURL|url>(本地归档优先)
|
||||
* write(dir, name, blob) → Promise<boolean>
|
||||
* toast(msg, type) → void
|
||||
*/
|
||||
function create (deps) {
|
||||
const d = deps || {}
|
||||
const getDir = typeof d.getDir === 'function' ? d.getDir : function () { return '' }
|
||||
const isOn = typeof d.isOn === 'function' ? d.isOn : function () { return false }
|
||||
const resolveSrc = typeof d.resolveSrc === 'function' ? d.resolveSrc : null
|
||||
const write = typeof d.write === 'function' ? d.write : null
|
||||
const toast = typeof d.toast === 'function' ? d.toast : function () {}
|
||||
|
||||
// 命名沿用图库既有约定:gen_<毫秒时间戳>_<随机6位>.png(不掺节点标题,避免重名与不可读字符)
|
||||
const genName = () => 'gen_' + Date.now() + '_' + Math.floor(Math.random() * 1000000) + '.png'
|
||||
|
||||
let running = false // 防并发重入:一次出图可能触发多次归档
|
||||
return {
|
||||
enabled: () => !!(getDir() && isOn() && write && resolveSrc),
|
||||
/** 保存一批结果;返回成功条数(失败静默,只提示一次) */
|
||||
async saveResults (items) {
|
||||
if (!this.enabled() || running) return 0
|
||||
const list = (Array.isArray(items) ? items : []).filter((x) => x && x.ok !== false && (x.url || x.data))
|
||||
if (!list.length) return 0
|
||||
running = true
|
||||
let saved = 0
|
||||
let failed = 0
|
||||
try {
|
||||
for (const item of list) {
|
||||
try {
|
||||
const src = await resolveSrc(item)
|
||||
if (!src) { failed++; continue }
|
||||
const resp = await fetch(src)
|
||||
if (!resp || !resp.ok) { failed++; continue }
|
||||
const blob = await resp.blob()
|
||||
const name = genName()
|
||||
const ok = await write(getDir(), name, blob)
|
||||
if (ok) saved++
|
||||
else failed++
|
||||
} catch (e) { failed++ }
|
||||
}
|
||||
} finally { running = false }
|
||||
if (saved) toast('已自动下载 ' + saved + ' 张到导出目录', 'ok')
|
||||
else if (failed) toast('自动下载失败(' + failed + ' 张),请检查导出目录是否可写', 'err')
|
||||
return saved
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
g.IWBDownloadAuto = Object.freeze({ create })
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -0,0 +1,52 @@
|
||||
/* runtime-plugin-backup.js —— 插件进出备份
|
||||
*
|
||||
* 备份里带上插件清单与源码(体积很小),换机器恢复后不必重装。
|
||||
* collect() → [{ id, version, file, integrity, code }]
|
||||
* restore(v) → 写回 <资料目录>/plugins/ 并合并清单(备份里没有的插件保留)
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
function store () {
|
||||
const F = global.IWBStorageFile || null
|
||||
return (F && F.plugins) ? F.plugins : null
|
||||
}
|
||||
|
||||
async function collect () {
|
||||
const s = store()
|
||||
if (!s) return []
|
||||
let list = []
|
||||
try { list = await s.manifest() } catch (e) { return [] }
|
||||
const out = []
|
||||
for (const e of (Array.isArray(list) ? list : [])) {
|
||||
if (!e || !e.id || !e.file) continue
|
||||
try {
|
||||
const text = await s.read(e.file)
|
||||
out.push({ id: e.id, version: e.version || '', file: e.file, integrity: e.integrity || '', code: String(text || '') })
|
||||
} catch (err) { /* 单个插件读失败不影响其它 */ }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async function restore (list) {
|
||||
const s = store()
|
||||
if (!s || !Array.isArray(list) || !list.length) return 0
|
||||
let cur = []
|
||||
try { cur = await s.manifest() } catch (e) { cur = [] }
|
||||
const byId = new Map((Array.isArray(cur) ? cur : []).map(function (e) { return [String(e && e.id), e] }))
|
||||
let n = 0
|
||||
for (const p of list) {
|
||||
if (!p || !p.id || !p.file) continue
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(String(p.file))) continue
|
||||
try {
|
||||
await s.write(String(p.file), String(p.code || ''))
|
||||
byId.set(String(p.id), { id: String(p.id), file: String(p.file), version: String(p.version || ''), integrity: String(p.integrity || '') })
|
||||
n++
|
||||
} catch (err) { /* 单个失败忽略 */ }
|
||||
}
|
||||
try { await s.write('index.json', JSON.stringify(Array.from(byId.values()))) } catch (e) { /* ignore */ }
|
||||
return n
|
||||
}
|
||||
|
||||
global.IWBRuntimePluginBackup = { collect: collect, restore: restore }
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -0,0 +1,121 @@
|
||||
/* runtime-plugin-loader.js —— 插件脚本加载(内置 / 外部 / 本地开发)
|
||||
*
|
||||
* 从 app.js 抽出来:app.js 只做装配,加载细节在这里。
|
||||
* 三个入口都返回 boolean,并把状态写回传进来的 record(status/error),供插件面板展示。
|
||||
* · loadBuiltin :同源 /plugins/<file>,走 SRI(integrity 强制校验)
|
||||
* · loadExternal :<资料目录>/plugins/<file>,先读文本 → WebCrypto 校验 sha256 → blob 注入
|
||||
* · loadLocal :开发者模式,code 已在内存里(免签名),blob 注入
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
function host () {
|
||||
return global.IWBPluginHost || null
|
||||
}
|
||||
|
||||
// 外部插件源(<资料目录>/plugins/ 的读写封装)
|
||||
function source () {
|
||||
const F = global.IWBStorageFile || null
|
||||
return (F && F.plugins && typeof F.plugins.read === 'function') ? F.plugins : null
|
||||
}
|
||||
|
||||
async function verifyCode (code, integrity) {
|
||||
if (!integrity) return false
|
||||
const expect = String(integrity).replace(/^sha256-/, '')
|
||||
const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(code))
|
||||
const u8 = new Uint8Array(buf)
|
||||
let bin = ''
|
||||
for (let i = 0; i < u8.length; i++) bin += String.fromCharCode(u8[i])
|
||||
return global.btoa(bin) === expect
|
||||
}
|
||||
|
||||
// 注入一段脚本并等它执行完(插件在加载期自我注册)
|
||||
function inject (attrs) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const script = global.document.createElement('script')
|
||||
script.src = attrs.src
|
||||
script.async = false
|
||||
if (attrs.integrity) { script.integrity = attrs.integrity; script.crossOrigin = 'anonymous' }
|
||||
script.onload = function () { resolve() }
|
||||
script.onerror = function () { reject(new Error(attrs.error || '脚本加载失败')) }
|
||||
global.document.head.appendChild(script)
|
||||
})
|
||||
}
|
||||
|
||||
function markResult (record) {
|
||||
const H = host()
|
||||
const registered = !!(H && typeof H.list === 'function' && H.list().some(function (p) { return p.id === record.id }))
|
||||
record.status = registered ? 'loaded' : 'not-registered'
|
||||
// 不在加载阶段写启用状态:否则会把用户关掉的插件又打开
|
||||
// (启用/停用由 app.js 加载完成后按持久化状态统一应用)
|
||||
return record.status === 'loaded'
|
||||
}
|
||||
|
||||
async function loadBuiltin (record) {
|
||||
record.status = 'loading'
|
||||
const integrity = record.integrity
|
||||
try {
|
||||
await inject({
|
||||
src: '/plugins/' + record.file,
|
||||
integrity: integrity,
|
||||
error: integrity ? '脚本完整性校验失败(integrity 不符或加载失败)' : '脚本加载失败'
|
||||
})
|
||||
return markResult(record)
|
||||
} catch (err) {
|
||||
record.status = 'error'
|
||||
record.error = String((err && err.message) || err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadExternal (record) {
|
||||
record.status = 'loading'
|
||||
const src = source()
|
||||
if (!src) { record.status = 'error'; record.error = '外部插件不可用'; return false }
|
||||
try {
|
||||
const code = await src.read(record.file)
|
||||
if (record.integrity) {
|
||||
const ok = await verifyCode(code, record.integrity)
|
||||
if (!ok) throw new Error('完整性校验失败(外部插件)')
|
||||
}
|
||||
const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' }))
|
||||
try {
|
||||
await inject({ src: url, error: '外部插件脚本执行失败' })
|
||||
} finally {
|
||||
setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000)
|
||||
}
|
||||
return markResult(record)
|
||||
} catch (err) {
|
||||
record.status = 'error'
|
||||
record.error = String((err && err.message) || err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLocal (record) {
|
||||
record.status = 'loading'
|
||||
try {
|
||||
const code = String(record.code || '')
|
||||
if (!code) throw new Error('插件源码为空')
|
||||
const url = global.URL.createObjectURL(new global.Blob([code], { type: 'text/javascript' }))
|
||||
try {
|
||||
await inject({ src: url, error: '本地插件脚本执行失败' })
|
||||
} finally {
|
||||
setTimeout(function () { try { global.URL.revokeObjectURL(url) } catch (e) { /* ignore */ } }, 30000)
|
||||
}
|
||||
return markResult(record)
|
||||
} catch (err) {
|
||||
record.status = 'error'
|
||||
record.error = String((err && err.message) || err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
global.IWBRuntimePluginLoader = {
|
||||
source: source,
|
||||
verifyCode: verifyCode,
|
||||
loadBuiltin: loadBuiltin,
|
||||
loadExternal: loadExternal,
|
||||
loadLocal: loadLocal
|
||||
}
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -0,0 +1,102 @@
|
||||
/* runtime-plugin-market.js —— 插件市场(下载 / 校验 / 安装 / 卸载)
|
||||
*
|
||||
* 索引:https://market.maqiart.eu.org/index.json,产物同域 plugin-<id>.<hash>.js
|
||||
* 落点:<资料目录>/plugins/(清单 index.json + 插件文件)
|
||||
* 校验:市场索引里的 sha256(hex)与下载文本比对,不符直接拒绝
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
const MARKET_URL = 'https://market.maqiart.eu.org/index.json'
|
||||
|
||||
function store () {
|
||||
const F = global.IWBStorageFile || null
|
||||
return (F && F.plugins) ? F.plugins : null
|
||||
}
|
||||
|
||||
// 桌面端优先走 Tauri 原生 HTTP(WKWebView 在代理/fake-IP 环境下 fetch 会 Load failed);
|
||||
// 原生失败时再退回 WebView fetch(有些 Windows 公司网络/代理只放行后者),两个错误都带上,便于定位。
|
||||
async function marketFetch (url) {
|
||||
const T = (global.__TAURI__ && global.__TAURI__.http) ? global.__TAURI__.http : null
|
||||
let nativeErr = ''
|
||||
if (T && typeof T.fetch === 'function') {
|
||||
try { return await T.fetch(url) } catch (e) { nativeErr = String((e && e.message) || e) }
|
||||
}
|
||||
try {
|
||||
return await global.fetch(url, { cache: 'no-store' })
|
||||
} catch (e2) {
|
||||
const webErr = String((e2 && e2.message) || e2)
|
||||
throw new Error('无法访问 ' + url + (nativeErr ? ('(原生 HTTP:' + nativeErr + ')') : '') + '(网页请求:' + webErr + ')')
|
||||
}
|
||||
}
|
||||
|
||||
// 本地缓存:上次成功拉到的市场列表(毫秒级出图,后台再刷新)
|
||||
const CACHE_KEY = 'iwb_market_cache'
|
||||
function localStore () {
|
||||
const L = global.IWBStorageLocal || null
|
||||
return (L && typeof L.getStore === 'function') ? L.getStore() : null
|
||||
}
|
||||
function cached () {
|
||||
try {
|
||||
const st = localStore()
|
||||
if (!st) return null
|
||||
const v = st.get(CACHE_KEY)
|
||||
return (Array.isArray(v) && v.length) ? v : null
|
||||
} catch (e) { return null }
|
||||
}
|
||||
function saveCache (list) {
|
||||
try { const st = localStore(); if (st && Array.isArray(list) && list.length) st.set(CACHE_KEY, list) } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
async function list () {
|
||||
const resp = await marketFetch(MARKET_URL)
|
||||
if (!resp.ok) throw new Error('市场不可达:HTTP ' + resp.status)
|
||||
const j = await resp.json()
|
||||
const items = Array.isArray(j && j.plugins) ? j.plugins : []
|
||||
saveCache(items)
|
||||
return items
|
||||
}
|
||||
|
||||
async function installed () {
|
||||
const s = store()
|
||||
if (!s) return []
|
||||
return await s.manifest()
|
||||
}
|
||||
|
||||
async function install (id) {
|
||||
try {
|
||||
const items = await list()
|
||||
const item = items.find(function (p) { return p && p.id === id })
|
||||
if (!item) return { ok: false, error: '市场里没有这个插件' }
|
||||
const base = MARKET_URL.replace(/index\.json$/, '')
|
||||
const resp = await marketFetch(base + item.file)
|
||||
if (!resp.ok) throw new Error('下载失败:HTTP ' + resp.status)
|
||||
const text = await resp.text()
|
||||
const buf = await global.crypto.subtle.digest('SHA-256', new global.TextEncoder().encode(text))
|
||||
const hex = Array.from(new Uint8Array(buf)).map(function (b) { return b.toString(16).padStart(2, '0') }).join('')
|
||||
if (item.sha256 && hex !== item.sha256) return { ok: false, error: '校验失败(sha256 不符)' }
|
||||
const s = store()
|
||||
if (!s) return { ok: false, error: '外部插件目录不可用' }
|
||||
const file = String(item.file).split('/').pop()
|
||||
await s.write(file, text)
|
||||
const cur = await s.manifest()
|
||||
const next = cur.filter(function (p) { return p && p.id !== id }).concat([{ id: id, file: file, version: item.version, integrity: item.integrity }])
|
||||
await s.write('index.json', JSON.stringify(next, null, 2) + '\n')
|
||||
return { ok: true, restart: true, file: file }
|
||||
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
|
||||
}
|
||||
|
||||
async function uninstall (id) {
|
||||
try {
|
||||
const s = store()
|
||||
if (!s) return { ok: false, error: '外部插件目录不可用' }
|
||||
const cur = await s.manifest()
|
||||
const hit = cur.find(function (p) { return p && p.id === id })
|
||||
const next = cur.filter(function (p) { return p && p.id !== id })
|
||||
await s.write('index.json', JSON.stringify(next, null, 2) + '\n')
|
||||
if (hit && hit.file) await s.remove(hit.file)
|
||||
return { ok: true, restart: true }
|
||||
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
|
||||
}
|
||||
|
||||
global.IWBRuntimePluginMarket = { list: list, cached: cached, installed: installed, install: install, uninstall: uninstall }
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -1119,22 +1119,10 @@
|
||||
// 而 MIME 没填的 PNG 反倒被静默丢掉(Windows 资源管理器就这行为)。
|
||||
const A = global.IWBImageAdmit
|
||||
const refused = []
|
||||
/* 同图去重(v3.24.75):拖进来的字节与画布上已有图片一致时不再建节点。
|
||||
* 判据见 src/image-dedupe.js —— 只认本地图片字节,URL / 复制节点组都不参与。
|
||||
* 多条命中合并成一条提示(拖 5 张重复图不该刷 5 条),并选中已有节点把位置指出来。 */
|
||||
const D = global.IWBImageDedupe
|
||||
const idx = (D && typeof D.index === 'function') ? D.index(refs.nodes) : null
|
||||
const dupNames = []
|
||||
const dupIds = []
|
||||
const flushDups = () => {
|
||||
if (!dupNames.length) return
|
||||
const ns = dupNames.splice(0, dupNames.length)
|
||||
const ids = dupIds.splice(0, dupIds.length)
|
||||
if (ids.length) setSel(ids)
|
||||
setNotice({ type: 'ok', text: ns.length === 1
|
||||
? ('「' + ns[0] + '」已经在画布上了,没有重复导入' + (ids.length ? '(已选中原来的节点)' : ''))
|
||||
: (ns.length + ' 张图已经在画布上了,没有重复导入' + (ids.length ? '(已选中原来的节点)' : '')) })
|
||||
}
|
||||
/* v3.25.8(用户裁定):拖入同一张图**允许重复添加**,不再走同图去重。
|
||||
* 去重曾经挡住「图片节点数据缺失后重新拖入」这条唯一的自愈路径:命中已有节点 →
|
||||
* 不写 blob → 那个节点依旧是空图。现在每次都正常导入并新建节点,顺带把丢失的
|
||||
* blob 按同一个内容 key 重新写回磁盘(旧节点也就跟着恢复了)。 */
|
||||
for (const f of files) {
|
||||
const verdict = (A && typeof A.of === 'function') ? A.of(f) : ((f.type && f.type.indexOf('image/') === 0) ? 'image' : 'other')
|
||||
if (verdict !== 'image') { refused.push(f); continue }
|
||||
@@ -1143,16 +1131,7 @@
|
||||
// 拖放与粘贴共用导入唯一收口(压缩到 ≤1600 + 立即引用化)
|
||||
rd.onload = () => wImportImage(rd.result, { onError: (msg) => setNotice({ type: 'err', text: msg }) }, (r) => {
|
||||
if (!r || !r.ok || !r.data) return
|
||||
const hitId = idx ? idx.hit(r.data) : ''
|
||||
if (hitId) {
|
||||
dupNames.push(String(f.name || '图片'))
|
||||
if (dupIds.indexOf(hitId) < 0) dupIds.push(hitId)
|
||||
clearTimeout(refs.dupNoticeTimer)
|
||||
refs.dupNoticeTimer = setTimeout(flushDups, 260)
|
||||
return
|
||||
}
|
||||
const nid = mk({ url: '', data: r.data, name: f.name })
|
||||
if (idx) idx.add(r.data, nid)
|
||||
mk({ url: '', data: r.data, name: f.name })
|
||||
})
|
||||
rd.onerror = () => setNotice({ type: 'err', text: '读取拖入的图片失败:' + String(f.name || '') })
|
||||
rd.readAsDataURL(f)
|
||||
@@ -2008,12 +1987,18 @@
|
||||
setSel([node.id])
|
||||
commitCanvas(refs.nodes.concat([node]), undefined, undefined)
|
||||
}
|
||||
const addPluginNode = (variantId, x, y) => {
|
||||
const addPluginNode = (variantId, x, y, extra) => {
|
||||
const variant = wPluginNodeVariants.find((v) => v.id === variantId)
|
||||
// 变体不存在就别建:插件可能传错 id(canvasWrite.createNode 也走这里),
|
||||
// 建出来会是一个没有渲染器的空壳节点,比什么都不发生更糟。
|
||||
if (!variant) return null
|
||||
const spot = (x != null && y != null) ? { x, y } : findSpot('plugin')
|
||||
const node = { id: uid('n'), type: pluginTypeId((variant && variant.pluginId) || '', variantId), x: spot.x, y: spot.y, w: NODE_W, data: { variant: String(variantId || ''), pluginId: String((variant && variant.pluginId) || ''), text: String((variant && variant.defaults && variant.defaults.text) || '') } }
|
||||
// 变体可声明初始宽度(如画布内网页节点要 520 才看得清):未声明则沿用通用宽度。
|
||||
// extra:调用方要带初值(浏览器面板的「在画布打开」要把当前网址一起带过去)。
|
||||
const node = { id: uid('n'), type: pluginTypeId((variant && variant.pluginId) || '', variantId), x: spot.x, y: spot.y, w: (variant && Number.isFinite(variant.w) ? variant.w : NODE_W), data: Object.assign({ variant: String(variantId || ''), pluginId: String((variant && variant.pluginId) || ''), text: String((variant && variant.defaults && variant.defaults.text) || '') }, extra || {}) }
|
||||
setSel([node.id])
|
||||
commitCanvas(refs.nodes.concat([node]), undefined, undefined)
|
||||
return node.id
|
||||
}
|
||||
// 输出节点「插入为参考图」:格式纠正统一走模块级 refSrcOf(2026-11-11 用户裁定:参考图必须是 PNG,
|
||||
// 上游开始返回 .svg)。纠正后的 PNG 仍要走 wImportImage 的「压缩 → 引用化」——画布里只留引用,
|
||||
|
||||
@@ -176,16 +176,26 @@
|
||||
const kv = {
|
||||
async put(key, value) {
|
||||
try {
|
||||
if (!enabled() || !dir) return false
|
||||
// 返回对象而不是裸 false:调用方(ImageBlobStore.put)用 r.ok===false 判断失败,
|
||||
// 裸布尔 false 会被误判为成功,产出指向空文件的 {__blob}(v3.25.10 修)。
|
||||
if (!enabled() || !dir) return { ok: false, error: 'not-ready' }
|
||||
if (value && typeof value === 'object' && typeof value.size === 'number' && value.type !== undefined) {
|
||||
// Blob:直接取二进制落盘
|
||||
const buf = await value.arrayBuffer()
|
||||
const hash = await sha16(buf)
|
||||
const rel = IMG_DIR + '/' + catOfKey(key) + '/' + hash + '.' + extOf(value.type)
|
||||
const cat = catOfKey(key)
|
||||
const rel = IMG_DIR + '/' + cat + '/' + hash + '.' + extOf(value.type)
|
||||
const abs = await join(dir, rel)
|
||||
// Windows 全新安装时 images/canvas|gallery 并不存在(只有 thumbs 因为 writeDisplayThumb 会 mkdir),
|
||||
// 直接 writeFile 会失败 → 整条 blob 写入被判失败 → 图片退化成不持久引用。
|
||||
// 这里先建目录(幂等),与 thumbs 的写法保持一致。
|
||||
try { await fs().mkdir(await join(dir, IMG_DIR, cat), { recursive: true }) } catch (e) { /* 已存在 */ }
|
||||
await fs().writeFile(abs, new Uint8Array(buf))
|
||||
assets[String(key)] = { f: rel, k: 'blob', m: value.type || 'application/octet-stream' }
|
||||
schedule()
|
||||
// 立即落盘:登记表只存在 data.json 里,晚 800ms 就可能被强杀丢掉,
|
||||
// 而画布文件是即时写的 ⇒ 引用还在、登记没了,GC 会把在用图片当孤儿。
|
||||
await flush()
|
||||
return true
|
||||
}
|
||||
const s = String(value)
|
||||
@@ -193,11 +203,14 @@
|
||||
const dec = dataUrlToBytes(s)
|
||||
if (dec) {
|
||||
const hash = await sha16(dec.bytes)
|
||||
const rel = IMG_DIR + '/' + catOfKey(key) + '/' + hash + '.' + extOf(dec.mime)
|
||||
const cat2 = catOfKey(key)
|
||||
const rel = IMG_DIR + '/' + cat2 + '/' + hash + '.' + extOf(dec.mime)
|
||||
const abs = await join(dir, rel)
|
||||
try { await fs().mkdir(await join(dir, IMG_DIR, cat2), { recursive: true }) } catch (e) { /* 已存在 */ }
|
||||
await fs().writeFile(abs, dec.bytes)
|
||||
assets[String(key)] = { f: rel, k: 'dataurl', m: dec.mime }
|
||||
schedule()
|
||||
await flush()
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -206,7 +219,7 @@
|
||||
return true
|
||||
} catch (e) {
|
||||
try { global.IWBMetricsSwallow && global.IWBMetricsSwallow('file-kv-put', e) } catch (e2) { /* ignore */ }
|
||||
return false
|
||||
return { ok: false, error: String((e && e.message) || e) }
|
||||
}
|
||||
},
|
||||
async get(key) {
|
||||
@@ -324,8 +337,11 @@
|
||||
try {
|
||||
const u8 = await fs().readFile(await join(dir, a.f))
|
||||
if (!u8 || u8.length > 96 * 1024) continue
|
||||
it.data = bytesToDataUrl(a.m || 'image/jpeg', u8)
|
||||
it.thumbHash = String(a.f).split('/').pop().replace(/\.[^.]+$/, '')
|
||||
const hash = String(a.f).split('/').pop().replace(/\.[^.]+$/, '')
|
||||
const thumbPath = await join(dir, IMG_DIR, 'thumbs', hash + '.jpg')
|
||||
try { if (!(await fs().exists(thumbPath))) await fs().writeFile(thumbPath, u8) } catch (e) { /* 写失败不阻塞 */ }
|
||||
it.thumbHash = hash
|
||||
it.data = ''
|
||||
n++
|
||||
} catch (e) { /* 单张失败忽略 */ }
|
||||
}
|
||||
@@ -494,7 +510,23 @@
|
||||
}
|
||||
|
||||
// 一次性迁移:把老版本存在 IndexedDB 里的图片字节搬到 images/ 下(跑过一次就写标记文件)
|
||||
const blog = async (m) => { try { await fs().writeTextFile(await join(dir, '_boot.log'), new Date().toISOString() + ' ' + m + '\n', { append: true }) } catch (e) { /* ignore */ } }
|
||||
// 启动日志:超过 256KB 只保留最后 64KB(否则长年累月会一直长)
|
||||
const blog = async (m) => {
|
||||
try {
|
||||
const logPath = await join(dir, '_boot.log')
|
||||
let tail = ''
|
||||
try {
|
||||
const st = await fs().stat(logPath)
|
||||
if (st && st.size > 262144) {
|
||||
const txt = await fs().readTextFile(logPath)
|
||||
tail = txt.slice(-65536)
|
||||
}
|
||||
} catch (e) { /* 文件不存在就是首次 */ }
|
||||
const line = new Date().toISOString() + ' ' + m + '\n'
|
||||
if (tail) await fs().writeTextFile(logPath, tail + line)
|
||||
else await fs().writeTextFile(logPath, line, { append: true })
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
async function migrateBlobs() {
|
||||
try {
|
||||
await blog('migrate:start dir=' + dir)
|
||||
@@ -592,6 +624,15 @@
|
||||
return true
|
||||
}
|
||||
|
||||
/* 建立工作必需目录:canvases/ library/ plugins/ trash/ 与 images/{canvas,gallery,thumbs,legacy} */
|
||||
async function ensureDirs() {
|
||||
const subs = [CANVAS_DIR, 'library', PLUG_DIR, 'trash', IMG_DIR, IMG_DIR + '/canvas', IMG_DIR + '/gallery', IMG_DIR + '/thumbs', IMG_DIR + '/legacy']
|
||||
for (const sub of subs) {
|
||||
try { await fs().mkdir(await join(dir, sub), { recursive: true }) } catch (e) { /* 已存在或不可写:继续下一个 */ }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function init(opts) {
|
||||
const o = opts || {}
|
||||
tauri = global.__TAURI__ || null
|
||||
@@ -615,6 +656,11 @@
|
||||
dir = want
|
||||
try { global.localStorage.setItem(PTR_KEY, dir) } catch (e) { /* ignore */ }
|
||||
try { await fs().mkdir(await join(dir, IMG_DIR), { recursive: true }) } catch (e) { /* 已存在 */ }
|
||||
// 兜底:把工作必需的子目录一次性补齐(幂等)。
|
||||
// 为什么需要:Windows 全新安装时 images/ 下只有 thumbs/,缺了 canvas/ 会导致
|
||||
// 图片写入失败(历史 bug:写进不持久的 Cache → 重启丢图);目录被手工删掉时也靠这里自愈,
|
||||
// 否则启动阶段读目录抛错会直接影响首屏渲染。
|
||||
try { await ensureDirs() } catch (e) { /* 建目录失败不阻塞启动 */ }
|
||||
try { await repairCanvasFileNames() } catch (e) { /* 修复失败按原样装载 */ }
|
||||
await loadInto()
|
||||
// 从 WebView 的 localStorage 捞回被截断/覆盖的画布(一次性)
|
||||
@@ -626,6 +672,10 @@
|
||||
try { await migrateBlobs() } catch (e) { /* 迁移失败不阻塞启动 */ }
|
||||
// 图库清单补齐缩略图(一次性)
|
||||
try { await backfillGalleryThumbs() } catch (e) { /* 忽略 */ }
|
||||
// 图库清单去 base64(一次性):缩略图已在 images/thumbs/,清单只留 thumbHash
|
||||
try { await stripInlineGalleryThumbs() } catch (e) { /* 忽略 */ }
|
||||
// trash/ 轮转:gcImages 只是移进来,超过 30 天在这里真正删除
|
||||
try { await rotateTrash(30) } catch (e) { /* 忽略 */ }
|
||||
// 自愈:图库清单丢了但 assets 还有 out_ 键 ⇒ 按键重建(名称/时间/idb 可推,label/远程 url 无法恢复)
|
||||
try {
|
||||
if (mem['iwb_web_outputs'] === undefined) {
|
||||
@@ -677,31 +727,174 @@
|
||||
|
||||
// 清理未引用图片:只动「没有任何 assets 条目指向」的文件,移到 trash/(不直接删)。
|
||||
// 保守策略:assets 里还有登记的键一律保留,避免误删仍在画布上引用的图。
|
||||
// trash/ 轮转:超过 maxAgeDays 的文件直接删除(gcImages 只是移进来,不清)
|
||||
async function rotateTrash(maxAgeDays) {
|
||||
const days = Number(maxAgeDays) > 0 ? Number(maxAgeDays) : 30
|
||||
try {
|
||||
if (!enabled() || !dir) return 0
|
||||
const trashAbs = await join(dir, 'trash')
|
||||
const cutoff = Date.now() - days * 86400000
|
||||
let removed = 0
|
||||
const walk = async (abs, depth) => {
|
||||
if (depth > 3) return
|
||||
let entries = []
|
||||
try { entries = await fs().readDir(abs) } catch (e) { return }
|
||||
for (const e of entries) {
|
||||
if (!e) continue
|
||||
const child = await join(abs, e.name)
|
||||
if (e.isDirectory) { await walk(child, depth + 1); continue }
|
||||
try {
|
||||
const st = await fs().stat(child)
|
||||
const mt = st && st.mtime ? new Date(st.mtime).getTime() : 0
|
||||
if (mt && mt < cutoff) { await fs().remove(child); removed++ }
|
||||
} catch (err) { /* 单条失败忽略 */ }
|
||||
}
|
||||
}
|
||||
await walk(trashAbs, 0)
|
||||
return removed
|
||||
} catch (e) { return 0 }
|
||||
}
|
||||
|
||||
// 图库缩略图:清单里只存 thumbHash,渲染时按需从 images/thumbs/ 读(避免 base64 撑爆 index.json)
|
||||
let thumbMapCache = null
|
||||
async function thumbFileMap() {
|
||||
if (thumbMapCache) return thumbMapCache
|
||||
const map = {}
|
||||
try {
|
||||
const abs = await join(dir, IMG_DIR, 'thumbs')
|
||||
const entries = await fs().readDir(abs)
|
||||
for (const e of entries) {
|
||||
if (!e || e.isDirectory) continue
|
||||
const base = String(e.name).replace(/\.[^.]+$/, '')
|
||||
if (!map[base]) map[base] = String(e.name)
|
||||
}
|
||||
} catch (e) { /* 没有 thumbs 目录就返回空表 */ }
|
||||
thumbMapCache = map
|
||||
return map
|
||||
}
|
||||
async function galleryThumb(hash) {
|
||||
try {
|
||||
if (!enabled() || !dir || !hash) return ''
|
||||
const map = await thumbFileMap()
|
||||
const name = map[String(hash)]
|
||||
if (!name) return ''
|
||||
const u8 = await fs().readFile(await join(dir, IMG_DIR, 'thumbs', name))
|
||||
if (!u8 || !u8.length) return ''
|
||||
const mime = /\.png$/i.test(name) ? 'image/png' : 'image/jpeg'
|
||||
return bytesToDataUrl(mime, u8)
|
||||
} catch (e) { return '' }
|
||||
}
|
||||
|
||||
// 画布显示缩略图(768px)落盘:重启后直接命中,不用重新解码 4K 原图
|
||||
async function readDisplayThumb(hash) {
|
||||
try {
|
||||
if (!enabled() || !dir || !hash) return ''
|
||||
const abs = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_768.jpg')
|
||||
if (!(await fs().exists(abs))) return ''
|
||||
const u8 = await fs().readFile(abs)
|
||||
if (!u8 || !u8.length) return ''
|
||||
return bytesToDataUrl('image/jpeg', u8)
|
||||
} catch (e) { return '' }
|
||||
}
|
||||
async function writeDisplayThumb(hash, dataUrl) {
|
||||
try {
|
||||
if (!enabled() || !dir || !hash || !dataUrl) return false
|
||||
const m = /^data:[^;]+;base64,(.*)$/.exec(String(dataUrl))
|
||||
if (!m) return false
|
||||
const bin = atob(m[1])
|
||||
const u8 = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i)
|
||||
const abs = await join(dir, IMG_DIR, 'thumbs', String(hash) + '_768.jpg')
|
||||
if (await fs().exists(abs)) return true
|
||||
await fs().mkdir(await join(dir, IMG_DIR, 'thumbs'), { recursive: true })
|
||||
await fs().writeFile(abs, u8)
|
||||
return true
|
||||
} catch (e) { return false }
|
||||
}
|
||||
|
||||
// 一次性:图库清单里历史遗留的 base64 data 删掉(缩略图已在 images/thumbs/)
|
||||
async function stripInlineGalleryThumbs() {
|
||||
try {
|
||||
const marker = await join(dir, 'gallery-data-stripped.flag')
|
||||
if (await fs().exists(marker)) return 0
|
||||
const raw = mem['iwb_web_outputs']
|
||||
if (!raw) { await fs().writeTextFile(marker, '0'); return 0 }
|
||||
const items = JSON.parse(raw)
|
||||
if (!Array.isArray(items)) return 0
|
||||
const map = await thumbFileMap()
|
||||
let n = 0
|
||||
for (const it of items) {
|
||||
if (!it || !it.data) continue
|
||||
if (it.thumbHash && map[String(it.thumbHash)]) { it.data = ''; n++ }
|
||||
}
|
||||
if (n) { mem['iwb_web_outputs'] = JSON.stringify(items); await flush() }
|
||||
await fs().writeTextFile(marker, String(n))
|
||||
return n
|
||||
} catch (e) { return 0 }
|
||||
}
|
||||
|
||||
async function gcImages(opts) {
|
||||
const dryRun = !!(opts && opts.dryRun)
|
||||
try {
|
||||
if (!enabled() || !dir) return { ok: false, error: '资料目录未就绪' }
|
||||
const used = new Set(Object.keys(assets).map((k) => assets[k] && assets[k].f).filter(Boolean))
|
||||
/* v3.25.8:assets 登记表是唯一的「在用」判据,但它可能因为恢复备份/迁移而落后于画布。
|
||||
* 只看 assets 会把画布仍在引用的图片当孤儿挪进 trash/ —— 节点随即变成占位图,
|
||||
* 而且用户重新拖入时又被同图去重挡回来(那条链路已废)。
|
||||
* 这里把 canvases/*.json 里出现的 {__blob} key 也算作在用:宁可留下几 MB,也不误删用户图片。 */
|
||||
const canvasKeys = new Set()
|
||||
try {
|
||||
const cd = await join(dir, 'canvases')
|
||||
const list = await fs().readDir(cd)
|
||||
for (const e of list) {
|
||||
if (!e || e.isDirectory || !/\.json$/i.test(e.name) || e.name === 'active.json') continue
|
||||
let txt = ''
|
||||
try { txt = await fs().readTextFile(await join(cd, e.name)) } catch (err) { continue }
|
||||
const m = txt.match(/"__blob"\s*:\s*"([^"]+)"/g) || []
|
||||
for (const hit of m) {
|
||||
const km = /"([^"]+)"$/.exec(hit)
|
||||
if (km) canvasKeys.add(km[1])
|
||||
}
|
||||
}
|
||||
} catch (e) { /* 画布读不到就退回旧判据 */ }
|
||||
const referenced = new Set()
|
||||
for (const k of canvasKeys) { const a = assets[k]; if (a && a.f) referenced.add(a.f) }
|
||||
referenced.forEach((f) => used.add(f))
|
||||
const imgAbs = await join(dir, IMG_DIR)
|
||||
const entries = await fs().readDir(imgAbs)
|
||||
// 子目录也要扫:images/{canvas,gallery,thumbs,legacy}/ 里的孤儿同样占空间
|
||||
const subs = ['', 'canvas', 'gallery', 'thumbs', 'legacy']
|
||||
const orphans = []
|
||||
for (const e of entries) {
|
||||
if (!e || e.isDirectory) continue
|
||||
if (!used.has(IMG_DIR + '/' + e.name)) orphans.push(e.name)
|
||||
for (const sub of subs) {
|
||||
const abs = sub ? await join(imgAbs, sub) : imgAbs
|
||||
let entries = []
|
||||
try { entries = await fs().readDir(abs) } catch (e) { continue }
|
||||
for (const e of entries) {
|
||||
if (!e || e.isDirectory) continue
|
||||
const rel = IMG_DIR + '/' + (sub ? sub + '/' : '') + e.name
|
||||
if (!used.has(rel)) orphans.push({ sub: sub, name: e.name, rel: rel })
|
||||
}
|
||||
}
|
||||
if (dryRun || !orphans.length) return { ok: true, orphans: orphans.length, moved: 0, dryRun: dryRun }
|
||||
// 断链:画布引用了、但登记表里没有的 key —— 这类节点的图**已经显示不出来**,
|
||||
// GC 不会动它们(文件根本不在),但值得在确认弹窗里报数,让用户知道数据已经缺了。
|
||||
const dangling = Array.from(canvasKeys).filter((k) => !assets[k]).length
|
||||
const keptByCanvas = referenced.size
|
||||
if (dryRun || !orphans.length) return { ok: true, orphans: orphans.length, moved: 0, dryRun: dryRun, dangling: dangling, keptByCanvas: keptByCanvas }
|
||||
const trashAbs = await join(dir, 'trash')
|
||||
try { await fs().mkdir(trashAbs, { recursive: true }) } catch (e) { /* 已存在 */ }
|
||||
let moved = 0
|
||||
for (const name of orphans) {
|
||||
try { await fs().rename(await join(imgAbs, name), await join(trashAbs, name)); moved++ } catch (e) { /* 单条失败忽略 */ }
|
||||
for (const item of orphans) {
|
||||
try {
|
||||
const targetDir = item.sub ? await join(trashAbs, item.sub) : trashAbs
|
||||
await fs().mkdir(targetDir, { recursive: true })
|
||||
await fs().rename(await join(imgAbs, item.sub, item.name), await join(targetDir, item.name))
|
||||
moved++
|
||||
} catch (e) { /* 单条失败忽略 */ }
|
||||
}
|
||||
return { ok: true, orphans: orphans.length, moved: moved, dryRun: dryRun }
|
||||
return { ok: true, orphans: orphans.length, moved: moved, dryRun: dryRun, dangling: dangling, keptByCanvas: keptByCanvas }
|
||||
} catch (e) { return { ok: false, error: String((e && e.message) || e) } }
|
||||
}
|
||||
|
||||
global.IWBStorageFile = {
|
||||
enabled, ready: init, flush, runtime, pickDir, switchTo, migrateTo, gcImages,
|
||||
enabled, ready: init, flush, runtime, pickDir, switchTo, migrateTo, gcImages, rotateTrash, galleryThumb, readDisplayThumb, writeDisplayThumb,
|
||||
plugins: { manifest: pluginManifest, read: pluginRead, write: pluginWrite, remove: pluginRemove, dir: pluginDir, listLocal: pluginListLocal },
|
||||
storage: () => storage,
|
||||
kv: () => kv,
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
/* ui-appearance.js —— 外观(界面主题 / 画布 / 连线 / 节点 / 主题色)与取色器(v3.25.22)
|
||||
*
|
||||
* 设计边界(与用户确认过):
|
||||
* · 开放:画布底色、网格、连线(颜色/粗细/线型/高亮)、节点(底色/边框/圆角/选中描边)、主题色
|
||||
* · 不开放:界面背景 / 面板底色 / 文字颜色 —— 它们被大量 color-mix 派生,开放后极易变成不可读
|
||||
* · 所有颜色项**亮/暗各存一套**;尺寸类(粗细、圆角、间距)共用一套
|
||||
* · 全部最终落到 CSS 变量上(改一个变量全局生效,不需要改渲染逻辑)
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
const g = /** @type {any} */ (global || {})
|
||||
const React = g.React || {}
|
||||
const el = (type, prop, ...children) => React.createElement(type, prop, ...children)
|
||||
|
||||
const DEFAULTS = Object.freeze({
|
||||
canvasBgLight: '#d9dbde', canvasBgDark: '#6f6f6f',
|
||||
gridDotLight: '#c9ccd6', gridDotDark: '#8f8f8f', gridSize: 1.4, gridGap: 22, gridOn: true,
|
||||
edgeColorLight: '#b9bfca', edgeColorDark: '#7a7a7a',
|
||||
edgeWidth: 1.8, edgeDash: 'dashed',
|
||||
edgeHotLight: '#6b7280', edgeHotDark: '#ffffff',
|
||||
nodeBgLight: '#f1f3f6', nodeBgDark: '#b3b3b3',
|
||||
nodeBorderLight: '#d5d9e0', nodeBorderDark: '#4f4f4f',
|
||||
nodeRadius: 14, nodeSelWidth: 1,
|
||||
accent: '#6b7280',
|
||||
presets: [],
|
||||
})
|
||||
|
||||
const DASH = { solid: 'none', dashed: '4 3', dotted: '1 3' }
|
||||
const HEX_RE = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i
|
||||
const isHex = (v) => HEX_RE.test(String(v || ''))
|
||||
const normHex = (v) => {
|
||||
const s = String(v || '').trim()
|
||||
if (!isHex(s)) return ''
|
||||
if (s.length === 4) return ('#' + s[1] + s[1] + s[2] + s[2] + s[3] + s[3]).toLowerCase()
|
||||
return s.toLowerCase()
|
||||
}
|
||||
const clamp = (v, lo, hi, def) => {
|
||||
const n = Number(v)
|
||||
if (!Number.isFinite(n)) return def
|
||||
return Math.min(hi, Math.max(lo, n))
|
||||
}
|
||||
|
||||
function normalize (cfg) {
|
||||
const c = (cfg && cfg.canvas && cfg.canvas.appearance) || {}
|
||||
const hex = (k) => normHex(c[k]) || DEFAULTS[k]
|
||||
return {
|
||||
canvasBgLight: hex('canvasBgLight'), canvasBgDark: hex('canvasBgDark'),
|
||||
gridDotLight: hex('gridDotLight'), gridDotDark: hex('gridDotDark'),
|
||||
gridSize: clamp(c.gridSize, 0.8, 2.6, DEFAULTS.gridSize),
|
||||
gridGap: clamp(c.gridGap, 16, 40, DEFAULTS.gridGap),
|
||||
gridOn: c.gridOn !== false,
|
||||
edgeColorLight: hex('edgeColorLight'), edgeColorDark: hex('edgeColorDark'),
|
||||
edgeWidth: clamp(c.edgeWidth, 1, 4, DEFAULTS.edgeWidth),
|
||||
edgeDash: DASH[c.edgeDash] ? c.edgeDash : DEFAULTS.edgeDash,
|
||||
edgeHotLight: hex('edgeHotLight'), edgeHotDark: hex('edgeHotDark'),
|
||||
nodeBgLight: hex('nodeBgLight'), nodeBgDark: hex('nodeBgDark'),
|
||||
nodeBorderLight: hex('nodeBorderLight'), nodeBorderDark: hex('nodeBorderDark'),
|
||||
nodeRadius: clamp(c.nodeRadius, 6, 20, DEFAULTS.nodeRadius),
|
||||
nodeSelWidth: clamp(c.nodeSelWidth, 1, 4, DEFAULTS.nodeSelWidth),
|
||||
accent: hex('accent'),
|
||||
presets: Array.isArray(c.presets) ? c.presets.slice(0, 12) : [],
|
||||
}
|
||||
}
|
||||
|
||||
function apply (cfg, dark) {
|
||||
try {
|
||||
const a = normalize(cfg)
|
||||
const root = g.document && g.document.documentElement
|
||||
if (!root || !root.style) return
|
||||
const set = (k, v) => root.style.setProperty(k, v)
|
||||
set('--iwb-canvas-bg', dark ? a.canvasBgDark : a.canvasBgLight)
|
||||
set('--iwb-brand', a.accent)
|
||||
set('--iwb-grid-dot', dark ? a.gridDotDark : a.gridDotLight)
|
||||
set('--iwb-grid-size', a.gridSize + 'px')
|
||||
set('--iwb-grid-gap', a.gridGap + 'px')
|
||||
set('--iwb-grid-on', a.gridOn ? '1' : '0')
|
||||
set('--iwb-edge', dark ? a.edgeColorDark : a.edgeColorLight)
|
||||
set('--iwb-edge-w', a.edgeWidth + 'px')
|
||||
set('--iwb-edge-dash', DASH[a.edgeDash] || DASH.dashed)
|
||||
set('--iwb-edge-hot', dark ? a.edgeHotDark : a.edgeHotLight)
|
||||
set('--iwb-node-bg', dark ? a.nodeBgDark : a.nodeBgLight)
|
||||
set('--iwb-border', dark ? a.nodeBorderDark : a.nodeBorderLight)
|
||||
set('--iwb-node-radius', a.nodeRadius + 'px')
|
||||
set('--iwb-node-sel-w', a.nodeSelWidth + 'px')
|
||||
} catch (e) { /* 样式写失败不影响功能 */ }
|
||||
}
|
||||
|
||||
function hexToRgb (hex) {
|
||||
const h = normHex(hex) || DEFAULTS.accent
|
||||
return { r: parseInt(h.slice(1, 3), 16), g: parseInt(h.slice(3, 5), 16), b: parseInt(h.slice(5, 7), 16) }
|
||||
}
|
||||
function rgbToHex (r, gg, b) {
|
||||
const p = (n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, '0')
|
||||
return '#' + p(r) + p(gg) + p(b)
|
||||
}
|
||||
function rgbToHsv (r, gg, b) {
|
||||
const R = r / 255, G = gg / 255, B = b / 255
|
||||
const max = Math.max(R, G, B), min = Math.min(R, G, B)
|
||||
const d = max - min
|
||||
let h = 0
|
||||
if (d) {
|
||||
if (max === R) h = ((G - B) / d) % 6
|
||||
else if (max === G) h = (B - R) / d + 2
|
||||
else h = (R - G) / d + 4
|
||||
h *= 60
|
||||
if (h < 0) h += 360
|
||||
}
|
||||
return { h: h, s: max ? d / max : 0, v: max }
|
||||
}
|
||||
function hsvToRgb (h, s, v) {
|
||||
const c = v * s
|
||||
const x = c * (1 - Math.abs(((h / 60) % 2) - 1))
|
||||
const m = v - c
|
||||
let R = 0, G = 0, B = 0
|
||||
if (h < 60) { R = c; G = x } else if (h < 120) { R = x; G = c } else if (h < 180) { G = c; B = x } else if (h < 240) { G = x; B = c } else if (h < 300) { R = x; B = c } else { R = c; B = x }
|
||||
return { r: (R + m) * 255, g: (G + m) * 255, b: (B + m) * 255 }
|
||||
}
|
||||
const lum = (rgb) => {
|
||||
const f = (v) => { const c = v / 255; return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4) }
|
||||
return 0.2126 * f(rgb.r) + 0.7152 * f(rgb.g) + 0.0722 * f(rgb.b)
|
||||
}
|
||||
function contrast (a, b) {
|
||||
const l1 = lum(hexToRgb(a)), l2 = lum(hexToRgb(b))
|
||||
const hi = Math.max(l1, l2), lo = Math.min(l1, l2)
|
||||
return (hi + 0.05) / (lo + 0.05)
|
||||
}
|
||||
const readableOn = (bg) => (contrast(bg, '#1c2333') >= 3 ? '#1c2333' : '#ffffff')
|
||||
|
||||
function ColorPicker (props) {
|
||||
const value = normHex(props && props.value) || DEFAULTS.accent
|
||||
const onChange = (props && props.onChange) || function () {}
|
||||
const [open, setOpen] = React.useState(false)
|
||||
const [hsv, setHsv] = React.useState(() => { const c = hexToRgb(value); return rgbToHsv(c.r, c.g, c.b) })
|
||||
const boxRef = React.useRef(null)
|
||||
|
||||
React.useEffect(() => {
|
||||
const c = hexToRgb(value)
|
||||
setHsv((prev) => {
|
||||
const next = rgbToHsv(c.r, c.g, c.b)
|
||||
return { h: next.s === 0 ? prev.h : next.h, s: next.s, v: next.v }
|
||||
})
|
||||
}, [value])
|
||||
|
||||
const emit = (next) => { const c = hsvToRgb(next.h, next.s, next.v); onChange(rgbToHex(c.r, c.g, c.b)) }
|
||||
const pick = (e) => {
|
||||
const box = boxRef.current
|
||||
if (!box || !box.getBoundingClientRect) return
|
||||
const r = box.getBoundingClientRect()
|
||||
const x = Math.max(0, Math.min(1, (e.clientX - r.left) / r.width))
|
||||
const y = Math.max(0, Math.min(1, (e.clientY - r.top) / r.height))
|
||||
const next = { h: hsv.h, s: x, v: 1 - y }
|
||||
setHsv(next); emit(next)
|
||||
}
|
||||
const hue = (e) => { const next = { h: Number(e.target.value) || 0, s: hsv.s || 0.6, v: hsv.v || 1 }; setHsv(next); emit(next) }
|
||||
const rgb = hexToRgb(value)
|
||||
const setChannel = (k) => (e) => {
|
||||
const n = Math.max(0, Math.min(255, Number(e.target.value) || 0))
|
||||
const c = { ...rgb }; c[k] = n
|
||||
onChange(rgbToHex(c.r, c.g, c.b))
|
||||
}
|
||||
const hueColor = 'hsl(' + Math.round(hsv.h) + ',100%,50%)'
|
||||
|
||||
return el('div', { className: 'iwb-cpick' },
|
||||
el('button', {
|
||||
type: 'button', className: 'iwb-cpick-swatch', title: '点击取色',
|
||||
onClick: () => setOpen((v) => !v),
|
||||
style: { background: value, color: readableOn(value) },
|
||||
}, el('span', { className: 'iwb-cpick-hex' }, value.toUpperCase())),
|
||||
open ? el('div', { className: 'iwb-cpick-pop', onPointerDown: (e) => e.stopPropagation() },
|
||||
el('div', {
|
||||
className: 'iwb-cpick-box', ref: boxRef,
|
||||
onPointerDown: (e) => { e.currentTarget.setPointerCapture && e.currentTarget.setPointerCapture(e.pointerId); pick(e) },
|
||||
onPointerMove: (e) => { if (e.buttons === 1) pick(e) },
|
||||
style: { background: 'linear-gradient(to top, #000, rgba(0,0,0,0)), linear-gradient(to right, #fff, ' + hueColor + ')' },
|
||||
}, el('div', { className: 'iwb-cpick-dot', style: { left: (hsv.s * 100) + '%', top: ((1 - hsv.v) * 100) + '%', background: value } })),
|
||||
el('input', { type: 'range', min: 0, max: 360, value: Math.round(hsv.h), onChange: hue, className: 'iwb-cpick-hue', style: { background: 'linear-gradient(to right,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00)' } }),
|
||||
el('div', { className: 'iwb-cpick-rgb' }, ['r', 'g', 'b'].map((k) => el('label', { key: k, className: 'iwb-cpick-chan' },
|
||||
el('input', { type: 'number', min: 0, max: 255, value: rgb[k], onChange: setChannel(k) }),
|
||||
el('span', null, k.toUpperCase())))),
|
||||
el('div', { className: 'iwb-cpick-foot' },
|
||||
el('input', { className: 'iwb-input iwb-cpick-input', value: value, onChange: (e) => { const v = normHex(e.target.value); if (v) onChange(v) }, title: '支持 #rgb / #rrggbb' }),
|
||||
g.EyeDropper ? el('button', { type: 'button', className: 'iwb-btn iwb-btn-sm', title: '从屏幕取色', onClick: () => { try { new g.EyeDropper().open().then((r) => { const v = normHex(r && r.sRGBHex); if (v) onChange(v) }).catch(() => {}) } catch (e) { /* ignore */ } } }, '吸管') : null,
|
||||
el('button', { type: 'button', className: 'iwb-btn iwb-btn-sm', onClick: () => setOpen(false) }, '完成')),
|
||||
) : null,
|
||||
)
|
||||
}
|
||||
|
||||
function NumberRow (props) {
|
||||
const { label, value, min, max, step, unit, onChange, title } = props
|
||||
return el('div', { className: 'iwb-row' },
|
||||
el('span', { className: 'iwb-label', title: title || '' }, label),
|
||||
el('input', { type: 'range', min, max, step, value, className: 'iwb-appear-range', onChange: (e) => onChange(Number(e.target.value)) }),
|
||||
el('span', { className: 'iwb-appear-val' }, String(value) + (unit || '')),
|
||||
)
|
||||
}
|
||||
|
||||
const PRESETS = [
|
||||
{ name: '默认', values: {} },
|
||||
{ name: '护眼深色', values: { canvasBgLight: '#cfd6cf', canvasBgDark: '#3c4a42', gridDotLight: '#b9c4b9', gridDotDark: '#6f7f73', edgeColorLight: '#9aa79c', edgeColorDark: '#8fa694', accent: '#3f8f6b', edgeHotLight: '#3f8f6b', edgeHotDark: '#7fe0b0', nodeBgLight: '#eef2ee', nodeBgDark: '#4a574e' } },
|
||||
{ name: '高对比', values: { canvasBgLight: '#ffffff', canvasBgDark: '#111111', gridDotLight: '#d0d0d0', gridDotDark: '#3a3a3a', edgeColorLight: '#111111', edgeColorDark: '#ffffff', edgeWidth: 2.4, edgeDash: 'solid', accent: '#0057d8', edgeHotLight: '#0057d8', edgeHotDark: '#59a4ff', nodeBgLight: '#ffffff', nodeBgDark: '#1e1e1e', nodeBorderLight: '#8a8a8a', nodeBorderDark: '#9a9a9a', nodeSelWidth: 2 } },
|
||||
{ name: '纸质', values: { canvasBgLight: '#efe7d7', canvasBgDark: '#3b3227', gridDotLight: '#d8cbb4', gridDotDark: '#5a4c3d', edgeColorLight: '#b9a88c', edgeColorDark: '#a2917a', edgeDash: 'solid', accent: '#8a6f4a', edgeHotLight: '#8a6f4a', edgeHotDark: '#e0c9a0', nodeBgLight: '#faf6ee', nodeBgDark: '#4a4034', nodeBorderLight: '#ddd0b8', nodeBorderDark: '#6b5c49' } },
|
||||
]
|
||||
|
||||
function AppearanceTab (props) {
|
||||
const draft = (props && props.draft) || {}
|
||||
const setDraft = (props && props.setDraft) || function () {}
|
||||
const theme = (props && props.theme) || 'light'
|
||||
const setTheme = (props && props.setTheme) || function () {}
|
||||
const applyTheme = (props && props.applyTheme) || function () {}
|
||||
const value = normalize(draft)
|
||||
const set = (patch) => setDraft((d) => Object.assign({}, d, {
|
||||
canvas: Object.assign({}, d.canvas, { appearance: Object.assign({}, normalize(d), patch) }),
|
||||
}))
|
||||
const setMany = (patch) => set(patch)
|
||||
const resetGroup = (keys) => { const p = {}; for (const k of keys) p[k] = DEFAULTS[k]; set(p) }
|
||||
|
||||
const warnEdge = (edge, bg) => {
|
||||
const r = contrast(edge, bg)
|
||||
return r < 1.5 ? el('div', { className: 'iwb-hint iwb-hint-warn' }, '连线与画布底色对比度仅 ' + r.toFixed(1) + ':1,可能看不清') : null
|
||||
}
|
||||
const importRef = React.useRef(null)
|
||||
const exportPresets = () => {
|
||||
try {
|
||||
const doc = { version: 1, appearance: Object.assign({}, value, { presets: undefined }) }
|
||||
const blob = new Blob([JSON.stringify(doc, null, 2)], { type: 'application/json' })
|
||||
const a = g.document.createElement('a')
|
||||
a.href = URL.createObjectURL(blob)
|
||||
a.download = 'iwb-appearance.json'
|
||||
a.click()
|
||||
setTimeout(() => URL.revokeObjectURL(a.href), 3000)
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
const importFile = (file) => {
|
||||
try {
|
||||
const rd = new g.FileReader()
|
||||
rd.onload = () => {
|
||||
try {
|
||||
const doc = JSON.parse(String(rd.result || '{}'))
|
||||
const src = doc && (doc.appearance || doc)
|
||||
if (!src || typeof src !== 'object') return
|
||||
set(normalize({ canvas: { appearance: src } }))
|
||||
} catch (e) { /* 忽略坏文件 */ }
|
||||
}
|
||||
rd.readAsText(file)
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
return el('div', null,
|
||||
el('div', { className: 'iwb-section-sub' }, '界面主题'),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('span', { className: 'iwb-label' }, '配色模式'),
|
||||
el('select', {
|
||||
className: 'iwb-input', title: '界面配色(亮色保证文字清晰)', value: theme,
|
||||
onChange: (e) => { const t = e.target.value; const v = (t === 'dark' || t === 'system') ? t : 'light'; setTheme(v); applyTheme(v) },
|
||||
},
|
||||
el('option', { value: 'light' }, '亮色(默认:节点灰底 + 内容白)'),
|
||||
el('option', { value: 'dark' }, '暗色'),
|
||||
el('option', { value: 'system' }, '跟随系统'),
|
||||
)),
|
||||
|
||||
el('div', { className: 'iwb-section-sub' }, '预设'),
|
||||
el('div', { className: 'iwb-appear-presets' },
|
||||
PRESETS.map((p) => el('button', { key: p.name, className: 'iwb-btn iwb-btn-sm', onClick: () => setMany(Object.assign({}, DEFAULTS, p.values)), title: '套用「' + p.name + '」' }, p.name)),
|
||||
value.presets.map((p, i) => el('button', { key: 'c' + i, className: 'iwb-btn iwb-btn-sm', onClick: () => set(normalize({ canvas: { appearance: p.values } })), title: '套用自定义预设' }, p.name || ('自定义 ' + (i + 1)))),
|
||||
),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('button', {
|
||||
className: 'iwb-btn iwb-btn-sm',
|
||||
onClick: () => {
|
||||
const name = (g.prompt ? g.prompt('预设名称', '我的配色') : '') || ''
|
||||
if (!name) return
|
||||
const snap = Object.assign({}, value, { presets: undefined })
|
||||
set({ presets: value.presets.concat([{ name: String(name).slice(0, 20), values: snap }]).slice(0, 12) })
|
||||
},
|
||||
}, '保存当前为预设'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: exportPresets }, '导出外观'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => importRef.current && importRef.current.click() }, '导入外观'),
|
||||
el('input', { ref: importRef, type: 'file', accept: 'application/json', style: { display: 'none' }, onChange: (e) => { const f = e.target.files && e.target.files[0]; if (f) importFile(f); e.target.value = '' } }),
|
||||
),
|
||||
|
||||
el('div', { className: 'iwb-section-sub' }, '画布'),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '底色(亮)'), el(ColorPicker, { value: value.canvasBgLight, onChange: (v) => set({ canvasBgLight: v }) })),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '底色(暗)'), el(ColorPicker, { value: value.canvasBgDark, onChange: (v) => set({ canvasBgDark: v }) })),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '网格点(亮)'), el(ColorPicker, { value: value.gridDotLight, onChange: (v) => set({ gridDotLight: v }) })),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '网格点(暗)'), el(ColorPicker, { value: value.gridDotDark, onChange: (v) => set({ gridDotDark: v }) })),
|
||||
el(NumberRow, { label: '网格点大小', value: value.gridSize, min: 0.8, max: 2.6, step: 0.1, unit: 'px', onChange: (v) => set({ gridSize: v }) }),
|
||||
el(NumberRow, { label: '网格间距', value: value.gridGap, min: 16, max: 40, step: 1, unit: 'px', onChange: (v) => set({ gridGap: v }) }),
|
||||
el('label', { className: 'iwb-check' }, el('input', { type: 'checkbox', checked: value.gridOn, onChange: (e) => set({ gridOn: e.target.checked }) }, null), ' 显示网格'),
|
||||
el('div', { className: 'iwb-row' }, el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => resetGroup(['canvasBgLight', 'canvasBgDark', 'gridDotLight', 'gridDotDark', 'gridSize', 'gridGap', 'gridOn']) }, '恢复本组默认')),
|
||||
|
||||
el('div', { className: 'iwb-section-sub' }, '连线'),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '默认色(亮)'), el(ColorPicker, { value: value.edgeColorLight, onChange: (v) => set({ edgeColorLight: v }) })),
|
||||
warnEdge(value.edgeColorLight, value.canvasBgLight),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '默认色(暗)'), el(ColorPicker, { value: value.edgeColorDark, onChange: (v) => set({ edgeColorDark: v }) })),
|
||||
warnEdge(value.edgeColorDark, value.canvasBgDark),
|
||||
el(NumberRow, { label: '默认粗细', value: value.edgeWidth, min: 1, max: 4, step: 0.1, unit: 'px', onChange: (v) => set({ edgeWidth: v }) }),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('span', { className: 'iwb-label' }, '线型'),
|
||||
el('select', { className: 'iwb-input', value: value.edgeDash, onChange: (e) => set({ edgeDash: e.target.value }) },
|
||||
el('option', { value: 'solid' }, '实线'),
|
||||
el('option', { value: 'dashed' }, '虚线'),
|
||||
el('option', { value: 'dotted' }, '点线'),
|
||||
)),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '高亮色(亮)'), el(ColorPicker, { value: value.edgeHotLight, onChange: (v) => set({ edgeHotLight: v }) })),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '高亮色(暗)'), el(ColorPicker, { value: value.edgeHotDark, onChange: (v) => set({ edgeHotDark: v }) })),
|
||||
el('div', { className: 'iwb-hint' }, '高亮色只用于选中节点的上下游连线、悬停连线与临时连线;默认连线永远用上面的「默认色」。'),
|
||||
el('div', { className: 'iwb-row' }, el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => resetGroup(['edgeColorLight', 'edgeColorDark', 'edgeWidth', 'edgeDash', 'edgeHotLight', 'edgeHotDark']) }, '恢复本组默认')),
|
||||
|
||||
el('div', { className: 'iwb-section-sub' }, '节点'),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '节点底色(亮)'), el(ColorPicker, { value: value.nodeBgLight, onChange: (v) => set({ nodeBgLight: v }) })),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '节点底色(暗)'), el(ColorPicker, { value: value.nodeBgDark, onChange: (v) => set({ nodeBgDark: v }) })),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '边框色(亮)'), el(ColorPicker, { value: value.nodeBorderLight, onChange: (v) => set({ nodeBorderLight: v }) })),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '边框色(暗)'), el(ColorPicker, { value: value.nodeBorderDark, onChange: (v) => set({ nodeBorderDark: v }) })),
|
||||
el(NumberRow, { label: '节点圆角', value: value.nodeRadius, min: 6, max: 20, step: 1, unit: 'px', onChange: (v) => set({ nodeRadius: v }) }),
|
||||
el(NumberRow, { label: '选中描边', value: value.nodeSelWidth, min: 1, max: 4, step: 0.5, unit: 'px', onChange: (v) => set({ nodeSelWidth: v }) }),
|
||||
el('div', { className: 'iwb-row' }, el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => resetGroup(['nodeBgLight', 'nodeBgDark', 'nodeBorderLight', 'nodeBorderDark', 'nodeRadius', 'nodeSelWidth']) }, '恢复本组默认')),
|
||||
|
||||
el('div', { className: 'iwb-section-sub' }, '主题色'),
|
||||
el('div', { className: 'iwb-row' }, el('span', { className: 'iwb-label' }, '按钮 / 端口 / 选中框'), el(ColorPicker, { value: value.accent, onChange: (v) => set({ accent: v }) })),
|
||||
el('div', { className: 'iwb-hint' }, '主题色同时用于亮色与暗色主题;作用在按钮、端口、选中框与进度动画上。连线用上面的「连线」分组。'),
|
||||
|
||||
el('div', { className: 'iwb-row', style: { marginTop: 12 } },
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => setMany(Object.assign({}, DEFAULTS, { presets: value.presets })) }, '全部恢复默认')),
|
||||
)
|
||||
}
|
||||
|
||||
g.IWBUIApearance = Object.freeze({ DEFAULTS, PRESETS, DASH, normalize, apply, contrast, ColorPicker, AppearanceTab })
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -169,6 +169,8 @@ function BackupModal(props) {
|
||||
items.outputs = ((r && r.files) || []).map((f) => { const o = Object.assign({}, f); delete o.data; return o })
|
||||
}))
|
||||
await Promise.all(jobs)
|
||||
// 插件(清单 + 源码)随备份走:换机器恢复后不用重装
|
||||
try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.collect) { const ps = await pb.collect(); if (ps && ps.length) items.plugins = ps } } catch (e) { /* 插件快照失败不影响主备份 */ }
|
||||
// 收集图片(画布引用大图 + 勾选的图库缩略图/原图)并读取数据
|
||||
const refMeta = await collectBackupImages()
|
||||
const galleryMeta = (bk.outputs && items.outputs) ? (await collectBackupOutputImages(items.outputs)) : []
|
||||
@@ -364,6 +366,9 @@ function BackupModal(props) {
|
||||
jobs.push(api('workspaces', { workspaces: mergeById((cur && cur.workspaces) || [], items.workspaces.workspaces || []), activeId: (cur && cur.activeId) || '' }))
|
||||
} else jobs.push(api('workspaces', { workspaces: items.workspaces.workspaces || [], activeId: items.workspaces.activeId || '' }))
|
||||
}
|
||||
if (items.plugins && items.plugins.length) {
|
||||
try { const pb = (typeof window !== 'undefined') ? window.IWBRuntimePluginBackup : null; if (pb && pb.restore) await pb.restore(items.plugins) } catch (e) { /* 插件还原失败不阻塞其它项 */ }
|
||||
}
|
||||
if (restoreSel.outputs && items.outputs) {
|
||||
if (restoreMerge) {
|
||||
const cur = await api('outputs').catch(() => ({ files: [] }))
|
||||
@@ -435,28 +440,6 @@ function BackupModal(props) {
|
||||
el('span', { className: 'iwb-backup-item-name' }, label),
|
||||
el('span', { className: 'iwb-backup-item-count' }, n),
|
||||
)
|
||||
// 清理本地数据:清空 localStorage(iwb_*) + IndexedDB(iwb_web),不可撤销
|
||||
const doClear = async () => {
|
||||
if (!(await askConfirm('确定清空本机的全部本地数据吗?\n\n将删除:设置、提示词库、节点组、画布工作台、图库索引与本机图片。\n此操作不可撤销。\n\n建议先「导出备份」再清理。', { title: '清空本地数据', okText: '全部清空' }))) return
|
||||
setClearBusy(true); setClearMsg(null)
|
||||
try {
|
||||
const st = _lstore()
|
||||
const toRemove = st ? st.keys().filter((k) => k && (k.indexOf('iwb_') === 0 || k.indexOf('__iwb_') === 0)) : []
|
||||
for (const k of toRemove) { try { if (st) st.remove(k) } catch (e) { /* ignore */ } }
|
||||
await new Promise((resolve) => {
|
||||
if (typeof indexedDB === 'undefined') return resolve()
|
||||
try {
|
||||
const req = indexedDB.deleteDatabase(StorageContract.indexedDb.name)
|
||||
req.onsuccess = req.onerror = req.onblocked = () => resolve()
|
||||
setTimeout(() => resolve(), 800)
|
||||
} catch (e) { resolve() }
|
||||
})
|
||||
setClearMsg({ type: 'ok', text: '✓ 本地数据已清空,即将刷新页面' })
|
||||
setTimeout(() => { try { location.reload() } catch (e) { /* ignore */ } }, 500)
|
||||
} catch (e) {
|
||||
setClearMsg({ type: 'err', text: '清理失败:' + String((e && e.message) || e) })
|
||||
} finally { setClearBusy(false) }
|
||||
}
|
||||
// 本组件**只以嵌入形式**使用(设置面板的「备份与还原」Tab)。
|
||||
// 2026-10-29:用户要求移除另外两个菜单入口后,独立弹层分支(遮罩 + 标题栏 ✕)已无调用方,
|
||||
// 属于死代码 ⇒ 一并删除;同时嵌入时不套 `.iwb-modal`,避免设置面板里多出一层外框(用户反馈"不要框住了")。
|
||||
@@ -528,14 +511,6 @@ function BackupModal(props) {
|
||||
el('div', { className: 'iwb-backup-note' },
|
||||
'提示:若需连同出图一起备份,请勾选「图库(含缩略图+原图)」(默认不勾选,避免备份体积随出图历史膨胀);画布工作台备份仍只带参考图,生成结果不入画布数据。备份为 ZIP/JSON 文件,请自行妥善保管。',
|
||||
),
|
||||
el('div', { className: 'iwb-backup-sec' },
|
||||
el('div', { className: 'iwb-backup-sec-title' }, '③ 清理本地数据'),
|
||||
el('div', { className: 'iwb-backup-item-count iwb-warn' }, '清空设置/提示词库/节点组/画布/图库及本机图片(IndexedDB)。不可撤销,建议先导出备份。'),
|
||||
el('div', { className: 'iwb-backup-actions' },
|
||||
el('button', { className: 'iwb-btn iwb-btn-danger', disabled: clearBusy, onClick: doClear }, clearBusy ? '清理中…' : '清空全部本地数据'),
|
||||
),
|
||||
clearMsg ? el('div', { className: 'iwb-status-' + (clearMsg.type === 'err' ? 'err' : 'ok') }, clearMsg.text) : null,
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/* ui-desktop-shell.js —— 桌面端外壳适配(2026-11-18)
|
||||
*
|
||||
* 平台迁移后需要「网页做不到、只有桌面壳能做」的三件事,集中放这里,
|
||||
* 避免 app.js 继续膨胀(source-text-ratchet 上限):
|
||||
* 1) 外链一律交给系统浏览器:桌面 webview 里点 <a target=_blank> 会把整个应用导航成网页
|
||||
* 2) 桌面原生通知:WKWebView 不支持 Web Notification
|
||||
* 3) 捕获阶段拦截外链点击(含中键)
|
||||
*
|
||||
* 网页版不装 Tauri,isTauri() 恒 false ⇒ 全部走浏览器原生行为,语义不变。
|
||||
*/
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
const g = /** @type {any} */ (global || {})
|
||||
const EXTERNAL_RE = /^https?:\/\//i
|
||||
|
||||
function tauri () {
|
||||
const T = g.__TAURI__
|
||||
return (T && T.core && typeof T.core.invoke === 'function') ? T : null
|
||||
}
|
||||
|
||||
function openExternal (url) {
|
||||
const u = String(url || '')
|
||||
if (!EXTERNAL_RE.test(u)) return false
|
||||
const T = tauri()
|
||||
if (T) {
|
||||
try { T.core.invoke('open_external_url', { url: u }) } catch (e) { /* 忽略:下面还会尝试原生窗口 */ }
|
||||
return true
|
||||
}
|
||||
try { global.open(u, '_blank', 'noopener') } catch (e) { /* ignore */ }
|
||||
return true
|
||||
}
|
||||
|
||||
/** 生成完成通知:桌面走原生;返回 true 表示已处理(调用方不要再走 Web Notification) */
|
||||
function notifyGenerationDone (info) {
|
||||
if (!tauri()) return false
|
||||
const x = info || {}
|
||||
const total = Number(x.total) || 0
|
||||
const failed = Number(x.failed) || 0
|
||||
const title = failed ? '出图完成(部分失败)' : '出图完成'
|
||||
const body = failed
|
||||
? ('成功 ' + Math.max(0, total - failed) + ' 张,失败 ' + failed + ' 张')
|
||||
: ('共生成 ' + total + ' 张图片')
|
||||
try { tauri().core.invoke('notify_desktop', { title: title, body: body }) } catch (e) { /* ignore */ }
|
||||
return true
|
||||
}
|
||||
|
||||
function notifyDesktop (title, body) {
|
||||
const T = tauri()
|
||||
if (!T) return false
|
||||
try { T.core.invoke('notify_desktop', { title: String(title || ''), body: String(body || '') }) } catch (e) { /* ignore */ }
|
||||
return true
|
||||
}
|
||||
|
||||
/* 捕获阶段拦截外链点击(含中键):桌面端不允许把应用窗口导航走 */
|
||||
function installLinkGuard (isTauri) {
|
||||
if (typeof document === 'undefined' || !document.addEventListener) return false
|
||||
if (isTauri && !isTauri()) return false
|
||||
const pick = (e) => {
|
||||
const t = e.target
|
||||
const a = (t && t.closest) ? t.closest('a[href]') : null
|
||||
if (!a) return ''
|
||||
const href = a.getAttribute('href') || ''
|
||||
return EXTERNAL_RE.test(href) ? href : ''
|
||||
}
|
||||
document.addEventListener('click', (e) => {
|
||||
const href = pick(e)
|
||||
if (!href) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
openExternal(href)
|
||||
}, true)
|
||||
document.addEventListener('auxclick', (e) => {
|
||||
if (e.button !== 1) return
|
||||
const href = pick(e)
|
||||
if (!href) return
|
||||
e.preventDefault()
|
||||
openExternal(href)
|
||||
}, true)
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
g.IWBUIShell = Object.freeze({ openExternal, notifyDesktop, notifyGenerationDone, installLinkGuard })
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -17,7 +17,7 @@
|
||||
// · ctx = { onUpdate, busy, progress, h, stop, refMini },由调用方 renderBodyInner 组装。
|
||||
|
||||
// ── 注入依赖(app.js 在首次渲染时调用 inject 注入)─────────────────────────
|
||||
let I, LocalTextField, autoGrow, React, ReactDOM, combineSourcePairs, downloadUrl, isImageProducer, nodePreviewRefsV2, nodeInheritOf, orderedUniqueRefNodes, outProgUI, outThumbCache, uploadRefToImageHost, wDisplayThumbOf, wImportImage, wPreviewUrlOf, wRawCfg, wResolveImg, wThumbSrc, el, wPluginNodeVariants, wPluginVariantMeta, isBatchSrc, batchSrcText, compareCanvasTextOrder, GenParams, RATIOS, RES_KEYS, RES_MAP, cachedGenerationTasks, classifyErr, fmtDur, presetDisplayName, ratioOfSize, resOfSize, taskStallEndMs, wDedupeTaskIds
|
||||
let I, LocalTextField, autoGrow, React, ReactDOM, combineSourcePairs, downloadUrl, wResolveOutSrc, isImageProducer, nodePreviewRefsV2, nodeInheritOf, orderedUniqueRefNodes, outProgUI, outThumbCache, uploadRefToImageHost, wDisplayThumbOf, wImportImage, wPreviewUrlOf, wRawCfg, wResolveImg, wThumbSrc, el, wPluginNodeVariants, wPluginVariantMeta, isBatchSrc, batchSrcText, compareCanvasTextOrder, GenParams, RATIOS, RES_KEYS, RES_MAP, cachedGenerationTasks, classifyErr, fmtDur, presetDisplayName, ratioOfSize, resOfSize, taskStallEndMs, wDedupeTaskIds
|
||||
function inject(d) {
|
||||
const D = d || {}
|
||||
I = D.I
|
||||
@@ -30,6 +30,7 @@
|
||||
autoGrow = D.autoGrow
|
||||
combineSourcePairs = D.combineSourcePairs
|
||||
downloadUrl = D.downloadUrl
|
||||
wResolveOutSrc = D.wResolveOutputSrc
|
||||
isImageProducer = D.isImageProducer
|
||||
nodePreviewRefsV2 = D.nodePreviewRefsV2
|
||||
nodeInheritOf = D.nodeInheritOf
|
||||
@@ -370,6 +371,9 @@
|
||||
function inheritBar(info, opts) {
|
||||
const o = opts || {}
|
||||
const own = !!info.own
|
||||
// 没有上游节点(纯手写提示词)就不要显示「已固定 / 恢复跟随」,
|
||||
// 否则点「恢复跟随」会把用户手写的文案清空。
|
||||
if (!info.hasUpstream) return null
|
||||
if (!own && !info.text) return null
|
||||
const srcName = nodeLabelOf(info.sourceNodeId, o.nodes)
|
||||
const parts = [
|
||||
@@ -829,7 +833,17 @@
|
||||
el('div', { className: 'iwb-out-cell-meta' }, (r.width || '?') + '×' + (r.height || '?')),
|
||||
el('div', { className: 'iwb-out-cell-actions' },
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', title: '插入为参考图节点', onClick: () => props.onCopyRef && props.onCopyRef(r.url), onPointerDown: stop }, I('copy')),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', title: '下载', onClick: () => downloadUrl(r.url, 'image.png'), onPointerDown: stop }, I('download')),
|
||||
el('button', {
|
||||
className: 'iwb-btn iwb-btn-sm',
|
||||
title: '下载',
|
||||
// v3.25.18:从资料目录的本地归档取图(原图优先),远端 URL 只作兜底
|
||||
onClick: async () => {
|
||||
let src = r.url
|
||||
try { if (wResolveOutSrc) src = (await wResolveOutSrc(r, true)) || r.url } catch (e) { /* 回退远端 */ }
|
||||
downloadUrl(src, 'image.png')
|
||||
},
|
||||
onPointerDown: stop,
|
||||
}, I('download')),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -440,6 +440,15 @@ function SettingsModal(props) {
|
||||
addLlmAddr, addLlmKey, addLlmModel, addLlmProvider, api, delLlmAddr, delLlmKey, delLlmModel, delLlmProvider, draft, llmAddrInput, llmAddrRes, llmAddrTesting, llmKeyInput, llmModelInput, llmTestMsg, llmTestSel, llmTesting, llmWarn, msg, setLlm, setLlmAddr, setLlmAddrDefault, setLlmAddrInput, setLlmDefaultModel, setLlmKey, setLlmKeyInput, setLlmModelInput, setLlmProv, setLlmTestSel, testLlm, testLlmAddrs,
|
||||
}) : el('div', { className: 'iwb-hint' }, 'llmTab 未就绪(请刷新页面)')
|
||||
const imgTab = el('div', null, transferSection)
|
||||
// 外观:画布底色(亮/暗两套)+ 主题色(两套共用)。实现见 src/ui-appearance.js。
|
||||
const appearanceTab = (function () {
|
||||
const A = (typeof window !== 'undefined') ? window.IWBUIApearance : null
|
||||
if (!A || !A.AppearanceTab) return el('div', { className: 'iwb-hint' }, '外观模块未就绪(请刷新页面)')
|
||||
return el('div', { className: 'iwb-section' },
|
||||
el('div', { className: 'iwb-section-title' }, '外观'),
|
||||
el(A.AppearanceTab, { draft, setDraft, theme, setTheme, applyTheme }),
|
||||
)
|
||||
})()
|
||||
const generalTab = Sections ? Sections.renderGeneralTab({
|
||||
imageLibSection: imageLibSection,
|
||||
appVersion: APP_VERSION,
|
||||
@@ -546,11 +555,12 @@ function SettingsModal(props) {
|
||||
BackupModalComp
|
||||
? el(BackupModalComp, { embedded: true, onClose: props.onClose, onSaveNow: props.onSaveNow })
|
||||
: el('div', { className: 'iwb-hint' }, '备份组件未就绪(请刷新页面)'),
|
||||
autoBackupSection,
|
||||
// 桌面版没有这套「localStorage 快照」:真实数据在资料目录,快照价值近零 ⇒ 只在网页版显示
|
||||
isDesk() ? null : autoBackupSection,
|
||||
)
|
||||
|
||||
// 顺序:通用放最前(最常用:目录/外观/图片图库/生成),其它按使用频率排
|
||||
const tabs = [['general', '通用'], ['gen', '生图服务'], ['llm', 'LLM 服务'], ['img', '图片传输'], ['sizes', '尺寸预设'], ['hotkeys', '快捷键'], ['backup', '备份与还原'], ['diag', '诊断'], ['plugins', '插件']]
|
||||
const tabs = [['general', '通用'], ['appearance', '外观'], ['gen', '生图服务'], ['llm', 'LLM 服务'], ['img', '图片传输'], ['sizes', '尺寸预设'], ['hotkeys', '快捷键'], ['backup', '备份与还原'], ['diag', '诊断'], ['plugins', '插件']]
|
||||
return el('div', { className: 'iwb-modal-mask', onWheel: (e) => e.stopPropagation(), onPointerDown: (e) => { if (e.target === e.currentTarget) props.onClose() } },
|
||||
el('div', { className: 'iwb-modal iwb-settings-modal' },
|
||||
el('div', { className: 'iwb-modal-head' },
|
||||
@@ -566,10 +576,10 @@ function SettingsModal(props) {
|
||||
}, I(SET_NAV_ICONS[t[0]] || 'settings'), el('span', null, t[1]))),
|
||||
el('div', { className: 'iwb-set-nav-group' }, '插件'),
|
||||
el('button', { key: 'nav-plugins', className: 'iwb-tab iwb-set-nav-item' + (tab === 'plugins' ? ' iwb-tab-active' : ''), onClick: () => setTab('plugins') }, I('panel'), el('span', null, '插件管理')),
|
||||
pluginItems.map((p) => el('button', { key: 'nav-plugin:' + p.id, className: 'iwb-tab iwb-set-nav-item' + (tab === 'plugin:' + p.id ? ' iwb-tab-active' : ''), onClick: () => setTab('plugin:' + p.id) }, I('star'), el('span', null, p.name))),
|
||||
pluginItems.filter((p) => p && p.enabled).map((p) => el('button', { key: 'nav-plugin:' + p.id, className: 'iwb-tab iwb-set-nav-item' + (tab === 'plugin:' + p.id ? ' iwb-tab-active' : ''), onClick: () => setTab('plugin:' + p.id) }, I('star'), el('span', null, p.name))),
|
||||
),
|
||||
el('div', { className: 'iwb-modal-body' },
|
||||
tab === 'gen' ? genTab : tab === 'llm' ? llmTab : tab === 'img' ? imgTab : tab === 'backup' ? backupTab : tab === 'hotkeys' ? hotkeyTab : tab === 'sizes' ? sizePresetTab : tab === 'plugins' ? pluginsTab : (typeof tab === 'string' && tab.indexOf('plugin:') === 0) ? pluginSettingsPage : tab === 'diag' ? diagTab : generalTab,
|
||||
tab === 'appearance' ? appearanceTab : tab === 'gen' ? genTab : tab === 'llm' ? llmTab : tab === 'img' ? imgTab : tab === 'backup' ? backupTab : tab === 'hotkeys' ? hotkeyTab : tab === 'sizes' ? sizePresetTab : tab === 'plugins' ? pluginsTab : (typeof tab === 'string' && tab.indexOf('plugin:') === 0) ? pluginSettingsPage : tab === 'diag' ? diagTab : generalTab,
|
||||
msg ? el('div', { className: 'iwb-status-' + (msg.type === 'err' ? 'err' : 'ok') }, msg.text) : null,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -123,54 +123,85 @@
|
||||
try { const st = pluginDevStore(); if (st) st.set('iwb_plugin_dev', !!on) } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
// 桌面端插件管理(参考 Obsidian):搜索 + 已安装(开关/设置)+ 可安装(市场)
|
||||
// 桌面端插件管理:两页 —— 管理页(横向列表 + 开关)/ 市场页(卡片墙 + 安装)
|
||||
function DesktopPluginsTab (props) {
|
||||
const { PluginHost, pluginItems, setPluginsRev, setTab, wRuntimePlugins } = props
|
||||
const [market, setMarket] = React.useState(null)
|
||||
const [view, setView] = React.useState('manage')
|
||||
const [market, setMarket] = React.useState(function () {
|
||||
try { const M = (typeof window !== 'undefined') ? window.IWBRuntimePluginMarket : null; return M && M.cached ? M.cached() : null } catch (e) { return null }
|
||||
})
|
||||
const [inst, setInst] = React.useState({})
|
||||
const [q, setQ] = React.useState('')
|
||||
const [msg, setMsg] = React.useState('')
|
||||
const [busy, setBusy] = React.useState('')
|
||||
const [restart, setRestart] = React.useState(false)
|
||||
const [devMode, setDevMode] = React.useState(function () {
|
||||
return pluginDevGet()
|
||||
})
|
||||
const [devMode, setDevMode] = React.useState(function () { return pluginDevGet() })
|
||||
const [mf, setMf] = React.useState('all') // 市场页筛选:all / installed / available
|
||||
const [mt, setMt] = React.useState('') // 市场页标签筛选(空=全部标签)
|
||||
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
|
||||
const refresh = React.useCallback(async () => {
|
||||
if (!D || !D.market) { setMarket([]); return }
|
||||
// 先读本地清单(毫秒级)→ 立刻把「已安装」渲染出来;市场列表(网络)随后补上
|
||||
try {
|
||||
const list = await D.market.list()
|
||||
const cur = await D.market.installed()
|
||||
const map = {}
|
||||
for (const p of (cur || [])) if (p && p.id) map[p.id] = p.version || ''
|
||||
setMarket(list); setInst(map); setMsg('')
|
||||
} catch (e) { setMarket([]); setMsg('市场加载失败:' + String((e && e.message) || e)) }
|
||||
setInst(map)
|
||||
} catch (e) { /* 本地清单失败不阻塞市场请求 */ }
|
||||
try {
|
||||
const list = await D.market.list()
|
||||
setMarket(list); setMsg('')
|
||||
} catch (e) { setMsg('市场加载失败:' + String((e && e.message) || e)) }
|
||||
}, [D])
|
||||
React.useEffect(() => { refresh() }, [refresh])
|
||||
const act = async (kind, id) => {
|
||||
React.useEffect(function () { refresh() }, [refresh])
|
||||
const act = async function (kind, id) {
|
||||
if (!D || !D.market) return
|
||||
setBusy(id)
|
||||
try {
|
||||
const r = kind === 'install' ? await D.market.install(id) : await D.market.uninstall(id)
|
||||
if (!r || !r.ok) { setMsg((r && r.error) || '操作失败'); return }
|
||||
setMsg(kind === 'install' ? '已安装,重启应用后生效' : '已移除外部副本,重启后回退内置')
|
||||
setMsg(kind === 'install' ? '已安装,重启应用后生效' : '已移除')
|
||||
await refresh()
|
||||
setRestart(true)
|
||||
if (kind === 'install') setRestart(true)
|
||||
} finally { setBusy('') }
|
||||
}
|
||||
const toggle = (p, on) => {
|
||||
const r = PluginHost.setEnabled(p.id, on)
|
||||
setPluginsRev((v) => v + 1)
|
||||
if (!r.ok) setMsg(p.name + ':' + r.error)
|
||||
// 用 src 模块加载脚本(不引 app.js 全局),成功后再写启用状态
|
||||
const loadRuntimePlugin = async function (id) {
|
||||
const rec = (wRuntimePlugins || []).find(function (r) { return r && r.id === id })
|
||||
const L = (typeof window !== 'undefined') ? window.IWBRuntimePluginLoader : null
|
||||
if (!rec || !L) { setMsg('插件清单里没有该 id'); return false }
|
||||
let ok = false
|
||||
try {
|
||||
if (rec.source === 'local') ok = await L.loadLocal(rec)
|
||||
else if (rec.source === 'external') ok = await L.loadExternal(rec)
|
||||
else ok = await L.loadBuiltin(rec)
|
||||
} catch (e) { setMsg('加载失败:' + String((e && e.message) || e)); return false }
|
||||
if (!ok) { setMsg('加载失败:' + (rec.error || '脚本已加载但插件未注册')); return false }
|
||||
return true
|
||||
}
|
||||
const toggle = async function (id, on, registered) {
|
||||
setBusy(id)
|
||||
try {
|
||||
// 打开一个「未加载」的插件:先加载脚本,再写启用状态(否则只是记了个开关,插件依然不生效)
|
||||
if (on && !registered) {
|
||||
const okLoad = await loadRuntimePlugin(id)
|
||||
if (!okLoad) return
|
||||
}
|
||||
const r = PluginHost.setEnabled(id, on)
|
||||
if (!r.ok) setMsg('切换失败:' + r.error)
|
||||
else setMsg(on ? '已启用' : '已停用(重启后保持关闭)')
|
||||
} finally {
|
||||
setPluginsRev(function (v) { return v + 1 })
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
const kw = q.trim().toLowerCase()
|
||||
const hit = (name, desc) => !kw || (String(name) + ' ' + String(desc || '')).toLowerCase().indexOf(kw) >= 0
|
||||
const hit = function (name, desc) { return !kw || (String(name) + ' ' + String(desc || '')).toLowerCase().indexOf(kw) >= 0 }
|
||||
const mList = market || []
|
||||
const findM = (id) => mList.find((m) => m && m.id === id) || {}
|
||||
const findM = function (id) { return mList.find(function (m) { return m && m.id === id }) || {} }
|
||||
const regById = {}
|
||||
for (const p of (pluginItems || [])) regById[p.id] = p
|
||||
// 已安装:以资料目录 plugins/ 清单为准(装了就列出来,哪怕加载失败也能看到/移除)
|
||||
const installedRows = Object.keys(inst).map((id) => {
|
||||
const installedRows = Object.keys(inst).map(function (id) {
|
||||
const m = findM(id)
|
||||
const reg = regById[id]
|
||||
return {
|
||||
@@ -178,94 +209,220 @@
|
||||
name: m.name || (reg && reg.name) || id,
|
||||
version: m.version || inst[id] || (reg && reg.version) || '',
|
||||
desc: m.desc || '',
|
||||
author: m.author || '',
|
||||
icon: m.icon || '◻',
|
||||
color: m.color || '#eef2f6',
|
||||
tags: m.tags || [],
|
||||
enabled: reg ? !!reg.enabled : true,
|
||||
compatible: reg ? !!reg.compatible : true,
|
||||
registered: !!reg,
|
||||
newer: !!(m.version && inst[id] && m.version !== inst[id]),
|
||||
}
|
||||
}).filter((row) => hit(row.name, row.desc))
|
||||
const availRows = mList.filter((m) => !(m.id in inst) && !regById[m.id] && hit(m.name, m.desc))
|
||||
const updatable = Object.keys(inst).filter((id) => findM(id).version && findM(id).version !== inst[id]).length
|
||||
const dirHint = (() => {
|
||||
}).filter(function (row) { return hit(row.name, row.desc) })
|
||||
const availRows = mList.filter(function (m) { return !(m.id in inst) && !regById[m.id] && hit(m.name, m.desc) })
|
||||
const updatable = Object.keys(inst).filter(function (id) { const m = findM(id); return m.version && m.version !== inst[id] }).length
|
||||
const dirHint = (function () {
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
return (F && F.dir && F.dir()) ? (F.dir() + '/plugins/') : '资料目录/plugins/'
|
||||
})()
|
||||
return el('div', { className: 'iwb-set-page' },
|
||||
el('div', { className: 'iwb-set-page-title' }, '插件'),
|
||||
el('div', { className: 'iwb-hint' }, '插件从市场安装到:' + dirHint + '(应用本体不再自带插件)'),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('label', { className: 'iwb-check', title: '本地开发用:把插件放到 plugins/local/<id>/plugin.js' },
|
||||
el('input', {
|
||||
type: 'checkbox',
|
||||
checked: devMode,
|
||||
onChange: function (e) {
|
||||
const on = e.target.checked
|
||||
setDevMode(on)
|
||||
pluginDevSet(on)
|
||||
setMsg(on ? '已开启开发者模式,重启后加载 plugins/local/ 下的插件' : '已关闭开发者模式,重启后只加载市场安装的插件')
|
||||
const kb = function (n) { return !n ? '' : (n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(n / 1024)) + ' KB') }
|
||||
|
||||
// ── 管理页:横向列表(名称/版本/作者 + 描述 + 操作 + 开关),像 Obsidian「第三方插件」 ──
|
||||
const manageView = function () {
|
||||
return el('div', { className: 'iwb-set-page' },
|
||||
el('div', { className: 'iwb-set-page-title' }, '插件'),
|
||||
el('div', { className: 'iwb-mk-setrow' },
|
||||
el('div', { className: 'iwb-mk-setrow-main' },
|
||||
el('div', { className: 'iwb-mk-setrow-title' }, '插件市场'),
|
||||
el('div', { className: 'iwb-hint' }, '浏览并安装由官方 / 社区制作的插件'),
|
||||
),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: function () { setView('market'); setMsg('') } }, '浏览'),
|
||||
),
|
||||
el('div', { className: 'iwb-mk-setrow' },
|
||||
el('div', { className: 'iwb-mk-setrow-main' },
|
||||
el('div', { className: 'iwb-mk-setrow-title' }, '插件安装情况'),
|
||||
el('div', { className: 'iwb-hint' }, (installedRows.length ? ('你目前已经安装了 ' + installedRows.length + ' 个插件') : '还没有安装插件') + (updatable ? (',其中 ' + updatable + ' 个可更新') : '')),
|
||||
),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: refresh }, '检查更新'),
|
||||
),
|
||||
el('div', { className: 'iwb-mk-setrow' },
|
||||
el('div', { className: 'iwb-mk-setrow-main' },
|
||||
el('div', { className: 'iwb-mk-setrow-title' }, '开发者模式'),
|
||||
el('div', { className: 'iwb-hint' }, '加载 plugins/local/<id>/plugin.js(未签名,仅本地调试)'),
|
||||
),
|
||||
el('label', { className: 'iwb-switch' },
|
||||
el('input', {
|
||||
type: 'checkbox', checked: devMode,
|
||||
onChange: function (e) {
|
||||
const on = e.target.checked
|
||||
setDevMode(on); pluginDevSet(on)
|
||||
setMsg(on ? '已开启开发者模式,重启后加载 plugins/local/ 下的插件' : '已关闭开发者模式')
|
||||
},
|
||||
}),
|
||||
el('span', { className: 'iwb-switch-track' }, el('span', { className: 'iwb-switch-dot' })),
|
||||
),
|
||||
),
|
||||
el('div', { className: 'iwb-mk-setrow' },
|
||||
el('div', { className: 'iwb-mk-setrow-main' },
|
||||
el('div', { className: 'iwb-mk-setrow-title' }, '插件诊断'),
|
||||
el('div', { className: 'iwb-hint' }, '加载失败时点这里复制诊断 JSON(含清单、运行时状态、错误原因)'),
|
||||
),
|
||||
el('button', {
|
||||
className: 'iwb-btn iwb-btn-sm',
|
||||
onClick: async function () {
|
||||
try {
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
let manifest = /** @type {any} */ ([])
|
||||
try { manifest = await F.plugins.manifest() } catch (e) { manifest = String(e && e.message) }
|
||||
let marketInfo = null
|
||||
try { const mm = await D.market.list(); marketInfo = { ok: true, count: (mm || []).length } } catch (e) { marketInfo = { ok: false, error: String((e && e.message) || e) } }
|
||||
const payload = {
|
||||
market: marketInfo,
|
||||
dir: (F && F.dir) ? F.dir() : '',
|
||||
devMode: pluginDevGet(),
|
||||
manifest: manifest,
|
||||
runtime: (wRuntimePlugins || []).map(function (r) { return { id: r.id, status: r.status, source: r.source, error: r.error || '', file: r.file, version: r.version } }),
|
||||
registered: (pluginItems || []).map(function (p) { return { id: p.id, enabled: p.enabled, compatible: p.compatible } }),
|
||||
}
|
||||
const text = JSON.stringify(payload, null, 2)
|
||||
try { await navigator.clipboard.writeText(text) } catch (e) { try { const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); ta.remove() } catch (e2) { /* ignore */ } }
|
||||
setMsg('诊断已复制到剪贴板')
|
||||
} catch (e) { setMsg('诊断生成失败:' + String((e && e.message) || e)) }
|
||||
},
|
||||
}),
|
||||
' 开发者模式(加载 plugins/local/<id>/plugin.js,未签名)'),
|
||||
),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('label', { className: 'iwb-check', title: '用于本地开发:把插件放到 plugins/local/<id>/plugin.js' },
|
||||
el('input', {
|
||||
type: 'checkbox', checked: devMode,
|
||||
onChange: (e) => {
|
||||
const on = e.target.checked
|
||||
setDevMode(on)
|
||||
pluginDevSet(on)
|
||||
setMsg(on ? '已开启开发者模式,重启后加载 plugins/local/ 下的插件' : '已关闭开发者模式,重启后只加载市场安装的插件')
|
||||
},
|
||||
}),
|
||||
' 开发者模式(加载 plugins/local/<id>/plugin.js,未签名)'),
|
||||
),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('input', { className: 'iwb-input iwb-grow', placeholder: '搜索已安装的插件…', value: q, onChange: (e) => setQ(e.target.value) }),
|
||||
),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('span', { className: 'iwb-hint', style: { flex: '1 1 auto' } },
|
||||
'已安装 ' + installedRows.length + ' 个' + (mList.length ? (' · 市场 ' + mList.length + ' 个 · 可安装 ' + availRows.length + ' 个') : '') + (updatable ? (' · 可更新 ' + updatable + ' 个') : '')),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: refresh }, '检查更新'),
|
||||
),
|
||||
el('div', { className: 'iwb-section-sub' }, '已安装插件'),
|
||||
installedRows.length ? installedRows.map((p) => {
|
||||
const rt = (wRuntimePlugins || []).find((r) => r && r.id === p.id)
|
||||
const status = !p.registered ? '未加载' : (rt && rt.status === 'error' ? '加载失败' : '已加载')
|
||||
const tagWarn = status !== '已加载'
|
||||
return el('div', { key: p.id, className: 'iwb-plugin-item' },
|
||||
el('div', { className: 'iwb-plugin-main' },
|
||||
el('label', { className: 'iwb-plugin-title' },
|
||||
el('input', { type: 'checkbox', checked: p.enabled, disabled: !p.registered || !p.compatible, onChange: (e) => p.registered && toggle(regById[p.id], e.target.checked) }),
|
||||
el('span', null, p.name + ' v' + p.version),
|
||||
el('span', { className: 'iwb-plugin-tag' + (tagWarn ? ' iwb-plugin-tag-warn' : ''), title: (rt && rt.error) || '' }, status),
|
||||
p.newer ? el('span', { className: 'iwb-plugin-tag' }, '可更新') : null,
|
||||
}, '复制诊断'),
|
||||
),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('span', { className: 'iwb-hint', style: { flex: '1 1 auto' } }, '开关灰色或显示「未加载」时,点右侧按钮会当场加载并启用'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!busy, onClick: async function () {
|
||||
const list = installedRows.filter(function (p) { return !p.registered })
|
||||
if (!list.length) { setMsg('已安装的插件都已加载'); return }
|
||||
setBusy('__all__')
|
||||
let ok = 0
|
||||
for (const p of list) {
|
||||
try { const good = await loadRuntimePlugin(p.id); if (good) { PluginHost.setEnabled(p.id, true); ok++ } } catch (e) { /* ignore */ }
|
||||
}
|
||||
setBusy('')
|
||||
setPluginsRev(function (v) { return v + 1 })
|
||||
setMsg('已启用 ' + ok + '/' + list.length + ' 个插件')
|
||||
} }, busy === '__all__' ? '处理中…' : '全部启用'),
|
||||
),
|
||||
el('div', { className: 'iwb-section-sub' }, '已安装插件'),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('input', { className: 'iwb-input iwb-grow', placeholder: '搜索已安装的插件…', value: q, onChange: function (e) { setQ(e.target.value) } }),
|
||||
),
|
||||
installedRows.length ? el('div', { className: 'iwb-mk-list' }, installedRows.map(function (p) {
|
||||
const rt = (wRuntimePlugins || []).find(function (r) { return r && r.id === p.id })
|
||||
const statusText = !p.registered ? '未加载' : (rt && rt.status === 'error' ? '加载失败' : '')
|
||||
const warn = !!statusText
|
||||
return el('div', { key: p.id, className: 'iwb-mk-row' },
|
||||
el('span', { className: 'iwb-mk-avatar', style: { background: p.color } }, p.icon),
|
||||
el('div', { className: 'iwb-mk-row-main' },
|
||||
el('div', { className: 'iwb-mk-row-title' },
|
||||
el('span', { className: 'iwb-mk-row-name' }, p.name),
|
||||
el('span', { className: 'iwb-mk-row-ver' }, 'v' + p.version),
|
||||
p.author ? el('span', { className: 'iwb-mk-row-author' }, p.author === 'official' ? '官方' : p.author) : null,
|
||||
statusText ? el('span', { className: 'iwb-plugin-tag' + (warn ? ' iwb-plugin-tag-warn' : ''), title: (rt && rt.error) || '' }, statusText) : null,
|
||||
p.newer ? el('span', { className: 'iwb-plugin-tag' }, '可更新') : null,
|
||||
),
|
||||
el('div', { className: 'iwb-mk-row-desc' }, p.desc || ''),
|
||||
(rt && rt.error) ? el('div', { className: 'iwb-hint', style: { color: 'var(--iwb-err)' } }, '错误:' + rt.error) : null,
|
||||
),
|
||||
p.desc ? el('div', { className: 'iwb-plugin-desc' }, p.desc) : null,
|
||||
el('div', { className: 'iwb-mk-row-actions' },
|
||||
p.newer ? el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!busy, onClick: function () { act('install', p.id) } }, '更新') : null,
|
||||
p.registered ? el('button', { className: 'iwb-btn iwb-btn-sm', onClick: function () { setTab('plugin:' + p.id) } }, '设置') : null,
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!busy, onClick: function () { act('uninstall', p.id) } }, '移除'),
|
||||
el('label', { className: 'iwb-switch', title: p.registered ? '启用 / 停用' : '未加载,无法启用' },
|
||||
el('input', {
|
||||
type: 'checkbox', checked: p.enabled, disabled: !p.compatible,
|
||||
onChange: function (e) { toggle(p.id, e.target.checked, p.registered) },
|
||||
}),
|
||||
el('span', { className: 'iwb-switch-track' }, el('span', { className: 'iwb-switch-dot' })),
|
||||
),
|
||||
),
|
||||
)
|
||||
})) : el('div', { className: 'iwb-hint' }, kw ? '没有匹配的插件' : (market === null ? '读取插件清单中…' : '还没有安装插件——点上面的「浏览」进入市场')),
|
||||
restart ? el('div', { className: 'iwb-mk-setrow' },
|
||||
el('div', { className: 'iwb-mk-setrow-main' },
|
||||
el('div', { className: 'iwb-mk-setrow-title' }, '需要重启应用才能生效'),
|
||||
el('div', { className: 'iwb-hint' }, '新装的插件在重启后加载'),
|
||||
),
|
||||
el('div', { className: 'iwb-plugin-actions' },
|
||||
p.registered ? el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => setTab('plugin:' + p.id) }, '设置') : null,
|
||||
p.newer ? el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!busy, onClick: () => act('install', p.id) }, '更新') : null,
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!busy, onClick: () => act('uninstall', p.id) }, '移除'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: function () { window.location.reload() } }, '立即重启'),
|
||||
) : null,
|
||||
msg ? el('div', { className: 'iwb-hint' }, msg) : null,
|
||||
)
|
||||
}
|
||||
|
||||
// ── 市场页:卡片墙 + 安装(与 market.maqiart.eu.org 同一套数据/视觉)──
|
||||
const marketView = function () {
|
||||
return el('div', { className: 'iwb-set-page' },
|
||||
el('div', { className: 'iwb-set-page-title' },
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', style: { marginRight: 10 }, onClick: function () { setView('manage') } }, '返回'),
|
||||
'插件市场',
|
||||
),
|
||||
el('div', { className: 'iwb-hint' }, '共 ' + mList.length + ' 个插件 · 安装在 ' + dirHint),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('input', { className: 'iwb-input iwb-grow', placeholder: '搜索插件,例如:出图、抠图、矢量…', value: q, onChange: function (e) { setQ(e.target.value) } }),
|
||||
),
|
||||
(function () {
|
||||
const tags = []
|
||||
for (const m of mList) for (const t of (m.tags || [])) if (tags.indexOf(t) < 0) tags.push(t)
|
||||
return el('div', { className: 'iwb-mk-filters' }, tags.map(function (t) {
|
||||
return el('button', { key: t, className: 'iwb-mk-chip' + (mt === t ? ' on' : ''), onClick: function () { setMt(mt === t ? '' : t) } }, t)
|
||||
}))
|
||||
})(),
|
||||
(function () {
|
||||
const all = mList.filter(function (m) { return hit(m.name, m.desc) })
|
||||
const shown = all.filter(function (m) {
|
||||
if (mt && (m.tags || []).indexOf(mt) < 0) return false
|
||||
const isInst = (m.id in inst) || !!regById[m.id]
|
||||
if (mf === 'installed') return isInst
|
||||
if (mf === 'available') return !isInst
|
||||
return true
|
||||
})
|
||||
return el('div', null,
|
||||
el('div', { className: 'iwb-mk-filters' },
|
||||
el('button', { className: 'iwb-mk-chip' + (mf === 'all' ? ' on' : ''), onClick: function () { setMf('all') } }, '全部 ' + all.length),
|
||||
el('button', { className: 'iwb-mk-chip' + (mf === 'installed' ? ' on' : ''), onClick: function () { setMf('installed') } }, '已安装 ' + all.filter(function (m) { return (m.id in inst) || !!regById[m.id] }).length),
|
||||
el('button', { className: 'iwb-mk-chip' + (mf === 'available' ? ' on' : ''), onClick: function () { setMf('available') } }, '未安装 ' + all.filter(function (m) { return !((m.id in inst) || !!regById[m.id]) }).length),
|
||||
),
|
||||
shown.length ? el('div', { className: 'iwb-mk-grid' }, shown.map(function (m) {
|
||||
const bits = []
|
||||
if (m.author) bits.push(m.author === 'official' ? '官方' : m.author)
|
||||
if (m.version) bits.push('v' + m.version)
|
||||
if (m.size) bits.push(kb(m.size))
|
||||
return el('div', { key: m.id, className: 'iwb-mk-card' },
|
||||
el('div', { className: 'iwb-mk-head' },
|
||||
el('span', { className: 'iwb-mk-avatar', style: { background: m.color || '#eef2f6' } }, m.icon || '◻'),
|
||||
el('div', { className: 'iwb-mk-titles' },
|
||||
el('div', { className: 'iwb-mk-name' }, m.name || m.id,
|
||||
((m.id in inst) || regById[m.id]) ? el('span', { className: 'iwb-plugin-tag', style: { marginLeft: 6 } }, '已安装') : null,
|
||||
),
|
||||
el('div', { className: 'iwb-mk-sub' }, bits.join(' · ')),
|
||||
),
|
||||
el('div', { className: 'iwb-mk-actions' },
|
||||
((m.id in inst) || regById[m.id])
|
||||
? el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!busy, onClick: function () { act('uninstall', m.id) } }, '移除')
|
||||
: el('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-primary', disabled: !!busy, onClick: function () { act('install', m.id) } }, busy === m.id ? '处理中…' : '安装'),
|
||||
),
|
||||
),
|
||||
m.desc ? el('div', { className: 'iwb-mk-desc' }, m.desc) : null,
|
||||
(m.tags && m.tags.length) ? el('div', { className: 'iwb-mk-tags' }, m.tags.map(function (t) { return el('span', { key: t, className: 'iwb-mk-tag' }, t) })) : null,
|
||||
)
|
||||
})) : el('div', { className: 'iwb-hint' }, mList.length ? '没有匹配的插件' : '市场加载中…'),
|
||||
)
|
||||
})(),
|
||||
restart ? el('div', { className: 'iwb-mk-setrow' },
|
||||
el('div', { className: 'iwb-mk-setrow-main' },
|
||||
el('div', { className: 'iwb-mk-setrow-title' }, '需要重启应用才能生效'),
|
||||
el('div', { className: 'iwb-hint' }, '安装完成后重启即可在「管理」页看到'),
|
||||
),
|
||||
)
|
||||
}) : el('div', { className: 'iwb-hint' }, kw ? '没有匹配的插件' : '还没有安装插件——从下面的市场里挑一个'),
|
||||
availRows.length ? el('div', { className: 'iwb-section-sub' }, '可安装(市场)') : null,
|
||||
availRows.map((m) => el('div', { key: m.id, className: 'iwb-plugin-item' },
|
||||
el('div', { className: 'iwb-plugin-main' },
|
||||
el('div', { className: 'iwb-plugin-title' }, el('span', null, (m.name || m.id) + ' v' + m.version)),
|
||||
m.desc ? el('div', { className: 'iwb-plugin-desc' }, m.desc) : null,
|
||||
),
|
||||
el('div', { className: 'iwb-plugin-actions' },
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !!busy, onClick: () => act('install', m.id) }, busy === m.id ? '处理中…' : '安装'),
|
||||
),
|
||||
)),
|
||||
restart ? el('div', { className: 'iwb-row' },
|
||||
el('span', { className: 'iwb-hint', style: { flex: '1 1 auto' } }, '需要重启应用才能生效'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => window.location.reload() }, '立即重启'),
|
||||
) : null,
|
||||
msg ? el('div', { className: 'iwb-hint' }, msg) : null,
|
||||
)
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: function () { window.location.reload() } }, '立即重启'),
|
||||
) : null,
|
||||
msg ? el('div', { className: 'iwb-hint' }, msg) : null,
|
||||
)
|
||||
}
|
||||
|
||||
return view === 'market' ? marketView() : manageView()
|
||||
}
|
||||
|
||||
function renderPluginsTab (ctx) {
|
||||
@@ -348,27 +505,26 @@
|
||||
function VersionBlock (props) {
|
||||
const version = props && props.version ? String(props.version) : ''
|
||||
const [msg, setMsg] = React.useState('')
|
||||
const [found, setFound] = React.useState(null)
|
||||
const invoke = (cmd) => {
|
||||
const T = (typeof window !== 'undefined') ? window.__TAURI__ : null
|
||||
if (!T || !T.core || typeof T.core.invoke !== 'function') return Promise.reject(new Error('Tauri 未就绪'))
|
||||
return T.core.invoke(cmd)
|
||||
}
|
||||
const check = async () => {
|
||||
try {
|
||||
const U = (typeof window !== 'undefined' && window.__TAURI__ && window.__TAURI__.updater) ? window.__TAURI__.updater : null
|
||||
if (!U || typeof U.check !== 'function') {
|
||||
setMsg('在线更新尚未启用:需要配置更新源地址与签名公钥(见 docs/DESKTOP_UPDATE.md)')
|
||||
return
|
||||
}
|
||||
setMsg('正在检查…')
|
||||
const u = await U.check()
|
||||
if (!u) { setMsg('已是最新版本'); return }
|
||||
setMsg('发现新版本 ' + (u.version || '') + ',点「立即更新」下载安装')
|
||||
window.__IWB_UPDATE__ = u
|
||||
} catch (e) { setMsg('检查失败:' + String((e && e.message) || e)) }
|
||||
const r = await invoke('check_update')
|
||||
if (!r) { setFound(null); setMsg('已是最新版本(v' + version + ')'); return }
|
||||
setFound(r)
|
||||
setMsg('发现新版本 v' + (r.version || '') + (r.notes ? ':' + r.notes : ''))
|
||||
} catch (e) { setFound(null); setMsg('检查失败:' + String((e && e.message) || e)) }
|
||||
}
|
||||
const install = async () => {
|
||||
try {
|
||||
const u = window.__IWB_UPDATE__
|
||||
if (!u || typeof u.downloadAndInstall !== 'function') { setMsg('没有可安装的更新'); return }
|
||||
setMsg('正在下载安装…')
|
||||
await u.downloadAndInstall()
|
||||
setMsg('安装完成,请重启应用')
|
||||
setMsg('正在下载并安装,完成后会自动重启…')
|
||||
await invoke('install_update')
|
||||
setMsg('安装完成,正在重启…')
|
||||
} catch (e) { setMsg('更新失败:' + String((e && e.message) || e)) }
|
||||
}
|
||||
return el('div', null,
|
||||
@@ -377,9 +533,9 @@
|
||||
el('span', { className: 'iwb-label' }, '版本'),
|
||||
el('span', { className: 'iwb-hint', style: { flex: '1 1 auto' } }, version || '未知'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: check }, '检查更新'),
|
||||
window.__IWB_UPDATE__ ? el('button', { className: 'iwb-btn iwb-btn-sm', onClick: install }, '立即更新') : null,
|
||||
found ? el('button', { className: 'iwb-btn iwb-btn-sm iwb-btn-primary', onClick: install }, '立即更新') : null,
|
||||
),
|
||||
el('div', { className: 'iwb-hint' }, '当前为本地目录版;在线更新需要「更新源 + 签名密钥」两样东西配好才会生效。'),
|
||||
el('div', { className: 'iwb-hint' }, '更新源:download.maqiart.eu.org/updates/latest.json(签名校验通过才会安装)'),
|
||||
msg ? el('div', { className: 'iwb-hint' }, msg) : null,
|
||||
)
|
||||
}
|
||||
@@ -388,7 +544,8 @@
|
||||
const D = (typeof window !== 'undefined') ? window.IWBDesktop : null
|
||||
const enabled = !!(D && D.isTauri && D.isTauri())
|
||||
const [dir, setDir] = React.useState(() => (enabled ? D.getDownloadDir() : ''))
|
||||
const [silent, setSilent] = React.useState(() => (enabled ? !!D.getSilentSave() : false))
|
||||
// 自动下载(v3.25.20):勾选 = 出图完成自动存到本目录;未勾 = 点「下载」时存(有目录就不弹框)
|
||||
const [autoDl, setAutoDl] = React.useState(() => (enabled && D.getAutoDownload ? !!D.getAutoDownload() : false))
|
||||
const [note, setNote] = React.useState('')
|
||||
const F = (typeof window !== 'undefined') ? window.IWBStorageFile : null
|
||||
const [dataDir, setDataDir] = React.useState(() => (F && F.dir ? F.dir() : ''))
|
||||
@@ -397,8 +554,8 @@
|
||||
try { const d = await D.pickDownloadDir(); if (d) { setDir(d); setNote('已保存') } else setNote('已取消') }
|
||||
catch (e) { setNote('失败:' + String((e && e.message) || e)) }
|
||||
}
|
||||
const clear = () => { try { D.setDownloadDir('') } catch (e) { /* ignore */ } setDir(''); setSilent(false); try { D.setSilentSave(false) } catch (e) { /* ignore */ } setNote('已清除,恢复为跟随系统') }
|
||||
const toggleSilent = (v) => { setSilent(v); try { D.setSilentSave(v) } catch (e) { /* ignore */ } setNote(v ? '已开启:批量保存不再逐个弹框' : '已关闭:每次保存都弹另存为对话框') }
|
||||
const clear = () => { try { D.setDownloadDir('') } catch (e) { /* ignore */ } setDir(''); setAutoDl(false); try { if (D.setAutoDownload) D.setAutoDownload(false) } catch (e) { /* ignore */ } setNote('已清除,恢复为跟随系统') }
|
||||
const toggleAutoDl = (v) => { setAutoDl(v); try { if (D.setAutoDownload) D.setAutoDownload(v) } catch (e) { /* ignore */ } setNote(v ? '已开启:出图完成后自动保存到该目录' : '已关闭:出图后不自动保存,点「下载」时才落盘') }
|
||||
const pickDataDir = async () => {
|
||||
try {
|
||||
const d = await F.pickDir()
|
||||
@@ -438,9 +595,16 @@
|
||||
const rDry = await F.gcImages({ dryRun: true })
|
||||
if (!rDry.ok) { setNote('检查失败:' + rDry.error); return }
|
||||
if (!rDry.orphans) { setNote('没有未引用的图片'); return }
|
||||
if (!(await askConfirm('发现 ' + rDry.orphans + ' 个文件没有被画布/图库引用。移动到 trash/(不直接删除)?', { title: '清理未引用图片', okText: '移动' }))) return
|
||||
// 确认弹窗必须把「会不会动到在用的图」讲清楚:这是破坏性动作,不能只报一个数字。
|
||||
const lines = ['发现 ' + rDry.orphans + ' 个文件没有被画布/图库引用。']
|
||||
if (rDry.keptByCanvas) lines.push('其中 ' + rDry.keptByCanvas + ' 张虽然登记表里没有,但画布仍在引用 → 会自动保留。')
|
||||
if (rDry.dangling) lines.push('另有 ' + rDry.dangling + ' 处画布引用已经找不到图片(之前丢的,本次不影响它们)。')
|
||||
lines.push('移动到 trash/(不直接删除,可在回收站找回)?')
|
||||
if (!(await askConfirm(lines.join('\n'), { title: '清理未引用图片', okText: '移动' }))) return
|
||||
const rGo = await F.gcImages({ dryRun: false })
|
||||
setNote(rGo.ok ? ('已移入 trash/:' + rGo.moved + ' 个文件') : ('清理失败:' + rGo.error))
|
||||
setNote(rGo.ok
|
||||
? ('已移入 trash/:' + rGo.moved + ' 个文件' + (rGo.dangling ? (';另有 ' + rGo.dangling + ' 处引用已缺图') : ''))
|
||||
: ('清理失败:' + rGo.error))
|
||||
} catch (e) { setNote('清理失败:' + String((e && e.message) || e)) }
|
||||
} }, '清理未引用图片'),
|
||||
),
|
||||
@@ -450,10 +614,11 @@
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: pick }, '选择…'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: clear }, '清除'),
|
||||
),
|
||||
el('label', { className: 'iwb-check', title: dir ? '' : '需先选择默认下载文件夹' },
|
||||
el('input', { type: 'checkbox', checked: silent, disabled: !dir, onChange: (e) => toggleSilent(e.target.checked) }, null),
|
||||
' 启用(点「下载」直接写进这里,不弹窗)'),
|
||||
el('div', { className: 'iwb-hint' }, '只是成品出口:下载/导出时写到这里,和数据库里的图不是同一份;关闭则每次弹另存为。'),
|
||||
el('label', { className: 'iwb-check', title: dir ? '勾选后出图完成自动保存到上面的目录' : '需先选择导出目录才能开启自动下载' },
|
||||
el('input', { type: 'checkbox', checked: autoDl, disabled: !dir, onChange: (e) => toggleAutoDl(e.target.checked) }, null),
|
||||
' 自动下载'),
|
||||
el('div', { className: 'iwb-hint' }, '设了目录:点「下载」直接存到这里,不弹框;没设目录:点「下载」时弹选择框。'),
|
||||
el('div', { className: 'iwb-hint' }, '勾选「自动下载」:出图完成后自动保存到上面的目录(需先选目录)。'),
|
||||
note ? el('div', { className: 'iwb-hint' }, note) : null,
|
||||
)
|
||||
}
|
||||
@@ -478,19 +643,12 @@
|
||||
}
|
||||
|
||||
function renderGeneralTab (ctx) {
|
||||
const { TASK_STALL_END_MAX, TASK_STALL_END_MIN, appVersion, applyTheme, draft, imageLibSection, setDraft, setTheme, theme } = ctx
|
||||
const { TASK_STALL_END_MAX, TASK_STALL_END_MIN, appVersion, draft, imageLibSection, setDraft } = ctx
|
||||
const generalTab = el('div', { className: 'iwb-section' },
|
||||
el('div', { className: 'iwb-section-title' }, '数据与目录'),
|
||||
// 桌面端才有目录概念;网页版退回原来的浏览器说明
|
||||
isDesk() ? el(DownloadDirBlock, null) : el(DataDirRow, null),
|
||||
el('div', { style: { height: 16 } }),
|
||||
el('div', { className: 'iwb-section-sub' }, '外观'),
|
||||
el('select', { className: 'iwb-input', title: '界面配色(亮色保证文字清晰)', value: theme, onChange: (e) => { const t = e.target.value; const v = (t === 'dark' || t === 'system') ? t : 'light'; setTheme(v); applyTheme(v) } },
|
||||
el('option', { value: 'light' }, '亮色(默认:节点灰底 + 内容白)'),
|
||||
el('option', { value: 'dark' }, '暗色'),
|
||||
el('option', { value: 'system' }, '跟随系统'),
|
||||
),
|
||||
el('div', { style: { height: 16 } }),
|
||||
el('div', { className: 'iwb-section-sub' }, '生成'),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('label', { className: 'iwb-label' }, '等待多久后允许提前结束(分钟)'),
|
||||
@@ -548,38 +706,77 @@
|
||||
return transferSection
|
||||
}
|
||||
|
||||
// 插件自定义设置块(2026-11-19):spec.type === 'custom' 时由插件自己渲染一整块
|
||||
// DOM(例如浏览器的「分组书签管理器」),宿主只提供挂载点。
|
||||
// 为什么不让插件直接返回 React 元素:插件是运行时下载的独立脚本,拿不到宿主的
|
||||
// React 实例(也没有共享模块),只能给它一个原生 DOM 容器。
|
||||
function PluginCustomSetting (props) {
|
||||
const boxRef = React.useRef(null)
|
||||
const spec = props.spec
|
||||
// 依赖里放 value:commit 之后父组件带着新值重渲染,这里才重建;同值重渲染
|
||||
// (别的设置项变更、开关插件)不会重建,避免把正在输入的框冲掉。
|
||||
React.useLayoutEffect(function () {
|
||||
const box = boxRef.current
|
||||
if (!box) return undefined
|
||||
box.innerHTML = ''
|
||||
let node = null
|
||||
try {
|
||||
node = spec.render({ value: props.value, commit: props.commit, spec: spec, pluginId: props.pluginId })
|
||||
} catch (e) {
|
||||
node = null
|
||||
// 插件渲染异常不该把整个设置页拖白:就地降级成一行说明
|
||||
if (typeof console !== 'undefined') console.error('[plugin-setting] 自定义设置渲染失败', e)
|
||||
}
|
||||
if (node && node.nodeType === 1) box.appendChild(node)
|
||||
else box.textContent = '该设置项需要更新版本的插件或客户端。'
|
||||
return function () { box.innerHTML = '' }
|
||||
}, [props.value, props.pluginId, spec])
|
||||
return el('div', { className: 'iwb-plugin-setting-custom', ref: boxRef })
|
||||
}
|
||||
|
||||
function renderPluginSettingsPage (ctx) {
|
||||
const { PluginHost, activePlugin, setMsg, setPluginsRev, setTab } = ctx
|
||||
const pluginSettingsPage = activePlugin ? el('div', { className: 'iwb-set-page' },
|
||||
el('div', { className: 'iwb-set-page-head' },
|
||||
el('div', { className: 'iwb-set-page-headtext' },
|
||||
el('div', { className: 'iwb-set-page-title' }, activePlugin.name),
|
||||
el('div', { className: 'iwb-hint' }, activePlugin.id + ' · v' + activePlugin.version + (activePlugin.compatible ? '' : ' · apiVersion 不兼容') + (activePlugin.enabled ? ' · 已启用' : ' · 未启用')),
|
||||
el('div', { className: 'iwb-mk-setrow' },
|
||||
el('div', { className: 'iwb-mk-setrow-main' },
|
||||
el('div', { className: 'iwb-mk-setrow-title' }, activePlugin.name,
|
||||
el('span', { className: 'iwb-plugin-tag' + (activePlugin.enabled ? '' : ' iwb-plugin-tag-warn'), style: { marginLeft: 8 } }, activePlugin.enabled ? '已启用' : '未启用'),
|
||||
activePlugin.compatible ? null : el('span', { className: 'iwb-plugin-tag iwb-plugin-tag-warn', style: { marginLeft: 4 } }, 'apiVersion 不兼容'),
|
||||
),
|
||||
el('div', { className: 'iwb-hint' }, activePlugin.id + ' · v' + activePlugin.version),
|
||||
),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', disabled: !activePlugin.compatible, onClick: () => { const r = PluginHost.setEnabled(activePlugin.id, !activePlugin.enabled); setPluginsRev((v) => v + 1); if (!r.ok) setMsg({ type: 'err', text: r.error }) } }, activePlugin.enabled ? '停用' : '启用'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: function () { setTab('plugins') } }, '返回'),
|
||||
),
|
||||
activePlugin.error ? el('div', { className: 'iwb-status-err' }, activePlugin.error) : null,
|
||||
Object.keys(activePlugin.settingsSchema || {}).length ? Object.keys(activePlugin.settingsSchema).map((key) => {
|
||||
el('div', { className: 'iwb-section-sub' }, '设置'),
|
||||
Object.keys(activePlugin.settingsSchema || {}).length ? Object.keys(activePlugin.settingsSchema).map(function (key) {
|
||||
const spec = activePlugin.settingsSchema[key] || {}
|
||||
const value = activePlugin.settings && activePlugin.settings[key] !== undefined ? activePlugin.settings[key] : spec.default
|
||||
const commit = (next) => { PluginHost.setSetting(activePlugin.id, key, next); setPluginsRev((v) => v + 1) }
|
||||
return el('div', { key, className: 'iwb-set-row' },
|
||||
el('div', { className: 'iwb-set-row-text' },
|
||||
el('div', { className: 'iwb-set-row-title' }, spec.label || key),
|
||||
spec.desc ? el('div', { className: 'iwb-set-row-desc' }, spec.desc) : null,
|
||||
const commit = function (next) { PluginHost.setSetting(activePlugin.id, key, next); setPluginsRev(function (v) { return v + 1 }) }
|
||||
const isCustom = spec.type === 'custom' && typeof spec.render === 'function'
|
||||
// 说明在上、控件在下(左对齐):右侧 260px 的窄框放地址/多行内容既看不全也
|
||||
// 改不动;boolean 仍是行末开关(这类是「开/关」而不是填写内容)。
|
||||
const stacked = isCustom || spec.type === 'text' || spec.type === 'number'
|
||||
return el('div', { key: key, className: 'iwb-mk-setrow' + (stacked ? ' iwb-mk-setrow-col' : '') },
|
||||
el('div', { className: 'iwb-mk-setrow-main' },
|
||||
el('div', { className: 'iwb-mk-setrow-title' }, spec.label || key),
|
||||
spec.desc ? el('div', { className: 'iwb-hint' }, spec.desc) : null,
|
||||
),
|
||||
spec.type === 'boolean'
|
||||
? el('input', { type: 'checkbox', checked: Boolean(value), onChange: (e) => commit(e.target.checked) })
|
||||
: el('input', {
|
||||
className: 'iwb-input', type: spec.type === 'number' ? 'number' : 'text',
|
||||
value: value === undefined ? '' : String(value),
|
||||
onChange: (e) => commit(spec.type === 'number' ? Number(e.target.value) : e.target.value),
|
||||
}),
|
||||
? el('label', { className: 'iwb-switch' },
|
||||
el('input', { type: 'checkbox', checked: Boolean(value), onChange: function (e) { commit(e.target.checked) } }),
|
||||
el('span', { className: 'iwb-switch-track' }, el('span', { className: 'iwb-switch-dot' })),
|
||||
)
|
||||
: isCustom
|
||||
? el(PluginCustomSetting, { key: 'custom-' + key, spec: spec, value: value, commit: commit, pluginId: activePlugin.id })
|
||||
: el('input', {
|
||||
className: 'iwb-input', type: spec.type === 'number' ? 'number' : 'text',
|
||||
style: { maxWidth: '520px' },
|
||||
value: value === undefined ? '' : String(value),
|
||||
onChange: function (e) { commit(spec.type === 'number' ? Number(e.target.value) : e.target.value) },
|
||||
}),
|
||||
)
|
||||
}) : el('div', { className: 'iwb-hint' }, '该插件没有可配置项。'),
|
||||
el('div', { className: 'iwb-row', style: { marginTop: '12px' } },
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => setTab('plugins') }, '← 返回插件列表'),
|
||||
),
|
||||
) : el('div', { className: 'iwb-hint' }, '插件不存在或已卸载。')
|
||||
return pluginSettingsPage
|
||||
}
|
||||
@@ -622,7 +819,7 @@
|
||||
const { addLlmAddr, addLlmKey, addLlmModel, addLlmProvider, api, delLlmAddr, delLlmKey, delLlmModel, delLlmProvider, draft, llmAddrInput, llmAddrRes, llmAddrTesting, llmKeyInput, llmModelInput, llmTestMsg, llmTestSel, llmTesting, llmWarn, msg, setLlm, setLlmAddr, setLlmAddrDefault, setLlmAddrInput, setLlmDefaultModel, setLlmKey, setLlmKeyInput, setLlmModelInput, setLlmProv, setLlmTestSel, testLlm, testLlmAddrs } = ctx
|
||||
const llmTab = el('div', { className: 'iwb-section' },
|
||||
el('div', { className: 'iwb-section-title' }, 'LLM 渠道(可选,用于提示词润色)'),
|
||||
el('div', { className: 'iwb-hint' }, '支持多个渠道:每个渠道独立 Base URL / 多个 Key / 多个模型,可分别测试;润色使用「默认渠道」。已保存的 Key 也能直接选择测试。'),
|
||||
el('div', { className: 'iwb-hint' }, '可选 · 用于提示词润色;润色使用「默认渠道」。'),
|
||||
(draft.llm.providers || []).length
|
||||
? draft.llm.providers.map((p, pi) => {
|
||||
const isDef = p.id === draft.llm.defaultProviderId
|
||||
@@ -639,19 +836,19 @@
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm' + (isDef ? ' iwb-btn-primary' : ''), title: isDef ? '当前默认渠道(润色用)' : '设为默认渠道', onClick: () => setLlm({ defaultProviderId: p.id }) }, isDef ? '✓ 默认' : '设为默认'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', title: '删除该渠道', onClick: () => delLlmProvider(pi) }, '删除'),
|
||||
),
|
||||
el('div', { className: 'iwb-label' }, '地址(可多个,第一行为主地址;填到 /v1 为止,不要带 /chat/completions —— 应用会自动拼接口路径)'),
|
||||
el('div', { className: 'iwb-label', title: '可填多个;第一行是主地址。地址填到 /v1 为止,不要带 /chat/completions —— 应用会自动拼接口路径' }, '地址'),
|
||||
[p.baseUrl || ''].concat(p.fallbacks || []).map((a, ai) => el('div', { key: ai, className: 'iwb-row' },
|
||||
el('input', { className: 'iwb-input iwb-grow', value: a || '', placeholder: ai === 0 ? '主地址,如 https://api.example.com/v1' : '备用地址,如 https://api2.example.com/v1', onChange: (e) => setLlmAddr(pi, ai, e.target.value) }),
|
||||
ai === 0 ? el('span', { className: 'iwb-hint iwb-llm-main' }, '主') : el('button', { className: 'iwb-btn iwb-btn-sm', title: '设为主地址(润色优先使用)', onClick: () => setLlmAddrDefault(pi, ai) }, '设为主'),
|
||||
el('button', { className: 'iwb-btn iwb-btn-xs', title: '删除该地址', onClick: () => delLlmAddr(pi, ai) }, '×'),
|
||||
)),
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('input', { className: 'iwb-input iwb-grow', value: llmAddrInput[pi] || '', placeholder: '备用地址,回车添加(填到 /v1 为止,不要带 /chat/completions)', onChange: (e) => setLlmAddrInput((m) => ({ ...m, [pi]: e.target.value })), onKeyDown: (e) => { if (e.key === 'Enter') { e.preventDefault(); addLlmAddr(pi) } } }),
|
||||
el('input', { className: 'iwb-input iwb-grow', value: llmAddrInput[pi] || '', placeholder: '备用地址(可选),回车添加', onChange: (e) => setLlmAddrInput((m) => ({ ...m, [pi]: e.target.value })), onKeyDown: (e) => { if (e.key === 'Enter') { e.preventDefault(); addLlmAddr(pi) } } }),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => addLlmAddr(pi) }, '+ 地址'),
|
||||
el('button', { className: 'iwb-btn', disabled: !!llmAddrTesting[pi], onClick: () => testLlmAddrs(pi) }, llmAddrTesting[pi] ? '测试中…' : '测全部地址'),
|
||||
),
|
||||
(llmAddrRes[pi] && llmAddrRes[pi].length) ? el('div', { className: 'iwb-llm-addrres' }, llmAddrRes[pi].map((r, ri) => el('div', { key: ri, className: 'iwb-hint', style: { color: r.ok ? '#15803d' : '#b91c1c', whiteSpace: 'pre-wrap' } }, (r.ok ? '✓ ' : '✗ ') + (r.url || '') + ' · ' + r.ms + 'ms' + (r.ok ? (' · ' + r.models + ' 模型') : (' · ' + (r.error || '')))))) : null,
|
||||
el('div', { className: 'iwb-label' }, 'Key(可多个;名称框窄、密钥框占满;测试时选择用哪个 Key)'),
|
||||
el('div', { className: 'iwb-label', title: '可填多个 Key;测试时可选择用哪个' }, 'Key'),
|
||||
pKeys.map((k) => el('div', { key: k.id, className: 'iwb-row' },
|
||||
el('input', { className: 'iwb-input iwb-llm-keyname', value: k.name || '', placeholder: '名称', title: 'Key 名称', onChange: (e) => setLlmKey(pi, k.id, { name: e.target.value }) }),
|
||||
el('input', { className: 'iwb-input iwb-grow', value: k.value || '', placeholder: k.masked ? ('已保存 ' + k.masked + '(留空保持不变,重新输入覆盖)') : 'API Key', onChange: (e) => setLlmKey(pi, k.id, { value: e.target.value }) }),
|
||||
@@ -662,7 +859,7 @@
|
||||
el('input', { className: 'iwb-input iwb-grow', value: keyInp.value || '', placeholder: '新 API Key', onChange: (e) => setLlmKeyInput((m) => ({ ...m, [pi]: Object.assign({}, m[pi] || {}, { value: e.target.value }) })) }),
|
||||
el('button', { className: 'iwb-btn iwb-btn-sm', onClick: () => addLlmKey(pi) }, '+ Key'),
|
||||
),
|
||||
el('div', { className: 'iwb-label' }, '模型(「✓」为默认模型,润色用;点击名称切换默认)'),
|
||||
el('div', { className: 'iwb-label', title: '点模型名切换默认(✓);润色用默认模型' }, '模型'),
|
||||
pModels.length ? el('div', { className: 'iwb-modellist' }, pModels.map((m, mi) => {
|
||||
const active = (p.defaultModel || '') === m.name
|
||||
return el('div', { key: mi, className: 'iwb-modelrow' + (active ? ' iwb-modelrow-active' : '') },
|
||||
@@ -690,10 +887,10 @@
|
||||
el('div', { className: 'iwb-row' },
|
||||
el('button', { className: 'iwb-btn', onClick: addLlmProvider }, '+ 添加渠道'),
|
||||
),
|
||||
el('div', { className: 'iwb-label' }, '默认润色指令(全局模板,LLM 节点内可覆盖;最多两行,可滚动)'),
|
||||
el('div', { className: 'iwb-label', title: '全局模板;LLM 节点内可覆盖' }, '默认润色指令'),
|
||||
el('textarea', { className: 'iwb-input iwb-hdrbox', style: { minHeight: '40px', maxHeight: '64px', overflowY: 'auto' }, value: draft.llm.defaultInstruction || '', onChange: (e) => setLlm({ defaultInstruction: e.target.value }) }, null),
|
||||
llmWarn ? el('div', { className: 'iwb-hint', style: { color: '#b91c1c' } }, llmWarn) : null,
|
||||
el('div', { className: 'iwb-hint' }, '流程可不经过 LLM(直接连 生图)。LLM 节点未填指令时使用此模板。默认渠道缺失时使用第一个渠道。'),
|
||||
el('div', { className: 'iwb-hint' }, '流程可不经过 LLM(直接连生图);节点未填指令时用此模板。'),
|
||||
)
|
||||
return llmTab
|
||||
}
|
||||
@@ -961,7 +1158,7 @@
|
||||
defaultInstruction: draft.llm.defaultInstruction || '',
|
||||
},
|
||||
security: { password: draft.sec.clear ? '__CLEAR__' : ((draft.sec.password && draft.sec.password.trim()) || (draft.sec.hasPassword ? '__KEEP__' : '')) },
|
||||
canvas: { hotkeys: Object.assign({}, HOTKEY_DEFAULTS, draft.canvas.hotkeys || {}), sizePresets: Array.isArray(draft.canvas.sizePresets) && draft.canvas.sizePresets.length ? draft.canvas.sizePresets : RATIOS, generationConcurrency: Math.max(GEN_CONCURRENCY_MIN, Math.min(GEN_CONCURRENCY_MAX, Number(draft.canvas.generationConcurrency) || GEN_CONCURRENCY_DEFAULT)), taskStallEndMs: Math.max(TASK_STALL_END_MIN, Math.min(TASK_STALL_END_MAX, Number(draft.canvas.taskStallEndMs) || 300000)), autoSaveImages: draft.canvas.autoSaveImages !== false, backupOriginals: draft.canvas.backupOriginals !== false },
|
||||
canvas: { hotkeys: Object.assign({}, HOTKEY_DEFAULTS, draft.canvas.hotkeys || {}), appearance: (function () { const A = (typeof window !== 'undefined') ? window.IWBUIApearance : null; return A ? A.normalize(draft) : ((draft.canvas && draft.canvas.appearance) || {}) })(), sizePresets: Array.isArray(draft.canvas.sizePresets) && draft.canvas.sizePresets.length ? draft.canvas.sizePresets : RATIOS, generationConcurrency: Math.max(GEN_CONCURRENCY_MIN, Math.min(GEN_CONCURRENCY_MAX, Number(draft.canvas.generationConcurrency) || GEN_CONCURRENCY_DEFAULT)), taskStallEndMs: Math.max(TASK_STALL_END_MIN, Math.min(TASK_STALL_END_MAX, Number(draft.canvas.taskStallEndMs) || 300000)), autoSaveImages: draft.canvas.autoSaveImages !== false, backupOriginals: draft.canvas.backupOriginals !== false },
|
||||
webhook: { enabled: !!draft.webhook.enabled, url: (draft.webhook.url || '').trim() },
|
||||
})
|
||||
setSaving(false)
|
||||
|
||||
@@ -21,6 +21,18 @@
|
||||
--iwb-border: #d5d9e0;
|
||||
--iwb-border2: #b9bfca;
|
||||
--iwb-brand: #6b7280; /* v3.1.0 全灰阶:原品牌蓝 → 同亮度中性灰(白字对比仍 ≥4.5:1) */
|
||||
/* 连线默认色:跟随边框灰(亮/暗自适应)。主题色只用于选中/悬停/上下游高亮(v3.25.18 用户裁定) */
|
||||
--iwb-edge: var(--iwb-border2);
|
||||
/* 外观自定义(v3.25.22):以下变量都由 src/ui-appearance.js 按配置写入,这里只给兜底默认值 */
|
||||
--iwb-edge-w: 1.8px;
|
||||
--iwb-edge-dash: 4 3;
|
||||
--iwb-edge-hot: var(--iwb-brand);
|
||||
--iwb-node-radius: 14px;
|
||||
--iwb-node-sel-w: 1px;
|
||||
--iwb-grid-dot: #c9ccd6;
|
||||
--iwb-grid-size: 1.4px;
|
||||
--iwb-grid-gap: 22px;
|
||||
--iwb-grid-on: 1;
|
||||
--iwb-text: #1c2333;
|
||||
--iwb-text2: #4d5668;
|
||||
--iwb-err: #e5484d;
|
||||
@@ -82,7 +94,7 @@ button { font-family: inherit; }
|
||||
/* 抓手工具(H):整块画布给「可抓」光标,按下拖动时变抓紧 */
|
||||
.iwb-canvas.iwb-tool-pan { cursor: grab; }
|
||||
.iwb-canvas.iwb-tool-pan:active { cursor: grabbing; }
|
||||
.iwb-grid { position: absolute; inset: 0; pointer-events: none; background-image: radial-gradient(circle, color-mix(in srgb, var(--iwb-text2) 24%, transparent) 1.4px, transparent 1.8px); background-size: 22px 22px; background-repeat: repeat; opacity: 0.85; }
|
||||
.iwb-grid { position: absolute; inset: 0; pointer-events: none; background-image: radial-gradient(circle, var(--iwb-grid-dot) var(--iwb-grid-size), transparent calc(var(--iwb-grid-size) + 0.4px)); background-size: var(--iwb-grid-gap) var(--iwb-grid-gap); background-repeat: repeat; opacity: calc(0.85 * var(--iwb-grid-on)); }
|
||||
/* 亮色主题:网格点更浅,降低与背景对比度(暗色主题不受影响) */
|
||||
/* 亮色主题的生图动效 token:与改动前逐值一致,保证亮色观感零变化 */
|
||||
:root:not(.theme-dark) {
|
||||
@@ -93,22 +105,21 @@ button { font-family: inherit; }
|
||||
--iwb-anim-flow-a: color-mix(in srgb, var(--iwb-brand) 16%, var(--iwb-layer));
|
||||
--iwb-anim-flow-b: color-mix(in srgb, var(--iwb-brand) 46%, var(--iwb-layer));
|
||||
}
|
||||
:root:not(.theme-dark) .iwb-grid { background-image: radial-gradient(circle, color-mix(in srgb, var(--iwb-text2) 16%, transparent) 1.4px, transparent 1.8px); }
|
||||
.iwb-world { position: absolute; left: 0; top: 0; transform-origin: 0 0; will-change: transform; }
|
||||
.iwb-edges { position: absolute; left: 0; top: 0; pointer-events: none; }
|
||||
.iwb-edge-hit { fill: none; stroke: transparent; stroke-width: 14; pointer-events: stroke; cursor: pointer; }
|
||||
.iwb-edge-hit:hover { stroke: color-mix(in srgb, var(--iwb-brand) 16%, transparent); }
|
||||
.iwb-edge-hit:hover + .iwb-edge { stroke-width: 2.4; stroke: var(--iwb-brand); }
|
||||
.iwb-edge { fill: none; stroke: color-mix(in srgb, var(--iwb-text2) 42%, transparent); stroke-width: 1.8; stroke-dasharray: 4 3; pointer-events: stroke; cursor: pointer; }
|
||||
.iwb-edge:hover { stroke: var(--iwb-brand); stroke-dasharray: none; }
|
||||
.iwb-edge-hit:hover + .iwb-edge { stroke-width: calc(var(--iwb-edge-w) + 0.6px); stroke: var(--iwb-edge-hot); }
|
||||
.iwb-edge { fill: none; stroke: var(--iwb-edge); stroke-width: var(--iwb-edge-w); stroke-dasharray: var(--iwb-edge-dash); pointer-events: stroke; cursor: pointer; }
|
||||
.iwb-edge:hover { stroke: var(--iwb-edge-hot); stroke-dasharray: none; }
|
||||
.iwb-edge-sel { stroke: var(--iwb-warn); stroke-width: 2.4; stroke-dasharray: none; }
|
||||
.iwb-edge-hot { stroke: var(--iwb-brand); stroke-width: 2.4; stroke-dasharray: none; }
|
||||
.iwb-edge-upstream { stroke: var(--iwb-brand); stroke-width: 1.2; opacity: 1; stroke-dasharray: none; }
|
||||
.iwb-edge-downstream { stroke: var(--iwb-brand); stroke-width: 1.2; opacity: 1; stroke-dasharray: none; }
|
||||
.iwb-edge-hot { stroke: var(--iwb-edge-hot); stroke-width: 2.4; stroke-dasharray: none; }
|
||||
.iwb-edge-upstream { stroke: var(--iwb-edge-hot); stroke-width: 1.2; opacity: 1; stroke-dasharray: none; }
|
||||
.iwb-edge-downstream { stroke: var(--iwb-edge-hot); stroke-width: 1.2; opacity: 1; stroke-dasharray: none; }
|
||||
.iwb-edge-detach { stroke: var(--iwb-err); stroke-width: 2.4; stroke-dasharray: 6 4; }
|
||||
.iwb-edge-temp { stroke: var(--iwb-brand); stroke-dasharray: 6 4; pointer-events: none; }
|
||||
.iwb-node { position: absolute; background: var(--iwb-node-bg); border: 1px solid var(--iwb-border); border-top: 1px solid var(--iwb-border); border-radius: 14px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); font-size: 12px; color: var(--iwb-text); display: flex; flex-direction: column; cursor: move; contain: layout style; }
|
||||
.iwb-node-selected { border-color: var(--iwb-brand); box-shadow: 0 0 0 1px var(--iwb-brand), 0 6px 20px rgba(0,0,0,0.25); }
|
||||
.iwb-edge-temp { stroke: var(--iwb-edge-hot); stroke-dasharray: 6 4; pointer-events: none; }
|
||||
.iwb-node { position: absolute; background: var(--iwb-node-bg); border: 1px solid var(--iwb-border); border-top: 1px solid var(--iwb-border); border-radius: var(--iwb-node-radius); box-shadow: 0 2px 12px rgba(0,0,0,0.08); font-size: 12px; color: var(--iwb-text); display: flex; flex-direction: column; cursor: move; contain: layout style; }
|
||||
.iwb-node-selected { border-color: var(--iwb-brand); box-shadow: 0 0 0 var(--iwb-node-sel-w) var(--iwb-brand), 0 6px 20px rgba(0,0,0,0.25); }
|
||||
.iwb-node:hover { z-index: 4; }
|
||||
.iwb-node input, .iwb-node select, .iwb-node button { cursor: auto; }
|
||||
.iwb-node .iwb-textarea:read-only { cursor: move; }
|
||||
@@ -846,6 +857,22 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
|
||||
.iwb-ctx-item.iwb-ctx-danger .iwb-ic { color: #ef4444; }
|
||||
.iwb-ctx-item.iwb-ctx-danger:hover:not(:disabled) { background: color-mix(in srgb, #ef4444 10%, transparent); color: #ef4444; }
|
||||
.iwb-ctx-sep { height: 1px; margin: 4px 6px; background: var(--iwb-border); flex: 0 0 auto; }
|
||||
/* ---- 二级菜单(2026-11-19 用户要求:一级太长了)----
|
||||
* 「选中操作」「该节点」两组收进子菜单,一级只留入口。纯 CSS 展开(:hover + :focus-within),
|
||||
* 不占 React 状态:鼠标悬停或键盘 Tab 到入口都会展开,点击入口也会(button 获得焦点)。
|
||||
* 定位:默认贴父项右侧(一级菜单永远离视口右边 ≥210px,见 app.js 的 left 夹取,放得下 200px 子菜单);
|
||||
* 最后一项「该节点」用 .iwb-ctx-sub-up 改为底对齐,避免向下溢出视口。 */
|
||||
.iwb-ctx-subwrap { position: relative; display: flex; flex-direction: column; }
|
||||
.iwb-ctx-arrow { margin-left: auto; padding-left: 10px; font-style: normal; font-size: 10px; line-height: 1; color: var(--iwb-text2); opacity: 0.7; }
|
||||
.iwb-ctx-sub { position: absolute; left: calc(100% + 6px); bottom: -6px; display: none; min-width: 200px; overflow: visible; max-height: none; }
|
||||
/* 6px 缝隙也要能滑过去,否则鼠标一移就收起来了。注意子菜单必须 overflow:visible,
|
||||
* 否则这条桥接用的伪元素会被 .iwb-ctxmenu 继承来的 overflow-y:auto 裁掉,等于没加。 */
|
||||
.iwb-ctx-sub::before { content: ''; position: absolute; left: -8px; top: 0; width: 8px; height: 100%; }
|
||||
/* 兜底:入口本身就在菜单最顶上时改用向下展开 */
|
||||
.iwb-ctx-sub-down { top: -6px; bottom: auto; }
|
||||
.iwb-ctx-subwrap:hover > .iwb-ctx-sub, .iwb-ctx-subwrap:focus-within > .iwb-ctx-sub { display: flex; }
|
||||
/* 一级菜单开了这个类就不再裁剪:overflow-y:auto 的祖先会把绝对定位的子菜单切掉 */
|
||||
.iwb-ctxmenu.iwb-ctx-noclip { overflow: visible; max-height: none; }
|
||||
|
||||
/* ---- 历史图片:常量可选(单击选择 / 双击放大)+ 单图操作 ---- */
|
||||
/* 选中有值(iwb-history-managed)时未选图片微暗,突出已选;基础 cursor 已统一为 pointer */
|
||||
@@ -1965,4 +1992,129 @@ html { scrollbar-width: thin; scrollbar-color: var(--iwb-border2) color-mix(in s
|
||||
.iwb-confirm-box { width: min(460px, calc(100vw - 48px)); background: var(--iwb-layer); color: var(--iwb-text); border-radius: 12px; padding: 18px 20px 14px; box-shadow: 0 12px 40px rgba(0,0,0,.28); }
|
||||
.iwb-confirm-title { font-weight: 650; font-size: 15px; margin-bottom: 8px; }
|
||||
.iwb-confirm-text { font-size: 13.5px; line-height: 1.65; color: var(--iwb-text2); white-space: pre-wrap; word-break: break-word; }
|
||||
.iwb-confirm-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
|
||||
.iwb-confirm-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
|
||||
/* 插件市场卡片(设置 → 插件 / 与 market.maqiart.eu.org 同一套视觉) */
|
||||
.iwb-mk-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; margin: 4px 0 6px; }
|
||||
.iwb-mk-card { border: 1px solid var(--iwb-border); border-radius: 12px; padding: 12px; display: flex; flex-direction: column; gap: 8px; min-height: 132px; }
|
||||
.iwb-mk-head { display: flex; gap: 10px; align-items: center; }
|
||||
.iwb-mk-avatar { width: 36px; height: 36px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 18px; flex: 0 0 36px; }
|
||||
.iwb-mk-titles { min-width: 0; }
|
||||
.iwb-mk-name { font-weight: 600; font-size: 14px; display: flex; align-items: center; flex-wrap: wrap; }
|
||||
.iwb-mk-sub { color: var(--iwb-text2); font-size: 12px; margin-top: 2px; }
|
||||
.iwb-mk-desc { color: var(--iwb-text2); font-size: 12.5px; line-height: 1.5; flex: 1 1 auto; }
|
||||
.iwb-mk-tags { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
.iwb-mk-tag { padding: 1px 8px; border-radius: 999px; background: var(--iwb-layer2); color: var(--iwb-text2); font-size: 11px; }
|
||||
.iwb-mk-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 2px; }
|
||||
/* 设置行(Obsidian 风格:标题 + 说明 + 右侧控件) */
|
||||
.iwb-set-row { display: flex; align-items: center; gap: 16px; padding: 12px 0; border-bottom: 1px solid var(--iwb-border); }
|
||||
.iwb-set-row-main { flex: 1 1 auto; min-width: 0; }
|
||||
.iwb-set-row-title { font-weight: 600; font-size: 14px; }
|
||||
|
||||
/* 开关 */
|
||||
.iwb-switch { display: inline-flex; align-items: center; cursor: pointer; flex: 0 0 auto; }
|
||||
.iwb-switch input { position: absolute; opacity: 0; width: 0; height: 0; }
|
||||
.iwb-switch-track { width: 38px; height: 22px; border-radius: 999px; background: var(--iwb-border); position: relative; transition: background .15s; }
|
||||
.iwb-switch-dot { position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #fff; transition: transform .15s; box-shadow: 0 1px 2px rgba(0,0,0,.2); }
|
||||
.iwb-switch input:checked + .iwb-switch-track { background: #6b5ce7; }
|
||||
.iwb-switch input:checked + .iwb-switch-track .iwb-switch-dot { transform: translateX(16px); }
|
||||
.iwb-switch input:disabled + .iwb-switch-track { opacity: .45; }
|
||||
|
||||
/* 已安装插件:横向列表 */
|
||||
.iwb-mk-list { display: flex; flex-direction: column; }
|
||||
.iwb-mk-row { display: flex; align-items: center; gap: 12px; padding: 10px 2px; border-bottom: 1px solid var(--iwb-border); }
|
||||
.iwb-mk-row-main { flex: 1 1 auto; min-width: 0; }
|
||||
.iwb-mk-row-title { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.iwb-mk-row-name { font-weight: 600; font-size: 14px; }
|
||||
.iwb-mk-row-ver { color: var(--iwb-text2); font-size: 12px; }
|
||||
.iwb-mk-row-author { color: var(--iwb-text2); font-size: 12px; }
|
||||
.iwb-mk-row-desc { color: var(--iwb-text2); font-size: 12.5px; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.iwb-mk-row-actions { display: flex; align-items: center; gap: 8px; flex: 0 0 auto; }
|
||||
.iwb-mk-chips { display: flex; gap: 6px; flex-wrap: wrap; margin: 4px 0 10px; }
|
||||
.iwb-mk-chip { padding: 3px 10px; border-radius: 999px; border: 1px solid var(--iwb-border); background: transparent; color: var(--iwb-text2); font-size: 12px; cursor: pointer; }
|
||||
.iwb-mk-chip.on { background: var(--iwb-text); color: var(--iwb-layer); border-color: var(--iwb-text); }
|
||||
/* 插件设置:行(无边框盒子,只有细分隔线) */
|
||||
.iwb-mk-setrow { display: flex; align-items: center; gap: 16px; padding: 14px 2px; border: 0; border-bottom: 1px solid var(--iwb-border); background: transparent; border-radius: 0; margin: 0; }
|
||||
.iwb-mk-setrow:last-of-type { border-bottom: 0; }
|
||||
.iwb-mk-setrow-main { flex: 1 1 auto; min-width: 0; }
|
||||
.iwb-mk-setrow-title { font-weight: 600; font-size: 14px; line-height: 1.4; }
|
||||
.iwb-mk-setrow .iwb-hint { margin-top: 3px; line-height: 1.55; }
|
||||
/* 插件设置项:说明在上、控件在下(左对齐,2026-11-19)。
|
||||
* 原来 label 在左、输入框挤在右边 260px,地址/书签这类内容既看不全也改不动;
|
||||
* 布尔开关仍留在行末 —— 那是「开/关」,不是要填写的内容。 */
|
||||
.iwb-mk-setrow-col { display: block; }
|
||||
.iwb-mk-setrow-col > .iwb-mk-setrow-main { width: 100%; }
|
||||
.iwb-mk-setrow-col > .iwb-input, .iwb-mk-setrow-col > .iwb-plugin-setting-custom { margin-top: 10px; }
|
||||
.iwb-plugin-setting-custom { display: block; min-width: 0; max-width: 100%; }
|
||||
|
||||
/* 市场页筛选条 */
|
||||
.iwb-mk-filters { display: flex; gap: 6px; flex-wrap: wrap; margin: 2px 0 12px; align-items: center; }
|
||||
.iwb-mk-filters .iwb-mk-sep { width: 1px; height: 16px; background: var(--iwb-border); margin: 0 4px; }
|
||||
/* 市场卡片:等高、底部按钮对齐 */
|
||||
.iwb-mk-grid { align-items: stretch; }
|
||||
.iwb-mk-card { min-height: 178px; display: flex; flex-direction: column; gap: 8px; }
|
||||
.iwb-mk-card .iwb-mk-desc { flex: 1 1 auto; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; min-height: 38px; }
|
||||
.iwb-mk-card .iwb-mk-tags { min-height: 20px; align-items: center; }
|
||||
.iwb-mk-card .iwb-mk-actions { margin-top: auto; display: flex; align-items: center; justify-content: flex-end; min-height: 30px; }
|
||||
.iwb-mk-card .iwb-mk-name { line-height: 1.35; }
|
||||
.iwb-mk-card .iwb-plugin-tag { font-size: 11px; padding: 0 6px; line-height: 16px; }
|
||||
/* 市场卡片:紧凑版(按钮在右上角,去掉底部空档) */
|
||||
.iwb-mk-card { min-height: 0; padding: 10px 12px; gap: 6px; border-radius: 10px; }
|
||||
.iwb-mk-head { align-items: flex-start; gap: 8px; }
|
||||
.iwb-mk-titles { flex: 1 1 auto; min-width: 0; }
|
||||
.iwb-mk-head .iwb-mk-actions { flex: 0 0 auto; margin: 0; padding: 0; min-height: 0; }
|
||||
.iwb-mk-card .iwb-mk-avatar { width: 32px; height: 32px; flex: 0 0 32px; font-size: 17px; border-radius: 9px; }
|
||||
.iwb-mk-card .iwb-mk-name { font-size: 13.5px; }
|
||||
.iwb-mk-card .iwb-mk-sub { font-size: 11.5px; margin-top: 1px; }
|
||||
.iwb-mk-card .iwb-mk-desc { font-size: 12px; line-height: 1.45; min-height: 0; margin-top: 2px; }
|
||||
.iwb-mk-card .iwb-mk-tags { min-height: 0; margin-top: 2px; gap: 5px; }
|
||||
.iwb-mk-card .iwb-mk-tag { font-size: 10.5px; padding: 0 7px; line-height: 16px; }
|
||||
.iwb-mk-grid { gap: 10px; }
|
||||
.iwb-mk-card .iwb-btn-sm { padding: 3px 10px; font-size: 12px; }
|
||||
/* LLM 渠道:去掉外框,改成分区 + 细分隔线;默认渠道用左侧色条标记 */
|
||||
.iwb-settings-modal .iwb-llm-card { border: 0; border-top: 1px solid var(--iwb-border); border-radius: 0; background: transparent; padding: 12px 0 8px; margin: 0; }
|
||||
.iwb-settings-modal .iwb-llm-card:first-of-type { border-top: 0; }
|
||||
.iwb-settings-modal .iwb-llm-card-def { border-left: 2px solid #6b5ce7; padding-left: 12px; }
|
||||
.iwb-settings-modal .iwb-llm-card .iwb-label { font-size: 12px; color: var(--iwb-text2); font-weight: 600; margin: 10px 0 4px; }
|
||||
.iwb-settings-modal .iwb-llm-card .iwb-row { margin: 4px 0; gap: 8px; }
|
||||
.iwb-settings-modal .iwb-llm-card .iwb-input { padding: 6px 10px; font-size: 13px; }
|
||||
.iwb-settings-modal .iwb-modellist { display: flex; flex-wrap: wrap; gap: 6px; margin: 2px 0 4px; }
|
||||
.iwb-settings-modal .iwb-modelrow { padding: 2px 8px; border-radius: 999px; background: var(--iwb-layer2); border: 1px solid transparent; margin: 0; font-size: 12.5px; }
|
||||
.iwb-settings-modal .iwb-modelrow-active { border-color: #6b5ce7; background: rgba(107,92,231,.08); }
|
||||
.iwb-settings-modal .iwb-llm-card .iwb-btn-xs { opacity: .5; }
|
||||
.iwb-settings-modal .iwb-llm-card .iwb-btn-xs:hover { opacity: 1; }
|
||||
/* ── 外观:取色器(v3.25.14,仿 Obsidian 的取色面板) ───────────────── */
|
||||
.iwb-cpick { position: relative; display: inline-flex; align-items: center; gap: 8px; }
|
||||
.iwb-cpick-swatch { display: inline-flex; align-items: center; justify-content: center; min-width: 92px; height: 28px; padding: 0 10px; border-radius: 6px; border: 1px solid var(--iwb-border); cursor: pointer; font-size: 11px; letter-spacing: .04em; }
|
||||
.iwb-cpick-swatch:hover { border-color: var(--iwb-border2); }
|
||||
.iwb-cpick-hex { mix-blend-mode: difference; }
|
||||
.iwb-cpick-pop { position: absolute; z-index: 80; top: calc(100% + 8px); left: 0; width: 236px; padding: 10px; border-radius: 10px; background: var(--iwb-panel); border: 1px solid var(--iwb-border); box-shadow: var(--sh-md); }
|
||||
.iwb-cpick-box { position: relative; height: 132px; border-radius: 6px; cursor: crosshair; }
|
||||
.iwb-cpick-dot { position: absolute; width: 12px; height: 12px; margin: -6px 0 0 -6px; border-radius: 50%; border: 2px solid #fff; box-shadow: 0 0 0 1px rgba(0,0,0,.4); pointer-events: none; }
|
||||
.iwb-cpick-hue { width: 100%; height: 12px; margin: 10px 0 8px; border-radius: 6px; -webkit-appearance: none; appearance: none; }
|
||||
.iwb-cpick-hue::-webkit-slider-thumb { -webkit-appearance: none; width: 14px; height: 14px; border-radius: 50%; background: #fff; border: 2px solid rgba(0,0,0,.45); cursor: pointer; }
|
||||
.iwb-cpick-rgb { display: flex; gap: 6px; }
|
||||
.iwb-cpick-chan { flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 2px; font-size: 10px; color: var(--iwb-text2); }
|
||||
.iwb-cpick-chan input { width: 100%; height: 26px; padding: 0 4px; text-align: center; border-radius: 5px; border: 1px solid var(--iwb-border); background: var(--iwb-layer2); color: var(--iwb-text); font-size: 11px; }
|
||||
.iwb-cpick-foot { display: flex; gap: 6px; align-items: center; margin-top: 8px; }
|
||||
/* 十六进制输入框可缩到 0(min-width:0 才能被 flex 压窄),「完成」按钮固定不换行 */
|
||||
.iwb-cpick-input { flex: 1 1 0; min-width: 0; width: auto; height: 26px; font-size: 11px; }
|
||||
.iwb-cpick-foot .iwb-btn { flex: 0 0 auto; white-space: nowrap; padding: 0 10px; }
|
||||
.iwb-hint-warn { color: var(--iwb-warn); }
|
||||
|
||||
/* 紧凑下拉(v3.25.19):图库顶部的时间/插入尺寸选择器,省横向空间 */
|
||||
.iwb-select-compact {
|
||||
width: auto;
|
||||
min-width: 62px;
|
||||
max-width: 84px;
|
||||
padding-left: 6px;
|
||||
padding-right: 4px;
|
||||
font-size: var(--fs-sm);
|
||||
background-position: right 2px center;
|
||||
}
|
||||
.iwb-history-head { flex-wrap: nowrap; gap: 6px; }
|
||||
.iwb-history-head .iwb-btn-sm { padding-left: 6px; padding-right: 6px; }
|
||||
|
||||
/* 外观自定义(v3.25.22):数值滑杆与预设按钮 */
|
||||
.iwb-appear-range { flex: 1 1 0; min-width: 90px; max-width: 220px; }
|
||||
.iwb-appear-val { min-width: 52px; text-align: right; font-size: var(--fs-sm); color: var(--iwb-text2); }
|
||||
.iwb-appear-presets { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; }
|
||||
@@ -213,7 +213,8 @@ test('插件节点:启用后可从右键菜单创建、渲染、运行;停
|
||||
await page.evaluate(() => window.IWBPluginHost.setEnabled('node-demo', true))
|
||||
|
||||
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
|
||||
const entry = page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '插件:打招呼节点' })
|
||||
// 2026-11-19:插件节点改成独立分组(分隔线 + 「插件节点」标题),条目文本不再带「插件:」前缀
|
||||
const entry = page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '打招呼节点' })
|
||||
await expect(entry).toBeVisible()
|
||||
await entry.click()
|
||||
|
||||
@@ -227,7 +228,7 @@ test('插件节点:启用后可从右键菜单创建、渲染、运行;停
|
||||
await page.evaluate(() => window.IWBPluginHost.setEnabled('node-demo', false))
|
||||
await expect(page.locator('.iwb-node')).toHaveCount(1, { timeout: 3000 })
|
||||
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
|
||||
await expect(page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '插件:打招呼节点' })).toHaveCount(0)
|
||||
await expect(page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '打招呼节点' })).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('插件面板:启用后出现在资源中心 tab 并可挂载;停用后 tab 消失', async ({ page }) => {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const code = fs.readFileSync(path.join(__dirname, '../src/clipboard-graph.js'), 'utf8')
|
||||
|
||||
function makeGlobal (withClipboard) {
|
||||
const calls = []
|
||||
const g = {
|
||||
TextEncoder,
|
||||
TextDecoder,
|
||||
btoa: (s) => Buffer.from(s, 'binary').toString('base64'),
|
||||
atob: (s) => Buffer.from(s, 'base64').toString('binary'),
|
||||
navigator: {},
|
||||
__TAURI__: { core: { invoke: (cmd, args) => { calls.push({ cmd, args }); return Promise.resolve(true) } } },
|
||||
console,
|
||||
}
|
||||
if (withClipboard) {
|
||||
g.ClipboardItem = function (items) { this.items = items }
|
||||
g.Blob = function (parts, opts) { this.parts = parts; this.type = (opts || {}).type }
|
||||
g.navigator.clipboard = { write: () => Promise.reject(new Error('not allowed')) }
|
||||
}
|
||||
return { g, calls }
|
||||
}
|
||||
|
||||
function run (withClipboard) {
|
||||
const { g, calls } = makeGlobal(withClipboard)
|
||||
const fn = new Function('window', 'globalThis', code + '\nreturn window.IWBClipboardGraph')
|
||||
const G = fn(g, g)
|
||||
const clip = { nodes: [{ id: 'n1', type: 'prompt', text: '两只猫在窗台' }], edges: [] }
|
||||
return G.write(clip).then((ok) => {
|
||||
const matched = G.matchPlain(G.plainFor(clip))
|
||||
return { ok, calls, plain: G.plainFor(clip), matched: !!matched, id: matched && matched.nodes[0].id }
|
||||
})
|
||||
}
|
||||
|
||||
run(false).then((r) => {
|
||||
console.log('无 clipboard.write(WKWebView 场景):', JSON.stringify({ ok: r.ok, native: r.calls.map(c => c.cmd), matched: r.matched, id: r.id }))
|
||||
if (!(r.ok && r.calls.some(c => c.cmd === 'clipboard_write_text') && r.matched)) process.exit(1)
|
||||
return run(true)
|
||||
}).then((r) => {
|
||||
console.log('有 clipboard.write 且被拒绝:', JSON.stringify({ ok: r.ok, native: r.calls.map(c => c.cmd), matched: r.matched }))
|
||||
if (!(r.ok && r.matched)) process.exit(1)
|
||||
console.log('PASS 图剪贴板兜底(原生写文本 + 摘要匹配)')
|
||||
}).catch((e) => { console.error('FAIL', e); process.exit(1) })
|
||||
@@ -210,8 +210,10 @@ function makeCtx(over) {
|
||||
eq('设置面板打开 → 不落节点', ctx.log.filter((x) => x.startsWith('commit')).length, 0)
|
||||
}
|
||||
{
|
||||
// v3.25.6(用户裁定):库面板打开时照常粘贴,并且**不关闭**面板。
|
||||
const ctx = makeCtx({ ui: { drawerOpen: true } })
|
||||
eq('图库抽屉打开 → 不接管', P.handle(pasteEv({ text: 'x' }), ctx), false)
|
||||
eq('图库抽屉打开 → 仍然接管粘贴', P.handle(pasteEv({ text: 'x' }), ctx), true)
|
||||
eq('图库抽屉打开 → 不关闭面板', ctx.ui.drawerOpen, true)
|
||||
}
|
||||
{
|
||||
const ctx = makeCtx({ ui: { helpOpen: true } })
|
||||
@@ -348,10 +350,9 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
eq('首次导入 → 落成 1 个参考图节点', ctx.log.filter((x) => x.startsWith('commit')).length, 1)
|
||||
ctx.log.length = 0
|
||||
pasted(u1)
|
||||
eq('同一张图再粘 → 不建节点', ctx.log.filter((x) => x.startsWith('commit')).length, 0)
|
||||
eq('同一张图再粘 → 选中已有节点(否则用户看不出东西在哪)', ctx.log.filter((x) => x === 'sel:1').length, 1)
|
||||
ok('同一张图再粘 → 提示"已经在画布上"', ctx.log.some((x) => x.indexOf('notice:ok') === 0 && x.indexOf('已经在画布上') > 0))
|
||||
ok('同一张图再粘 → 绝不静默(一定有提示)', ctx.log.some((x) => x.indexOf('notice:') === 0))
|
||||
// v3.25.6(用户裁定):同一张图允许重复粘贴(粘贴是显式动作,去重挡掉像按键没反应)
|
||||
eq('同一张图再粘 → 再建一个节点', ctx.log.filter((x) => x.startsWith('commit')).length, 1)
|
||||
ok('同一张图再粘 → 有成功提示', ctx.log.some((x) => x.indexOf('notice:') === 0))
|
||||
ctx.log.length = 0
|
||||
pasted(u2)
|
||||
eq('换一张不同的图 → 照常落地(不是"一律不粘")', ctx.log.filter((x) => x.startsWith('commit')).length, 1)
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/* desktop-csp-loopback-test.js —— 桌面客户端 CSP 必须放行本地服务插件(v3.25.14)
|
||||
*
|
||||
* 背景:v3.25.11 的「CSP 清理」把 30092 当成遗留端口删掉了,但它其实是
|
||||
* 2026-10-17 有意为「本地服务插件」放宽的安全边界。删掉后桌面版鲜艺抠图插件报
|
||||
* 「Failed to fetch」。
|
||||
*
|
||||
* ⚠️ 这个项目现在是**桌面客户端**:CSP 的唯一真相是 src-tauri/tauri.conf.json。
|
||||
* 不参照任何网页部署配置 —— 那是别的产品,耦合只会制造假失败。
|
||||
*
|
||||
* ⚠️ 写法约束(tests/source-text-ratchet-test.js 的零余量棘轮):
|
||||
* 不要读文件原文再 .includes/.indexOf(变量名命中 source|src|app53… 会被计数)。
|
||||
* 这里只做**解析后运行时值**的断言。
|
||||
*/
|
||||
'use strict'
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const assert = require('node:assert')
|
||||
|
||||
const conf = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'src-tauri', 'tauri.conf.json'), 'utf8'))
|
||||
const policy = String((conf.app && conf.app.security && conf.app.security.csp) || '')
|
||||
|
||||
assert.ok(policy.length > 0, '桌面版必须显式声明 CSP(不允许留空回落默认)')
|
||||
|
||||
const directives = Object.fromEntries(policy.split(';').map((part) => {
|
||||
const bits = part.trim().split(/\s+/).filter(Boolean)
|
||||
return bits.length ? [bits[0], bits.slice(1)] : ['', []]
|
||||
}))
|
||||
|
||||
const connect = directives['connect-src'] || []
|
||||
assert.ok(connect.length > 0, 'connect-src 不能为空')
|
||||
|
||||
// 30092 = 本地鲜艺抠图服务(XianyiAiRmbg)。两个 loopback 写法都要在:
|
||||
// 插件默认 http://localhost:30092,用户改成 127.0.0.1 也必须能用。
|
||||
for (const origin of ['http://127.0.0.1:30092', 'http://localhost:30092']) {
|
||||
assert.ok(connect.includes(origin), '桌面 CSP 的 connect-src 必须放行 ' + origin + '(本地抠图插件依赖)')
|
||||
}
|
||||
|
||||
// 守卫的守卫:确认没有顺手把整个 http: 放开
|
||||
assert.ok(!connect.includes('http:'), 'connect-src 不得放开整个 http: 协议(只放行具体 loopback 源)')
|
||||
|
||||
// 只允许 loopback 例外:桌面 CSP 里出现非 loopback 的 http 源视为放宽过度
|
||||
// http://ipc.localhost 是 Tauri 自己的 IPC 通道,属于必需项;其余 http 源只允许 loopback
|
||||
const ALLOWED_HTTP = new Set(['http://ipc.localhost'])
|
||||
const plainHttp = connect.filter((v) => /^http:\/\//.test(v) && !ALLOWED_HTTP.has(v) && !/^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(v))
|
||||
assert.deepStrictEqual(plainHttp, [], '除 loopback 外不得出现其它 http 源:' + plainHttp.join(', '))
|
||||
|
||||
console.log('desktop-csp-loopback: 5 通过 / 0 失败')
|
||||
@@ -20,6 +20,7 @@
|
||||
"IWBImageCompress",
|
||||
"IWBImagePreviewDerive",
|
||||
"IWBMetricsSwallow",
|
||||
"IWBNativeClipboard",
|
||||
"IWBNodeBodies",
|
||||
"IWBPluginHost",
|
||||
"IWBProviderPing",
|
||||
@@ -35,6 +36,8 @@
|
||||
"IWBRuntimeLifecycle",
|
||||
"IWBRuntimeLifecycleFactory",
|
||||
"IWBRuntimeMetrics",
|
||||
"IWBRuntimePluginLoader",
|
||||
"IWBRuntimePluginMarket",
|
||||
"IWBRuntimeRecord",
|
||||
"IWBRuntimeRecovery",
|
||||
"IWBRuntimeRunContext",
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
"clipboard-paste.js",
|
||||
"clipboard-copy.js",
|
||||
"clipboard-paste-once.js",
|
||||
"clipboard-native.js",
|
||||
"generation-size-policy.js",
|
||||
"generation-request-shape.js",
|
||||
"image-preview-derive.js",
|
||||
@@ -60,6 +61,9 @@
|
||||
"generation-results-store.js",
|
||||
"ui-groups-sidebar.js",
|
||||
"ui-lib-sidebar.js",
|
||||
"ui-desktop-shell.js",
|
||||
"ui-appearance.js",
|
||||
"runtime-download-auto.js",
|
||||
"ui-workspace-tabs.js",
|
||||
"ui-app-chrome.js",
|
||||
"ui-workbench-hooks.js",
|
||||
@@ -69,6 +73,9 @@
|
||||
"workspace-list.js",
|
||||
"workspace-purge.js",
|
||||
"generation-provider-ping.js",
|
||||
"runtime-plugin-loader.js",
|
||||
"runtime-plugin-market.js",
|
||||
"runtime-plugin-backup.js",
|
||||
"ui-canvas-view.js",
|
||||
"ui-confirm.js",
|
||||
"ui-settings-sections.js",
|
||||
@@ -79,5 +86,6 @@
|
||||
"runtime-workbench-logic.js",
|
||||
"ui-backup-modal.js",
|
||||
"ui-connect-menu.js",
|
||||
"ui-gen-config-panel.js"
|
||||
"ui-gen-config-panel.js",
|
||||
"canvas-webview.js"
|
||||
]
|
||||
@@ -1,154 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
// functions/api/*.js 的行为测试(此前这两个 Pages 函数无任何自动化测试)。
|
||||
// 用 Node 全局 Request/Response 调用 onRequest,并 mock 全局 fetch。
|
||||
|
||||
const assert = require('assert')
|
||||
const path = require('path')
|
||||
|
||||
const calls = []
|
||||
function setFetch(handler) {
|
||||
globalThis.fetch = async (url, init) => {
|
||||
const u = String(url)
|
||||
calls.push({ url: u, init: init || {} })
|
||||
return handler(u, init || {})
|
||||
}
|
||||
}
|
||||
const req = (method, url, headers, body) => new Request(url, { method, headers: headers || {}, body })
|
||||
const jsonReq = (url, payload, headers) => req('POST', url, Object.assign({ 'Content-Type': 'application/json' }, headers || {}), JSON.stringify(payload))
|
||||
const noAcao = (res) => assert.strictEqual(res.headers.get('access-control-allow-origin'), null, '不应再有 CORS *')
|
||||
|
||||
;(async () => {
|
||||
const img = await import(path.join(__dirname, '..', 'functions', 'api', 'img.js'))
|
||||
|
||||
// ---------- img.js ----------
|
||||
const IMG = 'https://d1.cloudfront.net/a.png'
|
||||
const okImg = () => new Response('PNGDATA', { status: 200, headers: { 'Content-Type': 'image/png' } })
|
||||
const imgUrl = (host, p) => 'https://site.example/api/img?url=' + encodeURIComponent('https://' + host + (p || '/a.png'))
|
||||
|
||||
// 1) 非 https 400
|
||||
setFetch(okImg)
|
||||
let r = await img.onRequest({ request: req('GET', 'https://site.example/api/img?url=' + encodeURIComponent('http://d1.cloudfront.net/a.png')) })
|
||||
assert.strictEqual(r.status, 400, 'img: http 应 400')
|
||||
|
||||
// 2) 非白名单 host 403
|
||||
setFetch(okImg)
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('evil.example')) })
|
||||
assert.strictEqual(r.status, 403, 'img: 非白名单 host 应 403')
|
||||
|
||||
// 3) 跨域 Origin 403
|
||||
setFetch(okImg)
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net'), { Origin: 'https://evil.example' }) })
|
||||
assert.strictEqual(r.status, 403, 'img: 跨域 Origin 应 403')
|
||||
|
||||
// 4) 直连白名单 host 放行,无 CORS *,透传 image/*
|
||||
setFetch(okImg)
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||||
assert.strictEqual(r.status, 200, 'img: 白名单 host 应 200')
|
||||
assert.strictEqual(r.headers.get('content-type'), 'image/png', 'img: 应透传 image/png')
|
||||
noAcao(r)
|
||||
|
||||
// 5) 重定向到非白名单 host 403(手动跟随并复检)
|
||||
calls.length = 0
|
||||
setFetch((u) => u.indexOf('d1.cloudfront.net') >= 0
|
||||
? new Response(null, { status: 302, headers: { Location: 'https://evil.example/x.png' } })
|
||||
: okImg())
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||||
assert.strictEqual(r.status, 403, 'img: 重定向到非白名单应 403')
|
||||
|
||||
// 6) 重定向到白名单 host 应跟随成功
|
||||
calls.length = 0
|
||||
setFetch((u) => u.indexOf('d1.cloudfront.net') >= 0
|
||||
? new Response(null, { status: 302, headers: { Location: 'https://other.aliyuncs.com/b.png' } })
|
||||
: okImg())
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||||
assert.strictEqual(r.status, 200, 'img: 重定向到白名单 host 应跟随 200')
|
||||
assert.strictEqual(calls.length, 2, 'img: 应发生两跳请求')
|
||||
|
||||
// 7) 无 Location 的重定向 502
|
||||
setFetch(() => new Response(null, { status: 302 }))
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||||
assert.strictEqual(r.status, 502, 'img: 重定向缺 Location 应 502')
|
||||
|
||||
// 8) content-length 超限 413
|
||||
setFetch(() => new Response(null, { status: 200, headers: { 'Content-Type': 'image/png', 'Content-Length': '99999999' } }))
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||||
assert.strictEqual(r.status, 413, 'img: 超大 content-length 应 413')
|
||||
|
||||
// 9) 非图片 content-type 415
|
||||
setFetch(() => new Response('{"a":1}', { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||||
assert.strictEqual(r.status, 415, 'img: 非图片应 415')
|
||||
|
||||
// 10) 安全头:Cloudflare Pages 的 `_headers` **不作用于 Functions 响应**
|
||||
// ⇒ 每个 Response 必须自带 nosniff + Referrer-Policy(否则未来某端点漏设 Content-Type
|
||||
// 时浏览器会自行嗅探类型 → 可能演变成 XSS)。这是 H1 的回归守卫。
|
||||
const hasSecurityHeaders = (res, who) => {
|
||||
assert.strictEqual(res.headers.get('x-content-type-options'), 'nosniff', who + ': 应有 X-Content-Type-Options: nosniff')
|
||||
assert.strictEqual(res.headers.get('referrer-policy'), 'no-referrer', who + ': 应有 Referrer-Policy: no-referrer')
|
||||
}
|
||||
setFetch(okImg)
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('d1.cloudfront.net')) })
|
||||
assert.strictEqual(r.status, 200, 'img: 正常取图应 200')
|
||||
hasSecurityHeaders(r, 'img 成功响应')
|
||||
r = await img.onRequest({ request: req('GET', imgUrl('evil.example')) })
|
||||
hasSecurityHeaders(r, 'img 403 响应')
|
||||
r = await img.onRequest({ request: req('GET', 'https://site.example/api/img?url=' + encodeURIComponent('http://d1.cloudfront.net/a.png')) })
|
||||
hasSecurityHeaders(r, 'img 400 响应')
|
||||
|
||||
// ---------- plugins/[[path]].js ----------
|
||||
const pluginsFn = await import(path.join(__dirname, '..', 'functions', 'plugins', '[[path]].js'))
|
||||
const pluginCtx = (tail, value, headers) => ({
|
||||
params: { path: [tail] },
|
||||
env: value === undefined ? {} : { PLUGINS: { get: async () => value } },
|
||||
request: req('GET', 'https://site.example/plugins/' + tail, headers || {}),
|
||||
})
|
||||
|
||||
// P1) 带内容哈希的 JS 名 → immutable + max-age=31536000
|
||||
let pr = await pluginsFn.onRequestGet(pluginCtx('plugin-xianyi-cutout.0123456789ab.js', 'console.log(1)'))
|
||||
assert.strictEqual(pr.status, 200, 'plugins: 带哈希 JS 应 200')
|
||||
assert.strictEqual(pr.headers.get('content-type'), 'application/javascript; charset=utf-8', 'plugins: 带哈希 JS 应为 application/javascript')
|
||||
assert.ok((pr.headers.get('cache-control') || '').indexOf('immutable') >= 0, 'plugins: 带哈希 JS 应含 immutable')
|
||||
assert.ok((pr.headers.get('cache-control') || '').indexOf('max-age=31536000') >= 0, 'plugins: 带哈希 JS 应含 max-age=31536000')
|
||||
|
||||
// P2) 未哈希的 JS 名 → no-cache + 非空 etag(安全网,绝不许永久缓存)
|
||||
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-xianyi-cutout.js', 'console.log(1)'))
|
||||
assert.strictEqual(pr.headers.get('cache-control'), 'no-cache', 'plugins: 未哈希 JS 应 no-cache')
|
||||
assert.ok(pr.headers.get('etag'), 'plugins: 未哈希 JS 应有非空 etag')
|
||||
|
||||
// P3) index.json → no-cache + 非空 etag,body 等于 KV 里的值
|
||||
const manifest = '[{"id":"xianyi-cutout"}]'
|
||||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', manifest))
|
||||
assert.strictEqual(pr.headers.get('content-type'), 'application/json; charset=utf-8', 'plugins: index.json 应为 application/json')
|
||||
assert.strictEqual(pr.headers.get('cache-control'), 'no-cache', 'plugins: index.json 应 no-cache')
|
||||
const manifestEtag = pr.headers.get('etag')
|
||||
assert.ok(manifestEtag, 'plugins: index.json 应有非空 etag')
|
||||
assert.strictEqual(await pr.text(), manifest, 'plugins: index.json body 应等于存储值')
|
||||
|
||||
// P4) if-none-match 命中 → 304 + 空 body + 同 etag
|
||||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', manifest, { 'if-none-match': manifestEtag }))
|
||||
assert.strictEqual(pr.status, 304, 'plugins: if-none-match 命中应 304')
|
||||
assert.strictEqual(await pr.text(), '', 'plugins: 304 应为空 body')
|
||||
assert.strictEqual(pr.headers.get('etag'), manifestEtag, 'plugins: 304 应带相同 etag')
|
||||
|
||||
// P5) 缺 KV 绑定 → 500
|
||||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', undefined))
|
||||
assert.strictEqual(pr.status, 500, 'plugins: 缺 PLUGINS 绑定应 500')
|
||||
|
||||
// P6) 未知键(KV 返回 null)→ 404 + no-store
|
||||
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-nope.js', null))
|
||||
assert.strictEqual(pr.status, 404, 'plugins: 未知键应 404')
|
||||
assert.strictEqual(pr.headers.get('cache-control'), 'no-store', 'plugins: 404 应 no-store')
|
||||
|
||||
// P7) 安全头:`_headers` 不作用于 Functions 响应 ⇒ 每个 Response 自带 nosniff + Referrer-Policy
|
||||
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-xianyi-cutout.0123456789ab.js', 'console.log(1)'))
|
||||
hasSecurityHeaders(pr, 'plugins 200 响应')
|
||||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', manifest))
|
||||
hasSecurityHeaders(pr, 'plugins 清单 200 响应')
|
||||
pr = await pluginsFn.onRequestGet(pluginCtx('plugin-nope.js', null))
|
||||
hasSecurityHeaders(pr, 'plugins 404 响应')
|
||||
pr = await pluginsFn.onRequestGet(pluginCtx('index.json', undefined))
|
||||
hasSecurityHeaders(pr, 'plugins 500 响应')
|
||||
|
||||
console.log('functions api tests passed')
|
||||
})().catch((e) => { console.error(e); process.exit(1) })
|
||||
@@ -151,14 +151,15 @@ test('⑤ 气泡删除按钮(2026-11-09 恢复,hover 红、静态灰);
|
||||
await expect(page.locator('[data-node-id="t1"]'), '气泡删除应真删掉该节点').toHaveCount(0)
|
||||
expect(await nodeCount(page), '气泡删除应让节点数 -1').toBe(n0 - 1)
|
||||
|
||||
// 删除入口②:右键菜单
|
||||
// 删除入口②:右键菜单(2026-11-19 收进「该节点▸」二级:一级只剩 添加节点/选中操作/该节点)
|
||||
const n1 = await nodeCount(page)
|
||||
const box = await page.locator('[data-node-id="p1"]').boundingBox()
|
||||
await page.mouse.click(box.x + box.width / 2, box.y + 60, { button: 'right' })
|
||||
await page.waitForTimeout(250)
|
||||
const delItem = page.locator('.iwb-ctxmenu .iwb-ctx-danger')
|
||||
await expect(delItem.first(), '右键菜单应保留「删除」').toBeVisible()
|
||||
await delItem.first().click()
|
||||
await page.locator('.iwb-ctxmenu:not(.iwb-ctx-sub)').locator('.iwb-ctx-item', { hasText: /^该节点/ }).hover()
|
||||
const delItem = page.locator('.iwb-ctxmenu.iwb-ctx-sub .iwb-ctx-danger').filter({ hasText: '删除该节点' })
|
||||
await expect(delItem, '「该节点▸」二级菜单应保留「删除」').toBeVisible()
|
||||
await delItem.click()
|
||||
expect(await nodeCount(page), '右键删除应生效').toBe(n1 - 1)
|
||||
|
||||
// 删除入口③:Delete 键
|
||||
@@ -205,8 +206,10 @@ test('⑦ 右键菜单「重命名节点」也能改名(备用入口)', asyn
|
||||
await boot(page)
|
||||
const nb = await page.locator('[data-node-id="t1"]').boundingBox()
|
||||
await page.mouse.click(nb.x + nb.width / 2, nb.y + 80, { button: 'right' })
|
||||
await expect(page.locator('.iwb-ctxmenu')).toBeVisible()
|
||||
await page.locator('.iwb-ctxmenu .iwb-ctx-item', { hasText: '重命名节点' }).click()
|
||||
await expect(page.locator('.iwb-ctxmenu:not(.iwb-ctx-sub)')).toBeVisible()
|
||||
// 2026-11-19:重命名收进「该节点▸」二级菜单
|
||||
await page.locator('.iwb-ctxmenu:not(.iwb-ctx-sub)').locator('.iwb-ctx-item', { hasText: /^该节点/ }).hover()
|
||||
await page.locator('.iwb-ctxmenu.iwb-ctx-sub .iwb-ctx-item', { hasText: '重命名节点' }).click()
|
||||
await expect(page.locator('.iwb-rename-modal')).toBeVisible()
|
||||
await page.locator('.iwb-rename-input').fill('新名字乙')
|
||||
await page.locator('.iwb-rename-modal .iwb-btn-primary').click()
|
||||
@@ -431,10 +434,11 @@ test('⑨ 节点背景色:气泡色板可选色、刷新后保留、可撤销
|
||||
await expect(page.locator('[data-node-id="n1"]')).toBeVisible({ timeout: 15000 })
|
||||
expect(await bgOf('n1'), '刷新后背景色应保留').toBe(cyanSwatchBg)
|
||||
|
||||
// ⑤ 右键菜单同一入口
|
||||
// ⑤ 右键菜单同一入口(2026-11-19:背景色收进「该节点▸」二级菜单)
|
||||
await page.locator('[data-node-id="n2"]').click({ button: 'right' })
|
||||
const ctxBg = page.locator('.iwb-ctx-item').filter({ hasText: '背景色' })
|
||||
await expect(ctxBg, '右键菜单应有「背景色」').toHaveCount(1)
|
||||
await page.locator('.iwb-ctxmenu:not(.iwb-ctx-sub)').locator('.iwb-ctx-item', { hasText: /^该节点/ }).hover()
|
||||
const ctxBg = page.locator('.iwb-ctxmenu.iwb-ctx-sub .iwb-ctx-item').filter({ hasText: '背景色' })
|
||||
await expect(ctxBg, '「该节点▸」二级菜单应有「背景色」').toBeVisible()
|
||||
await ctxBg.click()
|
||||
await expect(page.locator('.iwb-pop.iwb-bg-palette'), '右键应打开同一套色板').toBeVisible()
|
||||
const purpleSwatchBg = await page.locator('.iwb-bg-palette .iwb-bg-swatch').nth(3).evaluate((e) => getComputedStyle(e).backgroundColor)
|
||||
@@ -985,3 +989,46 @@ test('⑰ 提示词气泡「放大编辑」:单栏所见即所得(Markdown
|
||||
await page.keyboard.press('Control+E')
|
||||
await expect(page.locator('.iwb-prompt-modal'), '非提示词节点按快捷键不应打开').toHaveCount(0)
|
||||
})
|
||||
|
||||
test('⑪ 库面板(资源中心浮窗)开着时,画布空白处仍能框选', async ({ page }) => {
|
||||
// 2026-11-19:v3.25.21 加的「DOM 里有 .iwb-fullmask 就整体拦画布」把框选一起拦了 ——
|
||||
// 资源中心是可拖可连的浮窗,画布露在它外面必须还能框选;只有真模态(.iwb-modal-mask)才整体禁用。
|
||||
await boot(page)
|
||||
await page.locator('.iwb-top-nav-icon[title*="资源中心"]').click()
|
||||
await expect(page.locator('.iwb-fullmask')).toBeVisible()
|
||||
|
||||
// 在画布上找一个**没被浮窗/节点/底栏/侧栏盖住**的空白点(浮窗位置随视口变化,不能写死坐标)
|
||||
const pt = await page.evaluate(() => {
|
||||
const c = document.querySelector('.iwb-canvas')
|
||||
if (!c) return null
|
||||
const r = c.getBoundingClientRect()
|
||||
const blocked = '.iwb-node, .iwb-fullmask, .iwb-fullpanel, .iwb-toolbar, .iwb-statusbar, .iwb-minimap, .iwb-wsrail, .iwb-lib, .iwb-lib-embedded, .iwb-hint-bottom, .iwb-node-floatbar, .iwb-rightrail'
|
||||
for (let fy = 0.15; fy < 0.9; fy += 0.05) {
|
||||
for (let fx = 0.05; fx < 0.95; fx += 0.05) {
|
||||
const x = r.left + r.width * fx
|
||||
const y = r.top + r.height * fy
|
||||
const el = document.elementFromPoint(x, y)
|
||||
if (!el || !el.closest || !el.closest('.iwb-canvas')) continue
|
||||
if (el.closest(blocked)) continue
|
||||
return { x, y }
|
||||
}
|
||||
}
|
||||
return null
|
||||
})
|
||||
expect(pt, '应能在浮窗之外找到画布空白点').toBeTruthy()
|
||||
|
||||
await page.mouse.move(pt.x, pt.y)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(pt.x + 120, pt.y + 80, { steps: 8 })
|
||||
await expect(page.locator('.iwb-boxsel'), '浮窗开着时空白拖动必须出现框选').toHaveCount(1)
|
||||
await page.mouse.up()
|
||||
await expect(page.locator('.iwb-boxsel'), '松手后框选应清掉').toHaveCount(0)
|
||||
await expect(page.locator('.iwb-fullmask'), '框选不应把库面板关掉').toBeVisible()
|
||||
|
||||
// 浏览器插件面板 tab 应有图标(2026-11-19:宿主此前没有 globe 图标,tab 渲染成空白)。插件未加载时跳过。
|
||||
const bmTab = page.locator('.iwb-fullmask .iwb-res-tab', { hasText: '浏览器' })
|
||||
if (await bmTab.count()) {
|
||||
const svgHtml = await bmTab.locator('svg').first().innerHTML()
|
||||
expect(String(svgHtml).length, '浏览器 tab 图标 svg 应有内容(globe)').toBeGreaterThan(0)
|
||||
}
|
||||
})
|
||||
@@ -1,210 +0,0 @@
|
||||
// v3.86.10 CSP 门禁:本地 e2e 通过 scripts/serve-test.js 下发 _headers 里的 CSP,
|
||||
// 凡是依赖「被 CSP 禁止的能力」的实现都会在这里直接失败:
|
||||
// ① fetch(data:...) / fetch(blob:...)(connect-src 'self' https:)
|
||||
// ② 动态插 <script src="https://cdn...">(script-src 'self')
|
||||
// ③ 内联脚本 / eval / new Function(script-src 'self',无 unsafe-eval)
|
||||
// 覆盖两条真实用户链路:图库预览复制(blob: 源)+ 大图入库压缩(Worker + data: 解码)。
|
||||
// 任一 Console 出现 "Content Security Policy" 违规即视为失败——这是本 spec 的核心断言。
|
||||
const { test, expect } = require('./_pw-coverage')
|
||||
|
||||
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
|
||||
test.use({ baseURL, viewport: { width: 1440, height: 1000 }, permissions: ['clipboard-read', 'clipboard-write'] })
|
||||
|
||||
// 大图 fixture 的尺寸:**唯一来源**。canvas 生成 / outputs 声明 / 复制后断言全部引用它,
|
||||
// 避免"改了 fixture 却忘了改断言"这类硬编码漂移(2026-10-28 就是这么挂了一次)。
|
||||
const FIXTURE_W = 1100
|
||||
const FIXTURE_H = 800
|
||||
|
||||
const CFG = {
|
||||
providers: [],
|
||||
outputsRetention: { enabled: true, maxFiles: 500, maxDays: 15 },
|
||||
canvas: { snap: true, backupOriginals: true },
|
||||
image: { compress: { enabled: true, maxMB: 0.01, maxEdge: 1024, quality: 0.7 } },
|
||||
}
|
||||
|
||||
const WS = {
|
||||
workspaces: [{
|
||||
id: 'ws_csp', name: 'CSP',
|
||||
nodes: [
|
||||
{ id: 'ra', type: 'ref', x: 80, y: 120, data: { url: '', data: null, name: '', localName: null } },
|
||||
{ id: 'p1', type: 'prompt', x: 620, y: 120, data: { text: '提示词', title: 'P1' } },
|
||||
],
|
||||
edges: [], groups: [],
|
||||
}],
|
||||
activeId: 'ws_csp', rev: 1,
|
||||
}
|
||||
|
||||
// 大图 fixture:同时满足两个硬约束 ——
|
||||
// ① **尺寸必须真的超阈值**:CFG 里 maxMB=0.01(≈10KB)⇒ 任何 >13KB 的 base64 都会走压缩链路,
|
||||
// 所以不需要"约 1MB"那么大;
|
||||
// ② **必须装得进 localStorage**:outputs 里 url 与 data 各存一份 dataURL(约 2 倍体积),
|
||||
// 而 localStorage 每 origin 约 5MB。
|
||||
//
|
||||
// ⚠️ 2026-10-28 实测踩坑(playwright 1.52→1.64.1 / Chromium 1169→1248,Chrome 156):
|
||||
// 同一段代码 `toDataURL('image/png')` 的输出**随浏览器版本变化**——旧版本 1600×1200 约 1MB,
|
||||
// 新版本同样尺寸变成 **2.81MB**(近似未压缩),双份 JSON = **5.63MB ⇒ 超配额**,
|
||||
// `setItem` 抛 QuotaExceededError ⇒ 整个 addInitScript 后续语句不执行 ⇒ 图库恒为 0/0 ⇒ 测试假失败。
|
||||
// 现在改为 1100×800(实测 dataURL 1.27MB / JSON 2.53MB,配额安全),
|
||||
// 且长边 1100 > maxEdge 1024 ⇒ 仍会触发缩放,test 2 的「压缩+缩放」语义不变。
|
||||
async function bigPngDataUrl(page) {
|
||||
return page.evaluate(([W, H]) => {
|
||||
const c = document.createElement('canvas')
|
||||
c.width = W; c.height = H
|
||||
const x = c.getContext('2d')
|
||||
const g = x.createLinearGradient(0, 0, W, H)
|
||||
g.addColorStop(0, '#2f6bff'); g.addColorStop(0.5, '#e2453c'); g.addColorStop(1, '#16a34a')
|
||||
x.fillStyle = g; x.fillRect(0, 0, W, H)
|
||||
for (let i = 0; i < 600; i++) x.fillRect((i * 37) % W, (i * 53) % H, 3, 3)
|
||||
return c.toDataURL('image/png')
|
||||
}, [FIXTURE_W, FIXTURE_H])
|
||||
}
|
||||
|
||||
async function boot(page, outputs) {
|
||||
await page.addInitScript((d) => {
|
||||
localStorage.clear()
|
||||
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
|
||||
localStorage.setItem('iwb_web_workspaces', JSON.stringify(d.ws))
|
||||
localStorage.setItem('iwb_ws_active', d.ws.activeId)
|
||||
localStorage.setItem('iwb_ws_' + d.ws.activeId, JSON.stringify(d.ws.workspaces[0]))
|
||||
localStorage.setItem('iwb_web_outputs', JSON.stringify(d.outputs))
|
||||
localStorage.setItem('iwb_e2e_initialized', '1')
|
||||
// 配额探测:setItem 抛错会让**后续语句全部不执行**(图库恒空、__IWB_E2E__ 也不设),
|
||||
// 表现为「元素找不到」这种极难定位的假失败。这里把实际写入长度记到 window 上,
|
||||
// 由 Node 侧 goto 之后立刻校验并抛出**可读**的错误(在 initScript 里 throw 不会中止测试)。
|
||||
let wrote = -1
|
||||
try { wrote = (localStorage.getItem('iwb_web_outputs') || '').length } catch (e) { wrote = -1 }
|
||||
window.__IWB_FIXTURE_OUTPUTS_LEN__ = wrote
|
||||
// e2e 探针:暴露压缩 / 存缩略图两个最小入口(生产不设置该标志)
|
||||
window.__IWB_E2E__ = true
|
||||
}, { cfg: CFG, ws: WS, outputs })
|
||||
await page.goto('/', { waitUntil: 'domcontentloaded' })
|
||||
// ── 配额守卫(Node 侧)─────────────────────────────────────────────
|
||||
// 为什么不在 initScript 里 throw:那里抛出的异常不会中止测试,
|
||||
// 只会让后续步骤连锁失败成「元素找不到」,根本看不出真正原因(2026-10-28 实测过)。
|
||||
{
|
||||
const expectLen = JSON.stringify(outputs).length
|
||||
// undefined = initScript 在写 outputs 那一步就抛了(配额不足),后续赋值没执行
|
||||
const actualLen = await page.evaluate(() => window.__IWB_FIXTURE_OUTPUTS_LEN__ ?? 0)
|
||||
if (actualLen !== expectLen) {
|
||||
throw new Error(
|
||||
'[e2e fixture] localStorage 写入不完整,多半是配额不足(每 origin 约 5MB)\n'
|
||||
+ ' 期望 iwb_web_outputs = ' + expectLen + ' 字符,实际 ' + actualLen + '\n'
|
||||
+ ' 注意:本 fixture 把同一个 dataURL 存了 url + data 两份(约 2 倍体积)。\n'
|
||||
+ ' toDataURL 的输出大小**随浏览器版本变化** —— 缩小 FIXTURE_W/FIXTURE_H 即可。')
|
||||
}
|
||||
}
|
||||
await page.waitForTimeout(700)
|
||||
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
|
||||
await expect(page.locator('.iwb-canvas:not(.iwb-canvas-hidden)')).toBeVisible()
|
||||
await page.waitForTimeout(400)
|
||||
}
|
||||
|
||||
// 收集 CSP 违规(Console 原文里带 "Content Security Policy")+ 页面异常
|
||||
function watchCsp(page) {
|
||||
const csp = []
|
||||
const errors = []
|
||||
page.on('console', (m) => { const t = m.text() || ''; if (/Content Security Policy/i.test(t) || /Refused to (connect|load|create)/i.test(t)) csp.push(t) })
|
||||
page.on('pageerror', (e) => errors.push(String((e && e.message) || e)))
|
||||
return { csp, errors }
|
||||
}
|
||||
|
||||
// IndexedDB 里按 key 前缀取内容(图库缩略图 = out_<name>)
|
||||
async function idbGet(page, key) {
|
||||
return page.evaluate((k) => new Promise((resolve) => {
|
||||
const req = indexedDB.open('iwb_web')
|
||||
req.onerror = () => resolve(null)
|
||||
req.onsuccess = () => {
|
||||
const db = req.result
|
||||
let tx
|
||||
try { tx = db.transaction('images', 'readonly') } catch (e) { try { db.close() } catch (e2) {} return resolve(null) }
|
||||
const gr = tx.objectStore('images').get(k)
|
||||
gr.onerror = () => resolve(null)
|
||||
gr.onsuccess = () => { try { db.close() } catch (e) {} resolve(gr.result == null ? null : String(gr.result)) }
|
||||
}
|
||||
req.onupgradeneeded = () => { try { req.result.close() } catch (e) {} resolve(null) }
|
||||
}), key)
|
||||
}
|
||||
|
||||
async function idbKeys(page) {
|
||||
return page.evaluate(() => new Promise((resolve) => {
|
||||
const req = indexedDB.open('iwb_web')
|
||||
req.onerror = () => resolve([])
|
||||
req.onsuccess = () => {
|
||||
const db = req.result
|
||||
let tx
|
||||
try { tx = db.transaction('images', 'readonly') } catch (e) { try { db.close() } catch (e2) {} return resolve([]) }
|
||||
const kr = tx.objectStore('images').getAllKeys()
|
||||
kr.onerror = () => resolve([])
|
||||
kr.onsuccess = () => { try { db.close() } catch (e) {} resolve((kr.result || []).map(String)) }
|
||||
}
|
||||
req.onupgradeneeded = () => { try { req.result.close() } catch (e) {} resolve([]) }
|
||||
}))
|
||||
}
|
||||
|
||||
test('1. 图库预览复制:blob: 源在 CSP 下必须成功(fetch(blob:) 已被 connect-src 拦)', async ({ page }) => {
|
||||
const urls = { png: await bigPngDataUrl(page) }
|
||||
const w = watchCsp(page)
|
||||
await boot(page, [{ name: 'csp_png.png', url: urls.png, data: urls.png, size: 900000, mtime: Date.now() - 1000, w: FIXTURE_W, h: FIXTURE_H }])
|
||||
|
||||
await page.locator('.iwb-top-nav-icon[title*="资源中心"]').click()
|
||||
await expect(page.locator('.iwb-fullmask')).toBeVisible()
|
||||
await page.locator('.iwb-fullmask .iwb-res-tab').filter({ hasText: '图库' }).click()
|
||||
const thumb = page.locator('.iwb-history-item img[title^="csp_png.png"]')
|
||||
await expect(thumb).toBeVisible()
|
||||
await thumb.dblclick()
|
||||
await expect(page.locator('.iwb-imgpreview')).toBeVisible()
|
||||
// 预览把 dataURL 解析成 objectURL 后才可复制(复制源就是它)
|
||||
await expect.poll(() => page.locator('.iwb-imgpreview img').getAttribute('src'), { timeout: 8000 }).toContain('blob:')
|
||||
await page.locator('.iwb-imgpreview .iwb-prev-bar button', { hasText: '复制' }).click()
|
||||
await expect(page.locator('.iwb-status-ok').filter({ hasText: '已复制图片到剪贴板' }), 'CSP 下 blob: 源复制必须成功').toBeVisible()
|
||||
|
||||
const clip = await page.evaluate(async () => {
|
||||
const items = await navigator.clipboard.read()
|
||||
const pngItem = items.find((it) => it.types.includes('image/png'))
|
||||
if (!pngItem) return { types: items.map((it) => it.types.join('+')), ok: false }
|
||||
const bmp = await createImageBitmap(await pngItem.getType('image/png'))
|
||||
const out = { ok: true, type: 'image/png', w: bmp.width, h: bmp.height }
|
||||
if (bmp.close) bmp.close()
|
||||
return out
|
||||
})
|
||||
expect(clip.ok, JSON.stringify(clip)).toBe(true)
|
||||
// 复制的必须是**原图全尺寸**,不是压缩后的缩略图
|
||||
expect(clip.w).toBe(FIXTURE_W)
|
||||
expect(clip.h).toBe(FIXTURE_H)
|
||||
expect(w.csp, '不得出现 CSP 违规:\n' + w.csp.join('\n')).toEqual([])
|
||||
expect(w.errors).toEqual([])
|
||||
})
|
||||
|
||||
test('2. 大图入库压缩:CSP 下 Worker/解码/落库全链路必须产出压缩缩略图(out_)且无 CSP 违规', async ({ page }) => {
|
||||
const bigPng = await bigPngDataUrl(page)
|
||||
const w = watchCsp(page)
|
||||
await boot(page, [])
|
||||
|
||||
// 走应用自己的 compressDataUrl(与保存/上传/缩略图完全同一条代码路径)
|
||||
const compressed = await page.evaluate(async (png) => {
|
||||
const t0 = Date.now()
|
||||
const out = await window.__IWB_E2E__API__.compress(png, { maxEdge: 320, quality: 0.72, format: 'jpeg' })
|
||||
return { out, ms: Date.now() - t0 }
|
||||
}, bigPng)
|
||||
expect(compressed.out && compressed.out.indexOf('data:image/jpeg') === 0, '压缩产物应是 JPEG dataURL').toBe(true)
|
||||
expect(compressed.out.length).toBeLessThan(bigPng.length)
|
||||
expect(await page.evaluate((d) => { const b = atob(d.split(',')[1]); return b.length > 200 }, compressed.out)).toBe(true)
|
||||
|
||||
// 压缩必须真的跑在 Worker 线程(worker-src 未放行时会退化成主线程,那正是线上卡顿的根因)
|
||||
const used = await page.evaluate(() => window.__IWB_COMPRESS_LAST__)
|
||||
expect(used, '大图压缩必须走 Worker(不得静默退化成主线程)').toBe('worker')
|
||||
|
||||
// 落库链路:storeOutputThumb → out_<name>(图库缩略图)+ out_orig_<name>(原图)
|
||||
const stored = await page.evaluate(async (d) => {
|
||||
return await window.__IWB_E2E__API__.thumb({ name: 'csp_probe.png', data: d, url: '' })
|
||||
}, bigPng)
|
||||
expect(stored, 'storeOutputThumb 应返回写入的原图 IDB key').toBe('out_orig_csp_probe.png')
|
||||
const keys = await idbKeys(page)
|
||||
expect(keys, 'IDB 里必须出现 out_ 压缩缩略图;实际 keys=' + JSON.stringify(keys)).toContain('out_csp_probe.png')
|
||||
const thumb = await idbGet(page, 'out_csp_probe.png')
|
||||
expect(String(thumb).indexOf('data:image/jpeg') === 0, '缩略图应是压缩后的 JPEG dataURL').toBe(true)
|
||||
expect(String(thumb).length).toBeLessThan(bigPng.length)
|
||||
|
||||
expect(w.csp, '不得出现 CSP 违规:\n' + w.csp.join('\n')).toEqual([])
|
||||
expect(w.errors).toEqual([])
|
||||
})
|
||||
@@ -1,84 +0,0 @@
|
||||
// Pages Functions 安全头门禁(2026-10-20 加,审计 H1 的自动化护栏)。
|
||||
//
|
||||
// 背景(为什么会加):
|
||||
// Cloudflare Pages 的 `_headers` **不作用于 Pages Functions 响应**
|
||||
// (https://developers.cloudflare.com/pages/configuration/headers/)——
|
||||
// 静态资源(app.js / style.css)有 CSP + nosniff,而 `/api/*` 与 `/plugins/*` 这两个
|
||||
// Functions 此前**一个安全头都没有**。性质是**纵深防御缺口**(每个响应本就显式设了
|
||||
// 安全的 Content-Type,不是可利用漏洞),但缺兜底意味着:将来新增端点时漏设
|
||||
// Content-Type,浏览器会自行嗅探类型 ⇒ 可能演变成 XSS。
|
||||
// 此前这两条路径**本地完全测不到**(serve-test.js 只服务 dist/ 静态资源),
|
||||
// 「本地过、线上挂」这一类缺陷无法被 e2e 发现 ⇒ 补上本地 Functions 模拟 + 本用例。
|
||||
//
|
||||
// 本用例守三件事:
|
||||
// ① 每个 Function 响应的**每个分支**都带 X-Content-Type-Options: nosniff + Referrer-Policy: no-referrer;
|
||||
// ② Function 响应**不含** `_headers` 里的 CSP —— 显式钉死「本地与线上一致:_headers 不作用于 Function」;
|
||||
// (这条最关键:若哪天本地"好心"给 Function 套上 CSP,线上差异就被掩盖了,② 会先红)
|
||||
// ③ 静态资源**仍然**带 CSP —— 防止修 Functions 时误伤静态资源的既有防护。
|
||||
//
|
||||
// 依赖:scripts/serve-test.js 的本地 Functions 模拟(/api/* 与 /plugins/* 路由)。
|
||||
// 该模拟**只透传 Function 自己的 header**,不叠加 _headers —— 与线上语义一致。
|
||||
|
||||
const { test, expect } = require('./_pw-coverage')
|
||||
|
||||
const baseURL = process.env.IWB_BASE_URL || 'http://127.0.0.1:8787'
|
||||
test.use({ baseURL, viewport: { width: 1280, height: 900 } })
|
||||
|
||||
// 断言某个响应带 Functions 必带的安全头
|
||||
async function expectFunctionSecurityHeaders(res, who) {
|
||||
const h = res.headers() // APIResponse.headers() 是同步的,返回小写 header 名映射
|
||||
expect(h['x-content-type-options'], who + ' 应有 X-Content-Type-Options: nosniff').toBe('nosniff')
|
||||
expect(h['referrer-policy'], who + ' 应有 Referrer-Policy: no-referrer').toBe('no-referrer')
|
||||
}
|
||||
|
||||
test('Functions 响应带 nosniff + Referrer-Policy(且不含 _headers 的 CSP)', async ({ request }) => {
|
||||
// ① /plugins/index.json(清单)
|
||||
const manifest = await request.get('/plugins/index.json')
|
||||
expect(manifest.status(), '/plugins/index.json 应 200').toBe(200)
|
||||
await expectFunctionSecurityHeaders(manifest, '/plugins/index.json')
|
||||
|
||||
// ② /plugins/<内容寻址>.js(不可变缓存的插件字节)
|
||||
const body = await manifest.text()
|
||||
const file = (JSON.parse(body)[0] || {}).file
|
||||
expect(file, '本地 mock 清单应含一个插件').toBeTruthy()
|
||||
const pluginJs = await request.get('/plugins/' + file)
|
||||
expect(pluginJs.status(), '/plugins/' + file + ' 应 200').toBe(200)
|
||||
await expectFunctionSecurityHeaders(pluginJs, '/plugins/' + file)
|
||||
|
||||
// ③ /plugins 未知键 → 404 分支也必须带安全头
|
||||
const missing = await request.get('/plugins/plugin-does-not-exist.js')
|
||||
expect(missing.status(), '/plugins 未知键应 404').toBe(404)
|
||||
await expectFunctionSecurityHeaders(missing, '/plugins 404')
|
||||
|
||||
// ④ /api/img 各分支:非白名单 host → 403
|
||||
const forbidden = await request.get('/api/img?url=' + encodeURIComponent('https://evil.example/a.png'))
|
||||
expect(forbidden.status(), '/api/img 非白名单 host 应 403').toBe(403)
|
||||
await expectFunctionSecurityHeaders(forbidden, '/api/img 403')
|
||||
|
||||
// ⑤ /api/img 非 https → 400
|
||||
const badProto = await request.get('/api/img?url=' + encodeURIComponent('http://d1.cloudfront.net/a.png'))
|
||||
expect(badProto.status(), '/api/img 非 https 应 400').toBe(400)
|
||||
await expectFunctionSecurityHeaders(badProto, '/api/img 400')
|
||||
|
||||
// ⑥ /api/img 成功分支(上游由 serve-test 本地 mock,不依赖外部图床)
|
||||
const ok = await request.get('/api/img?url=' + encodeURIComponent('https://d1.cloudfront.net/a.png'))
|
||||
expect(ok.status(), '/api/img 白名单 host 应 200').toBe(200)
|
||||
await expectFunctionSecurityHeaders(ok, '/api/img 200')
|
||||
|
||||
// ② 反向断言:Function 响应**不含** CSP —— 与线上一致(_headers 不作用于 Functions)。
|
||||
// 这条防止本地模拟"好心"叠加 CSP,从而掩盖真实的线上差异。
|
||||
for (const res of [manifest, pluginJs, missing, forbidden, badProto, ok]) {
|
||||
const csp = res.headers()['content-security-policy']
|
||||
expect(csp, 'Function 响应不应带 CSP(_headers 不作用于 Functions;线上亦如此)').toBeFalsy()
|
||||
}
|
||||
})
|
||||
|
||||
test('静态资源仍带 CSP(修 Functions 时不得误伤静态资源防护)', async ({ request }) => {
|
||||
const app = await request.get('/app.js')
|
||||
expect(app.status(), '/app.js 应 200').toBe(200)
|
||||
const csp = app.headers()['content-security-policy']
|
||||
expect(csp, '静态资源应有 Content-Security-Policy').toBeTruthy()
|
||||
expect(csp, 'CSP 应限制 script-src 为 self').toContain("script-src 'self'")
|
||||
expect(csp, 'CSP 不应允许 unsafe-eval').not.toContain('unsafe-eval')
|
||||
expect(app.headers()['x-content-type-options'], '静态资源应有 nosniff').toBe('nosniff')
|
||||
})
|
||||