Compare commits
186
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b00a59f4ba | ||
|
|
3eb8900b51 | ||
|
|
01253fceea | ||
|
|
dd294a75cd | ||
|
|
0ea25fcea2 | ||
|
|
d43b1520dc | ||
|
|
37c7c4b666 | ||
|
|
e97c9beb0d | ||
|
|
89841c4d4d | ||
|
|
99269aa0ae | ||
|
|
8f1f7ea7a7 | ||
|
|
48d86f3e0f | ||
|
|
4092eb5437 | ||
|
|
7c348e60c7 | ||
|
|
deac7513fd | ||
|
|
f0568342b1 | ||
|
|
b9c110709d | ||
|
|
c9bb3b09f3 | ||
|
|
4f4e64a989 | ||
|
|
9959096ab3 | ||
|
|
e7f8e68909 | ||
|
|
eb6880b11f | ||
|
|
ba9a4448e4 | ||
|
|
5ff3318fb9 | ||
|
|
8c6ed43078 | ||
|
|
9ed18827a8 | ||
|
|
352cac6031 | ||
|
|
2d2738f3a1 | ||
|
|
27a641903c | ||
|
|
89c2dca424 | ||
|
|
b8718d6810 | ||
|
|
17fd3be13b | ||
|
|
e7d54cb0a8 | ||
|
|
1aba7a0c94 | ||
|
|
4fc4e469c2 | ||
|
|
7cb4379e41 | ||
|
|
f5a5712628 | ||
|
|
56962dca0b | ||
|
|
e9da55cced | ||
|
|
ced0482ed8 | ||
|
|
3a563950ba | ||
|
|
eec5ab6c9b | ||
|
|
385a73c111 | ||
|
|
89d3cfc619 | ||
|
|
ae9b07fe91 | ||
|
|
cb56ffdfda | ||
|
|
34ba29f04f | ||
|
|
65ea7cd64c | ||
|
|
51cfa56f26 | ||
|
|
9f148f06ef | ||
|
|
178b36c477 | ||
|
|
d8f1e89e74 | ||
|
|
b914c76df4 | ||
|
|
98ed47673f | ||
|
|
1ceb241b89 | ||
|
|
efe58236e1 | ||
|
|
dbf3adfc77 | ||
|
|
b10a3bf28d | ||
|
|
09730c7ee9 | ||
|
|
4c6ef7098c | ||
|
|
7a15511582 | ||
|
|
1fa7a8d24a | ||
|
|
2c96524f6b | ||
|
|
2c2ad434bc | ||
|
|
a3d289da21 | ||
|
|
79d631ce86 | ||
|
|
98826f9ee3 | ||
|
|
89eb3053c6 | ||
|
|
aca659615e | ||
|
|
f97fbf6330 | ||
|
|
64db27155a | ||
|
|
e02b5f4345 | ||
|
|
59403a4867 | ||
|
|
5d4bdf5400 | ||
|
|
4539668c06 | ||
|
|
d151df3512 | ||
|
|
ca1764b2c4 | ||
|
|
c9d06b8388 | ||
|
|
4f92ec12dc | ||
|
|
d190cc6433 | ||
|
|
c917d267eb | ||
|
|
99649b0ecd | ||
|
|
675ccf5016 | ||
|
|
f65f037cff | ||
|
|
b2c3dd18d0 | ||
|
|
a4f69164dd | ||
|
|
06fa7f0a9b | ||
|
|
928ffa0de0 | ||
|
|
d42cc3a409 | ||
|
|
00f03de106 | ||
|
|
e6400b35c3 | ||
|
|
59ccc66de4 | ||
|
|
8180607754 | ||
|
|
501e46965a | ||
|
|
5c34856c6a | ||
|
|
8b72967381 | ||
|
|
2fb6372252 | ||
|
|
8078f6495e | ||
|
|
013bb6ba13 | ||
|
|
5e09a587e2 | ||
|
|
aa4ec99c0b | ||
|
|
a5081a81bb | ||
|
|
3e55a83169 | ||
|
|
c25144138d | ||
|
|
59b6393e8a | ||
|
|
930ca2b02a | ||
|
|
b318bae3d2 | ||
|
|
acbf31c26e | ||
|
|
c3eb72fb10 | ||
|
|
c8ae61a3ed | ||
|
|
3ea7c239ac | ||
|
|
344da1bb45 | ||
|
|
f51626040c | ||
|
|
8523120f6c | ||
|
|
3d21bf6457 | ||
|
|
dfe08dcb3c | ||
|
|
87384f124d | ||
|
|
7e9d73d702 | ||
|
|
e8a15cca75 | ||
|
|
e00f211031 | ||
|
|
ebf277158b | ||
|
|
b0258f9ab6 | ||
|
|
59588ef4cc | ||
|
|
b89b181173 | ||
|
|
57efde3eea | ||
|
|
8670619690 | ||
|
|
2495c5bde7 | ||
|
|
5da8f6d3f1 | ||
|
|
ceb97aecee | ||
|
|
da0c3f35c2 | ||
|
|
070a4818f9 | ||
|
|
a487fd3d44 | ||
|
|
61b279a2ca | ||
|
|
c7f619a36d | ||
|
|
43b02a3a1c | ||
|
|
7c7eff40ee | ||
|
|
ca43f08f03 | ||
|
|
3dde0b15b4 | ||
|
|
02fba5aef0 | ||
|
|
9b98eb1a7e | ||
|
|
758e76572f | ||
|
|
b904e9739e | ||
|
|
70b50dc654 | ||
|
|
dccac9d88b | ||
|
|
6c3b21232c | ||
|
|
fa13eb5997 | ||
|
|
21b1c70acb | ||
|
|
df5361cf6e | ||
|
|
7119dcf356 | ||
|
|
fe1d3fcaa6 | ||
|
|
e5e1c25c24 | ||
|
|
a1d0a8e980 | ||
|
|
0cbfc15a60 | ||
|
|
f52aeaa46e | ||
|
|
f7e2b786c7 | ||
|
|
2dc43b701f | ||
|
|
5b2e49f052 | ||
|
|
57070a5720 | ||
|
|
01391ee8b8 | ||
|
|
0c42831cab | ||
|
|
c78da782a2 | ||
|
|
35133d4c23 | ||
|
|
f8998faef0 | ||
|
|
bab181b12f | ||
|
|
a74978d09a | ||
|
|
136fdf58f5 | ||
|
|
329b4638c3 | ||
|
|
9dd3b0985b | ||
|
|
e015b26e0b | ||
|
|
9b09c7606f | ||
|
|
b136217e2f | ||
|
|
20118eec0b | ||
|
|
a8512ba777 | ||
|
|
d16e68bfa9 | ||
|
|
00a2699e89 | ||
|
|
fdfb4ed603 | ||
|
|
929b7ec2a1 | ||
|
|
a94e5be954 | ||
|
|
b6d10339f6 | ||
|
|
89c8e0a1d8 | ||
|
|
9bbb94b789 | ||
|
|
6284f84d29 | ||
|
|
b299895730 | ||
|
|
32363d8c9b | ||
|
|
352a7668d7 | ||
|
|
3baa76d0cd |
No files matched your search
@@ -1,175 +1,199 @@
|
||||
# IWB 插件仓
|
||||
# IWB 插件仓(桌面客户端)
|
||||
|
||||
本仓**只写插件**,不复制宿主契约。宿主(`image-workbench-web` / 工作树 `iwb-arch`)负责提供并演进
|
||||
`window.IWBPluginHost` 契约;这里只消费它。
|
||||
本仓**只写插件**,是桌面宿主 `image-workbench-desktop`(Tauri v2 客户端,数据全部落本机)的插件源仓。
|
||||
宿主负责提供并演进 `window.IWBPluginHost` 契约,这里只消费它;本仓不复制宿主契约、不改宿主代码。
|
||||
|
||||
## 为什么能"不动主仓"
|
||||
插件是**可信代码**:与画布同页、同源、同 JS 上下文运行(宿主动态注入 `<script>`),可读画布数据、可发网络请求。
|
||||
只写你信任的插件。
|
||||
|
||||
插件**不复制宿主契约**,只消费 `window.IWBPluginHost`。两条落地路径**都不需要改宿主代码**:
|
||||
## 插件怎么到用户手里
|
||||
|
||||
- **路径 A(推荐,实际采用)**:运行时从 KV 加载 —— 本仓开发 → 上传 KV → 刷新即生效(**不重编译、不部署宿主**)。
|
||||
- **路径 B**:构建期并入 —— 本仓开发 → `src/plugin-<id>.js`(宿主构建**自动发现** `plugin-*.js` 并排序追加)→ 宿主 verify → 部署。
|
||||
桌面客户端**不随包发布插件**,插件全部从插件市场安装到本机资料目录:
|
||||
|
||||
两条路都**不需要改宿主的代码 / 清单 / 快照**。详见下文「两条合入路径」与「运行时机制」。
|
||||
|
||||
## 两条合入路径(同一条契约,不同部署形态)
|
||||
|
||||
宿主(`iwb-arch`)同时提供两条路径;**当前唯一真实插件 `xianyi-cutout` 走的是路径 A**。
|
||||
|
||||
### 路径 A:运行时发布到 KV(推荐,本仓插件实际采用)
|
||||
|
||||
源码迁出主仓,经 Cloudflare Function `functions/plugins/[[path]].js` + KV(binding `PLUGINS`)**同源运行时加载**。
|
||||
上传后**刷新浏览器即生效**,不重编译、不 deploy 主仓。
|
||||
|
||||
```bash
|
||||
cd /Users/qiqi/open/github/iwb-arch
|
||||
# 发布器算 SHA-256(SRI integrity)→ 写 plugins/index.json → 上传 KV;输入文件名须为 plugin-<id>.js
|
||||
cp /绝对路径/<插件目录>/src/index.js /tmp/plugin-<id>.js
|
||||
node scripts/plugins-publish.mjs /tmp/plugin-<id>.js --upload --version <id>=<ver>
|
||||
```
|
||||
本仓 <id>/src/index.js
|
||||
→ 桌面仓 node scripts/sync-plugins-from-repo.js # 拷到 plugins/runtime/,内容寻址命名 + SRI
|
||||
→ 桌面仓 node scripts/gen-market.js # 生成 market/index.json + market/plugins/*
|
||||
→ 上传 market/ 到 NAS /vol8/web/iwb-market/ # market.maqiart.eu.org(纯静态)
|
||||
→ 用户在客户端「设置 → 插件 / 市场」安装
|
||||
```
|
||||
|
||||
- **发布器必须写出 `SHA-256`(SRI integrity)到 `plugins/index.json`**;宿主用 `<script integrity>` 强制校验,
|
||||
**缺失/不符即拒载(fail-closed)** —— 这是硬要求。
|
||||
- 推荐 `plugins-publish.mjs`(默认 dry-run、`--upload` 才写 KV;输入文件名须为 `plugin-<id>.js`)。
|
||||
`plugins-publish.sh`(`<id> <file> [version]`)**现已同样产出 `integrity`**,可放心使用。
|
||||
- A2 Function 已在**测试站与正式站**上线;本地发布后刷新浏览器即生效。
|
||||
- 市场索引:`https://market.maqiart.eu.org/index.json`,每个条目带 `sha256` 与 `integrity`。
|
||||
- 安装落点:`<资料目录>/plugins/`(macOS 默认 `~/Documents/ImageWorkbench/plugins/`)。
|
||||
加载时校验 sha256/integrity,**不符即拒载(fail-closed)**。
|
||||
|
||||
### 路径 B:构建期并入 `src/plugin-<id>.js`
|
||||
|
||||
```bash
|
||||
cd /Users/qiqi/open/github/iwb-arch
|
||||
scripts/plugins-sync.sh <本仓路径或 URL> <插件 id> [源文件,默认 dist/plugin.js] [--force]
|
||||
npm run verify # 全绿
|
||||
npm run deploy:test # 发到测试站
|
||||
```
|
||||
|
||||
`scripts/build.js` 自动发现 `src/plugin-*.js`(按文件名排序追加),合入**不需要改主仓任何代码**。
|
||||
`plugins-sync.sh` 会打印来源 `仓库@tag (sha)`,请把它写进宿主的提交信息,便于追溯。
|
||||
|
||||
## 校验(本地 + CI)
|
||||
|
||||
```bash
|
||||
npm run validate # 契约:ibwPlugin 字段、entry 语法、entry 内 manifest(id/apiVersion/version/name/capabilities)与 package.json 一致
|
||||
```
|
||||
|
||||
`.github/workflows/ci.yml` 在 push / PR 时跑同一条命令(只读源码,不需要网络或依赖)。
|
||||
开发者调试不必走市场:用「开发者模式」直接加载本机未签名代码,见下文「本地调试」。
|
||||
|
||||
## 插件契约(写插件前必读)
|
||||
|
||||
每个插件 = **一个 IIFE 文件**,加载时向宿主注册:
|
||||
每个插件 = **一个 IIFE 文件**,脚本执行时向宿主注册:
|
||||
|
||||
```js
|
||||
;(function (global) {
|
||||
if (!global.IWBPluginHost) return
|
||||
global.IWBPluginHost.register(manifest, function (ctx) {
|
||||
'use strict'
|
||||
global.IWBPluginHost.register({
|
||||
id: 'hello-world', name: '示例插件', version: '0.1.0', apiVersion: 1,
|
||||
capabilities: ['nodeActions', 'canvas']
|
||||
}, function (ctx) {
|
||||
// 在这里用 ctx 注册能力;返回 { dispose } 可选
|
||||
return {}
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
```
|
||||
|
||||
**manifest**:`id`(`^[a-z][a-z0-9-]{2,31}$`)、`name`、`version`、`apiVersion`、`capabilities`、可选 `settings`(每项 `{type:'text'|'number'|'boolean', label, desc, default}`)。
|
||||
**manifest 必填**:`id`(`^[a-z][a-z0-9-]{2,31}$`)、`name`、`version`、`apiVersion`(当前 `1`)、`capabilities`。
|
||||
可选 `settings`:对象 `{ 键: { label, desc, default, type } }`,`type` 为 `text` / `number` / `boolean`。
|
||||
|
||||
**恒定提供**:`ctx.settings` / `ctx.log` / `ctx.storage`(按插件 id 隔离)/ `ctx.events`。
|
||||
**恒定提供**(`ctx` 上一定有):
|
||||
|
||||
**声明式能力**(在 `capabilities` 里声明后才发放):
|
||||
| API | 用途 |
|
||||
|---|---|
|
||||
| `ctx.settings` | `all()` / `get(k)` / `set(k,v)` / `onChange(fn)`;缺省值取 manifest 的 `settings[].default` |
|
||||
| `ctx.storage` | `ctx.storage.namespace(ns)` → `{ get, set, remove, keys }`,按插件 id + 命名空间隔离 |
|
||||
| `ctx.log(...)` | 写宿主日志 |
|
||||
| `ctx.events` | `on(name,fn)` / `emit(name,payload)` |
|
||||
|
||||
| capability | `ctx.` 下的 API | 用途 |
|
||||
**声明式能力**(在 `capabilities` 里声明后才发放到 `ctx`):
|
||||
|
||||
| capability | 挂到 ctx 的 key | 用途 |
|
||||
|---|---|---|
|
||||
| `commands` | `ctx.commands.register({id,title,icon,run})` | 右键菜单「插件命令」 |
|
||||
| `nodeActions` | `ctx.nodeActions.register({id,title,icon,appliesTo(node),run(node)})` | 节点漂浮菜单按钮 |
|
||||
| `nodeTypes` | `ctx.nodes.register({id,title,defaults,run})` | 通用插件节点 `type:'plugin'` 的变体 |
|
||||
| `panels` | `ctx.ui.registerPanel({id,title,mount(el)})` | 资源中心新增插件面板 |
|
||||
| `generationHooks` | `ctx.generation.use({beforeRequest,afterResult})` | 改写生图请求体 / 处理归档结果 |
|
||||
| `providers` | `ctx.providers.register({id,name,baseUrl,key,models})` | 外部服务提供方(可直接当生图后端) |
|
||||
| `canvas` | `ctx.canvas.getNodes()/listNodeTypes()/getSelectedNode()/getNodeImage(id)` | 只读画布(`getNodeImage` 异步直出 dataURL) |
|
||||
| `canvasWrite` | `ctx.canvas.createNode(...)/createImageNode({dataUrl,name})/setNodeImage(id,dataUrl)` | 受控写画布 |
|
||||
| `panels` | `ctx.ui` | `registerPanel({id,title,mount(el)})`,资源中心新增插件面板 |
|
||||
| `commands` | `ctx.commands` | `register({id,title,icon,run})`,右键菜单「插件命令」 |
|
||||
| `nodeActions` | `ctx.nodeActions` | `register({id,title,icon,appliesTo(node),run(node)})`,节点漂浮菜单按钮 |
|
||||
| `nodeTypes` | `ctx.nodes` | `register({id,title,ports,height,color,render})`,通用插件节点变体 |
|
||||
| `generationHooks` | `ctx.generation` | `use({beforeRequest,afterResult})`,改写生图请求 / 处理归档结果 |
|
||||
| `providers` | `ctx.providers` | `register({id,name,baseUrl,key,models})`,外部服务提供方 |
|
||||
| `canvas` | `ctx.canvas` | 只读画布:`getNodes()` / `listNodeTypes()` / `getSelectedNode()` / `getNodeImage(id)` / `screenToWorld()` |
|
||||
| `canvasWrite` | `ctx.canvas`(合并) | 受控写画布:`createNode()` / `createImageNode()` / `setNodeImage()`。注意**没有 `ctx.canvasWrite`**,仍需同时声明本能力 |
|
||||
|
||||
**硬约束**:
|
||||
- 插件是**可信代码**(无沙箱):可读画布数据、可发网络请求。只合入你信任的代码。
|
||||
- **不得依赖其他插件的加载顺序**(自动发现按文件名排序,彼此独立)。
|
||||
- **不得引用宿主的内部实现**(宿主的守门测试会检查:`src/*.js` 不能引用 `app.js` 定义的全局)——只用 `ctx`。
|
||||
- CSP:页面只放行 `'self'` + `https:` + `http://127.0.0.1:30092` / `http://localhost:30092`。要连别的 http 地址会被拦。
|
||||
未声明的能力在 `ctx` 上是 undefined,调用会抛错。插件 id 重复会被拒绝注册(先注册者生效)。
|
||||
工厂抛异常会被宿主隔离;`dispose()`(以及工厂返回值里的 `dispose`)里清理你自己加的 DOM / 定时器 / 监听器。
|
||||
|
||||
## 目录约定
|
||||
## 桌面环境约束(CSP)
|
||||
|
||||
```
|
||||
template/ # 最小可运行插件(复制它开始;手写单文件)
|
||||
xianyi-cutout/ # 真实插件:鲜艺抠图(A2 运行时插件,已发布到宿主 KV;手写单文件)
|
||||
white-bg-800/ # 真实插件:白底图(移植自 iwb-cutout-extension;已发布到宿主 KV;手写单文件)
|
||||
image-annotate/ # 真实插件:标注 / 修图(编辑器移植自 iwb-plaus;需要构建,见下节)
|
||||
batch-export/ # 真实插件:批量出图(panels 面板 + 串行队列 + 可选抠图 + 双版本 + ZIP + 行内单张下载;手写单文件)
|
||||
scripts/ # validate.mjs(CI 必跑)+ build-plugin.mjs(仅需构建的插件用)
|
||||
宿主的内容安全策略在 `image-workbench-desktop/src-tauri/tauri.conf.json`,要点:
|
||||
|
||||
- `script-src 'self' blob:`:经典脚本 IIFE,禁 `eval` / `new Function` / CDN;blob 注入用于本地开发插件。
|
||||
- `style-src 'self' 'unsafe-inline'`:样式用 JS 注入 `<style>`。
|
||||
- `connect-src` 放行 `self` / `ipc:` / `https:` / `blob:` / `data:` 及本机 `127.0.0.1:30092`、`localhost:30092`(本地抠图服务)。
|
||||
**其它本机端口未放行**(如 ai-chat 用的 Magpie `3425`)——要连需改宿主 CSP 并重新打包客户端。
|
||||
- `img-src` / `font-src` 放行 `data:`、`blob:`,`https:`(字体仅 `data:`)。
|
||||
|
||||
因为 CSP 里 `connect-src` 含 `blob:`/`data:`,在客户端里 `fetch(blob:)` / `fetch(data:)` 是允许的;
|
||||
但测试用的合成宿主可能按更严的策略跑,插件保留本地解码兜底更稳妥。
|
||||
|
||||
## 目录与插件清单
|
||||
|
||||
顶层目录**有 `package.json` 才会被当成插件**(`scripts/validate.mjs` 的发现规则);
|
||||
多插件共用的源码可放顶层 `shared/`,无需改校验器或 CI。
|
||||
|
||||
| 目录 | 插件 | 形态 |
|
||||
|---|---|---|
|
||||
| `template/` | 最小可运行模板(复制它开始,手写单文件) | 模板 |
|
||||
| `xianyi-cutout/` | 鲜艺抠图:调本机服务抠图 → 透明底节点 | 手写单文件 |
|
||||
| `white-bg-800/` | 白底图:等比居中合成白底/透明大图(双版本,≤500KB) | 手写单文件 |
|
||||
| `batch-export/` | 批量出图:面板 + 串行队列 + 抠图 + 合成 + ZIP / 单张下载 | 手写单文件 |
|
||||
| `blank-canvas/` | 空白画布:给空 ref 节点填纯白图 | 手写单文件 |
|
||||
| `image-annotate/` | 标注 / 修图:全屏单张图片编辑器(选区 / 图层 / 裁剪…) | **需构建** |
|
||||
| `image-vectorize/` | 位图转矢量:potrace 单色 / 灰度描摹 → SVG / PNG | **需构建** |
|
||||
| `style-source/` | 风格库:367 风格面板 → 插预览图 / 提示词 / 样式节点 | 手写单文件 |
|
||||
| `ai-chat/` | AI 对话:直连本机 Magpie 网关的浮窗流式对话 | 手写单文件 · 实验/需本机 Magpie+CSP |
|
||||
|
||||
> 桌面仓的同步脚本 `sync-plugins-from-repo.js` 里有一份**上架白名单**(当前为
|
||||
> `batch-export / blank-canvas / image-annotate / image-vectorize / style-source / white-bg-800 / xianyi-cutout`)。
|
||||
> **新增插件要上架市场,必须把 id 加进那份白名单**,并在桌面仓 `plugins/meta.json` 补名称 / 描述 / 图标等展示信息。
|
||||
|
||||
## 快速开始:5 分钟做出第一个插件
|
||||
|
||||
```bash
|
||||
cp -r template my-plugin # 复制模板
|
||||
# 改 my-plugin/package.json 的 name,以及 my-plugin/src/index.js 里的 id / name
|
||||
npm run validate # 校验 manifest 与 package.json 是否一致
|
||||
```
|
||||
|
||||
> 顶层目录**没有 `package.json` 就不会被当成插件**(`scripts/validate.mjs` 的发现规则),
|
||||
> 因此将来两个以上插件共用的源码可以放顶层 `shared/`,不需要改校验器或 CI。
|
||||
把 `my-plugin/src/index.js` 拷到 `<资料目录>/plugins/local/my-plugin/plugin.js`,
|
||||
客户端「设置 → 插件」打开**开发者模式**并重启 —— 右键菜单里就能看到新命令。
|
||||
本地调试免签名、免市场,改完代码重启一次即可重新加载(详见「本地调试」)。
|
||||
|
||||
## 需要构建的插件(复杂插件)
|
||||
## 开发、构建、校验
|
||||
|
||||
编辑器/多文件类插件用 ESM 写,构建成单文件 IIFE 产物:
|
||||
```bash
|
||||
npm install # esbuild 是 devDependency,只有构建时需要
|
||||
|
||||
npm run validate # 契约校验:manifest 与 package.json 一致、entry 语法、无重复 id
|
||||
npm run build -- image-annotate # 需要构建的插件:ESM 源码 → 单文件 IIFE 产物
|
||||
```
|
||||
|
||||
校验脚本是 `scripts/validate.mjs`(只读源码、不联网、无依赖),CI 配置在 `.github/workflows/ci.yml`。
|
||||
**CI 只校验、不构建**:所以 `src/index.js` 产物必须提交进仓,不能只提交源码等 CI 来构建。
|
||||
|
||||
### 手写单文件插件
|
||||
|
||||
`src/index.js` 即最终产物(IIFE),改完直接 `npm run validate`。模板见 `template/`。
|
||||
|
||||
### 需要构建的插件(编辑器 / 多文件类)
|
||||
|
||||
用 ESM 写,esbuild 打成单文件 IIFE:
|
||||
|
||||
```
|
||||
<插件>/
|
||||
plugin/entry.js # 打包入口(import 编辑器 + 胶水,导出工厂到全局)
|
||||
plugin/entry.js # 打包入口
|
||||
plugin/manifest.banner.js # 手写 manifest(单引号,原样放产物最前)
|
||||
plugin/manifest.footer.js # 手写注册 IIFE(原样放产物最后)
|
||||
plugin/editor/…、*.css # 源码;CSS 以 text loader 内联
|
||||
src/index.js # 构建产物(提交进仓,CI 只校验不构建)
|
||||
```
|
||||
|
||||
分三段拼接的原因:esbuild 会把字符串统一改写成双引号,而校验器只认单引号 manifest,
|
||||
且用「文件里第一个 `id` 字面量」判定插件 id,manifest 必须排在 bundle 之前。
|
||||
`version` 只有一处真源:构建时从 `package.json` 注入 banner 的 `__PLUGIN_VERSION__`。
|
||||
|
||||
## 本地调试(开发者模式)
|
||||
|
||||
1. 把单文件产物放到 `<资料目录>/plugins/local/<插件 id>/plugin.js`。
|
||||
2. 客户端「设置 → 插件」打开**开发者模式**(不开则 `plugins/local/` 下的插件不会加载)。
|
||||
3. 重启客户端(插件在启动时加载);改完代码再重启一次即可重新加载。
|
||||
|
||||
开发者模式下的插件**不校验签名**(免 SRI / sha256),仅限本机调试;正式分发走市场。
|
||||
|
||||
各插件 `tools/harness.mjs` 是本地端到端测试(合成宿主 + 真实 Chromium),改完插件先跑它;
|
||||
需要 Playwright(可从桌面仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定)。
|
||||
|
||||
## 发布到市场
|
||||
|
||||
前提:源码已提交,并在桌面仓完成同步与重建市场。步骤:
|
||||
|
||||
```bash
|
||||
npm install # esbuild 是 devDependency,只有构建时需要
|
||||
npm run build -- image-annotate # 含产物自检:首个 id / register / version / 无 eval
|
||||
# 1) 本仓:改版本(package.json 与 src/index.js 的 manifest.version 保持一致)→ 构建 → 校验 → 提交
|
||||
npm run build -- <需构建的插件> # 手写单文件跳过
|
||||
npm run validate
|
||||
|
||||
# 2) 桌面仓:同步源仓产物(内容寻址命名 + SRI),再生成市场
|
||||
cd /Users/qiqi/open/github/image-workbench-desktop
|
||||
node scripts/sync-plugins-from-repo.js # 默认读 ../iwb-plugins-desktop
|
||||
node scripts/gen-market.js
|
||||
|
||||
# 3) 把 market/ 上传到 NAS /vol8/web/iwb-market/(market.maqiart.eu.org)
|
||||
```
|
||||
|
||||
**为什么分三段拼接**:esbuild 会把字符串统一改写成双引号,而校验器只认单引号 manifest;
|
||||
且校验器用「文件里第一个 id 字面量」判定插件 id,manifest 必须排在 bundle 之前。
|
||||
`version` 只有一处真源 —— 构建时用 `package.json` 的 `version` 替换 banner 里的 `__PLUGIN_VERSION__`。
|
||||
- 同步脚本按白名单读取每个 `<id>/src/index.js`,生成 `plugin-<id>.<sha12>.js`(sha256 前 12 位),
|
||||
重建 `plugins/index.json`;内容不变时产物名与清单完全一致(幂等,可用 `git diff` 验证)。
|
||||
- `gen-market.js` 读 `plugins/index.json` + `plugins/meta.json`,写出市场索引,每个条目带 `sha256` 与 `integrity`。
|
||||
- **版本两处一起改**:`package.json` 的 `version` 与 `src/index.js` 里 manifest 的 `version`(`validate` 会校验一致)。
|
||||
- 发布后回读市场索引确认版本与文件哈希已更新,再在客户端市场里刷新、安装验证——不能只看命令退出码。
|
||||
历史上出过「字节传了、清单没换」导致用户仍拿到旧版的事故(见 `style-source/README.md`)。
|
||||
|
||||
每个插件目录含 `src/index.js`(IIFE 产物)与 `package.json`(`version` + `ibwPlugin.entry` 供人读,
|
||||
`version` 用于来源追溯)。合入/发布时把 `src/index.js` 交给对应脚本:路径 A 交给发布器
|
||||
(`.mjs` 需先拷成 `plugin-<id>.js` 再传文件;`.sh` 直接传 `<id> <file>`),路径 B 传 `plugins-sync.sh` 的第三参数(默认 `dist/plugin.js`)。
|
||||
## 排障速查
|
||||
|
||||
## 运行时机制(插件怎么跑 / 为什么发布更新不用宿主)
|
||||
|
||||
**运行位置**:插件与画布/生图**同页、同源、同 JS 上下文**(由 `app.js` 动态插 `<script src="/plugins/<file>">`)。
|
||||
|
||||
- **可信代码,无沙箱**:与核心同权限(可读画布、可发网络)。只合入你信任的代码。
|
||||
- **插件彼此独立**:不得依赖加载顺序;生命周期由 `plugin-host.js` 管(`register` / `activate` / `deactivate` / `dispose`),
|
||||
存储按插件 id **命名空间隔离**、工厂异常被 try/catch **隔离**。
|
||||
- **但依赖宿主契约** `window.IWBPluginHost`(没有它 IIFE 直接 `return`)——**不是**脱离宿主的独立进程/沙箱。
|
||||
|
||||
**发布/更新为何不用宿主**(A2 的设计核心):
|
||||
|
||||
- 运行时**唯一数据源是 KV**:宿主 `functions/plugins/[[path]].js` 读 `env.PLUGINS`(键 `plugins/index.json` + `plugins/<file>`),
|
||||
`app.js` 明说「**更新只需上传到 KV、刷新即生效**」。
|
||||
- 宿主**没有**插件 id 白名单 / 硬编码清单 ⇒ 新增插件 id **不需要改宿主**。
|
||||
- 宿主仓里的 `plugins/index.json` 只是**本地记录**(`dist/` 不含 `plugins/`,function 直读 KV)⇒ 加/改插件**不必**在宿主提交。
|
||||
- `scripts/plugins-publish.{sh,mjs}` 只是**便利脚本**(从宿主 `wrangler.toml` 读 KV namespace id、本地算 SHA-256、`wrangler kv put`),
|
||||
**不改宿主代码、不重编译、不部署宿主**。可直接用裸命令绕过:
|
||||
|
||||
```bash
|
||||
# 只需 KV namespace id(宿主 wrangler.toml 的 [[kv_namespaces]] id)
|
||||
wrangler kv key put --namespace-id <PLUGINS_ID> --remote "plugins/plugin-<id>.js" --path <本仓插件文件>
|
||||
wrangler kv key put --namespace-id <PLUGINS_ID> --remote "plugins/index.json" --path <清单>
|
||||
```
|
||||
|
||||
**仅两个前置/例外**(都不是"改宿主功能"):
|
||||
|
||||
1. **一次性前置**:A2 Function 需先在目标环境**上线一次**。正式站若未部署,`/plugins/index.json` 会走 SPA 兜底、插件不加载;
|
||||
上线之后,插件发布/更新与宿主无关。
|
||||
2. **新能力例外**:插件用到现有 8 项能力之外的新能力时,才需回宿主扩契约(见下节)。
|
||||
|
||||
## 什么时候必须改宿主
|
||||
|
||||
| 情形 | 动主仓? |
|
||||
| 现象 | 常见原因 / 排查方向 |
|
||||
|---|---|
|
||||
| **发布/更新插件**(仅用现有能力,A2 Function 已上线) | **不用**——上传 KV + 刷新即生效(见上节) |
|
||||
| 只用上表能力、纯加文件 | **不用** |
|
||||
| 需要**新的能力/API** | 要——那是一次性契约扩展(宿主侧) |
|
||||
| 需要放宽 CSP / 改构建语义 | 要(安全或架构变更) |
|
||||
| A2 Function 首次上线(正式站) | 要——一次性 `npm run deploy`(之后与插件发布无关) |
|
||||
| 插件完全不加载,状态 `not-registered` | manifest 的 `id` 与产物文件名 `plugin-<id>.js` 的 id 不一致;或 `capabilities` 写错——注意能力名与 ctx key 不同(`nodeTypes` → `ctx.nodes`、`panels` → `ctx.ui`),写错会静默失效 |
|
||||
| 状态 `error`,提示「脚本完整性校验失败(integrity 不符或加载失败)」 | SRI 校验不符或文件 404;重跑同步脚本并回读市场索引,确认清单指向的哈希文件确实存在 |
|
||||
| 状态 `error`,提示「外部插件不可用 / 完整性校验失败(外部插件)」 | 市场条目缺 `src` 或 `integrity`;重跑 `gen-market.js` 重建索引 |
|
||||
| 装了新版本却还是旧行为 | 多半是清单没更新(版本字节传了但索引没换);对照市场索引里的 `sha256` 与客户端实际加载文件算一遍 |
|
||||
| 面板能开,但节点体是无样式裸 DOM / 图片铺满 | CSS 只在面板 `mount()` 里注入了——从存档直接进画布时面板从不 mount。**在脚本执行时就注入 `<style>`**(定义 `ensureStyle()` 并紧跟 CSS 常量调用),关键元素再补行内尺寸兜底 |
|
||||
| 节点里输入框一输入就失焦 | `render()` 里重建了 DOM。幂等同步、不重建;输入框 `pointerdown` 阻止冒泡;`activeElement` 是自己时跳过 value 覆盖 |
|
||||
| 本机服务连不上(如抠图 / Magpie) | 检查 CSP `connect-src`:桌面版只放行本机 `30092`,其它端口(如 `3425`)需改 `tauri.conf.json` 并重新打包客户端 |
|
||||
| 连了多条线却只出一个任务 | 任务身份按 `ownerNodeId`(节点自己)而非 `sourceNodeId`(文本真实来源),多条路径会归约到同一 owner;这是宿主侧语义,排查时别误判为插件丢线 |
|
||||
|
||||
即:**契约是接口**;插件在接口内玩,宿主只是"收文件的"。**发布 ≠ 改宿主**。
|
||||
遇到具体插件的问题,先去对应 `README.md` 的历史版本章节,多数坑都记着来龙去脉。
|
||||
+23
-10
@@ -1,6 +1,6 @@
|
||||
# AI 对话(ai-chat)
|
||||
|
||||
浮窗式 AI 对话插件:直接连你本机的 **[Magpie](https://github.com/yetone/magpie)**(OpenAI 兼容网关,默认 `http://127.0.0.1:3425/v1`),在画布上方开聊。不嵌网页、不走后端代理(Pages Function 跑在边缘、连不到本机 `127.0.0.1`,故插件直连)。
|
||||
浮窗式 AI 对话插件:直接连你本机的 **[Magpie](https://github.com/yetone/magpie)**(OpenAI 兼容网关,默认 `http://127.0.0.1:3425/v1`),在画布上方开聊。不嵌网页、不走后端代理——桌面客户端没有服务端,插件直接连本机网关。
|
||||
|
||||
## 能力
|
||||
|
||||
@@ -16,13 +16,18 @@
|
||||
|
||||
| 项 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| Magpie 地址 | `http://127.0.0.1:3425/v1` | 本机 Magpie 端点。改端口需同步放宽宿主 `_headers` 的 `connect-src`。 |
|
||||
| Magpie 地址 | `http://127.0.0.1:3425/v1` | 本机 Magpie 端点。改端口需同步放宽桌面宿主 `src-tauri/tauri.conf.json` 的 CSP `connect-src`。 |
|
||||
| API Key | `magpie` | Magpie 走 loopback,任意值均可(只认本机)。 |
|
||||
|
||||
## 前置
|
||||
|
||||
1. 本机跑起 Magpie,并配好你想用的 provider(详见 Magpie 文档)。
|
||||
2. 宿主 `_headers` 的 `connect-src` 已放行 `http://127.0.0.1:3425` 与 `http://localhost:3425`(本仓已加)。
|
||||
2. 桌面宿主 CSP 的 `connect-src` 默认**未放行 `3425`**(只放了 `30092` 抠图端口)。
|
||||
要用本插件需先在 `image-workbench-desktop/src-tauri/tauri.conf.json` 的 `connect-src` 里加
|
||||
`http://127.0.0.1:3425 http://localhost:3425`,再重新打包客户端(见根 README「桌面环境约束」)。
|
||||
|
||||
> ⚠️ 因为 CSP 需改宿主并重新打包,本插件当前**不在市场同步白名单里**(见根 README),
|
||||
> 只能以「开发者模式」本机加载使用。
|
||||
|
||||
## 用法
|
||||
|
||||
@@ -39,11 +44,19 @@
|
||||
|
||||
## 发布
|
||||
|
||||
手写单文件(IIFE),`src/index.js` 即产物,无需构建:
|
||||
手写单文件(IIFE),`src/index.js` 即产物,无需构建。本插件因需改宿主 CSP(见「前置」),
|
||||
暂以开发者模式本机加载:把 `src/index.js` 放到 `<资料目录>/plugins/local/ai-chat/plugin.js`,
|
||||
打开客户端开发者模式后重启。若要纳入市场,需先把 id 加进桌面仓同步脚本的白名单、改好 CSP 并重新打包客户端,
|
||||
再走根 README「发布到市场」的链路。
|
||||
|
||||
```bash
|
||||
# 路径 A:运行时发布到 KV(推荐)
|
||||
cp src/index.js /tmp/plugin-ai-chat.js
|
||||
node ../../image-workbench-web/scripts/plugins-publish.mjs /tmp/plugin-ai-chat.js --upload --version ai-chat=1.0.0
|
||||
# 注:实际发布需把全部插件一并传入,保持 index.json 完整(见宿主发布流程)
|
||||
```
|
||||
## 状态:实验性,默认不上市场(2026-11-22 明确)
|
||||
|
||||
本插件**不在** `plugins/index.json` / `market/index.json` 的同步白名单里(见根 README 与 `image-workbench-desktop/scripts/sync-plugins-from-repo.js` 的 `DEV_ONLY_IDS`)。原因:
|
||||
|
||||
1. 依赖**本机 Magpie** 网关(默认 `127.0.0.1:3425`),多数用户没有;
|
||||
2. 需要宿主 CSP `connect-src` 放行 `3425`,必须**改客户端并重新打包**才生效。
|
||||
|
||||
因此它只作为「开发者直装」保留:
|
||||
|
||||
- 目录里已有 `manifest.json`(`main` 指向 `src/index.js`);想本机试用,把整个 `ai-chat/` 放到资料目录 `plugins/ai-chat/`,并在宿主 CSP 里放行 3425 后重启;
|
||||
- 不随客户端发版、不进市场,避免用户装了连不上。
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"id": "ai-chat",
|
||||
"name": "AI 对话",
|
||||
"version": "1.0.0",
|
||||
"apiVersion": 1,
|
||||
"main": "src/index.js",
|
||||
"description": "浮窗直连本机 Magpie(OpenAI 兼容网关)的 AI 对话插件;需本机网关 + 宿主 CSP 放行 3425 端口,默认不上市场。",
|
||||
"author": "official",
|
||||
"icon": "💬",
|
||||
"tags": ["AI", "对话", "实验"],
|
||||
"files": {}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "@iwb-plugin/album",
|
||||
"private": true,
|
||||
"version": "1.1.1",
|
||||
"description": "相册:一个节点装多张本地图(只引用不复制),宫格自适应分页,一图一任务 / 批量两种模式批量生图",
|
||||
"ibwPlugin": {
|
||||
"id": "album",
|
||||
"entry": "src/index.js",
|
||||
"apiVersion": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
// 相册节点(2026-11-26,iwb-plugin: album)
|
||||
//
|
||||
// 一件事:把「多个图片节点」收成一个节点——宫格装 N 张本地图,接提示词/组合做批量生图。
|
||||
//
|
||||
// 三条关键设计(都对宿主有依赖,别在插件里重造):
|
||||
// ① 只引用不复制:item.src = { __file: '/abs/a.png' };宿主生成时才读盘(ctx.images.reference / dataUrl)
|
||||
// ② 任务展开由宿主任务图做:data.outKind='images' + data.items,宿主按 albumMode 展开成 N 个任务
|
||||
// (一图一任务)或分批(批量,每组 ≤12 张);本插件只负责「数据 + 界面」
|
||||
// ③ 分页容量随节点尺寸实时算:拖大 = 一页装更多(装得下就隐藏分页条),缩小 = 自动多页;
|
||||
// 只有 data.onlyPage 打开时才把可见区间写进 data.pageRange 交给宿主过滤
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
if (!global.IWBPluginHost) return
|
||||
|
||||
// 密度档位 = 目标单元格边长(px)。1.1.0 修正:旧值 {S:64, M:48, L:100} 里 M 比 S 还小,
|
||||
// 于是「中格」每页装 30 张(比小格的 20 张还多),档位语义是反的。现在 S < M < L 严格递增。
|
||||
const DENSITY = { S: 64, M: 80, L: 104 }
|
||||
// ⚠ 下面这一组必须与 styles.css 逐个对齐(换了 box-sizing / padding 就会算错容量 ⇒ 最后一行被裁)。
|
||||
// 宿主全局 * { box-sizing: border-box },所以 CSS 里写的 height 已含 padding。
|
||||
const GAP = 4 // .iwb-album-grid 的 gap = --iwb-space-4
|
||||
const PAD_X = 16 // 宫格左右 padding 合计(.iwb-album-grid 左右各 --iwb-space-8)
|
||||
const PAD_Y = 8 // 上下 padding 合计(.iwb-album-grid 2px + 6px)
|
||||
const BAR_H = 26 // 状态栏
|
||||
const TOOLS_H = 25 // 工具条(padding 2+2 + 按钮 21)
|
||||
const PAGER_H = 26 // 分页条 / 一页提示条
|
||||
const HINT_H = 28 // 批量模式提示行(含 margin-bottom 4)
|
||||
const DEFAULT_H = 470 // 注册时声明的默认高度(与 height 字段保持一致)
|
||||
const THUMB_EDGE = 256
|
||||
const THUMB_Q = 0.8
|
||||
const IMG_EXT = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg']
|
||||
|
||||
const STATE = new WeakMap() // host 元素 → 渲染状态(一个容器一个实例)
|
||||
|
||||
// ── 小工具 ──────────────────────────────────────────────
|
||||
function el (tag, attrs, kids) {
|
||||
const node = document.createElement(tag)
|
||||
if (attrs) for (const k in attrs) {
|
||||
const v = attrs[k]
|
||||
if (v === null || v === undefined || v === false) continue
|
||||
if (k === 'className') node.className = v
|
||||
else if (k === 'text') node.textContent = v
|
||||
else if (k === 'style' && typeof v === 'object') Object.assign(node.style, v)
|
||||
else if (k.slice(0, 2) === 'on' && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v)
|
||||
else node.setAttribute(k, v === true ? '' : String(v))
|
||||
}
|
||||
for (const kid of (Array.isArray(kids) ? kids : (kids ? [kids] : []))) {
|
||||
if (kid === null || kid === undefined || kid === false) continue
|
||||
node.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid)
|
||||
}
|
||||
return node
|
||||
}
|
||||
// 可点击元素:宿主在节点体上的 pointerdown 会启动「拖动节点」,单击事件因此被吞。
|
||||
// 所有可点击的非 input/button 元素都必须挡住 pointerdown(与 ui-node-bodies 里 stop 的用法一致)。
|
||||
function onTap (el0, fn) {
|
||||
el0.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
el0.addEventListener('click', (e) => { e.stopPropagation(); fn(e) })
|
||||
return el0
|
||||
}
|
||||
function hash32 (s) {
|
||||
let h = 0x811c9dc5
|
||||
const str = String(s || '')
|
||||
for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0 }
|
||||
return ('00000000' + h.toString(16)).slice(-8)
|
||||
}
|
||||
const extOf = (p) => { const m = /\.([a-z0-9]{1,5})$/i.exec(String(p || '')); return m ? m[1].toLowerCase() : '' }
|
||||
const isImagePath = (p) => IMG_EXT.indexOf(extOf(p)) >= 0
|
||||
const fileRefOf = (src) => (src && typeof src === 'object' && typeof src.__file === 'string') ? src.__file : ''
|
||||
const nameOf = (p) => String(p || '').replace(/^.*[\\/]/, '')
|
||||
const str = (v) => (v == null ? '' : String(v))
|
||||
|
||||
// ── 缩略图(插件私有缓存,几十 KB/张,不碰画布存储)────────────
|
||||
const thumbNameOf = (key) => 't-' + hash32(key) + '.jpg'
|
||||
|
||||
// 缩略图缓存键(1.1.0 修「串味」):旧实现是 `fileRefOf(src) || it.name`,一旦固化(src 变成
|
||||
// {__blob})或从别处导入,路径就没了 ⇒ 键退化成纯文件名 ⇒ 不同目录下的 1.png 共用同一张缩略图。
|
||||
// 现在按引用本身取键:路径 → 路径;blob/cache → 各自 id;dataURL → 内容哈希;只有都没有才退回文件名。
|
||||
function thumbKeyOf (it) {
|
||||
const src = (it && it.src) != null ? it.src : it
|
||||
const path = fileRefOf(src)
|
||||
if (path) return 'f:' + path
|
||||
if (src && typeof src === 'object') {
|
||||
if (typeof src.__blob === 'string' && src.__blob) return 'b:' + src.__blob
|
||||
if (typeof src.__cache === 'string' && src.__cache) return 'c:' + src.__cache
|
||||
}
|
||||
if (typeof src === 'string' && src) {
|
||||
if (src.length > 4096) return 'd:' + hash32(src.slice(0, 2048) + src.slice(-2048) + ':' + src.length)
|
||||
return 'd:' + hash32(src)
|
||||
}
|
||||
const n = (it && (it.name || it.size)) || ''
|
||||
return 'n:' + str(n)
|
||||
}
|
||||
|
||||
function makeThumb (dataUrl) {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
const img = new Image()
|
||||
img.onload = () => {
|
||||
try {
|
||||
const scale = Math.min(1, THUMB_EDGE / Math.max(img.naturalWidth || 1, img.naturalHeight || 1))
|
||||
const w = Math.max(1, Math.round((img.naturalWidth || 1) * scale))
|
||||
const h = Math.max(1, Math.round((img.naturalHeight || 1) * scale))
|
||||
const cv = document.createElement('canvas')
|
||||
cv.width = w; cv.height = h
|
||||
const c2 = cv.getContext('2d')
|
||||
c2.drawImage(img, 0, 0, w, h)
|
||||
resolve(cv.toDataURL('image/jpeg', THUMB_Q))
|
||||
} catch (e) { resolve('') }
|
||||
}
|
||||
img.onerror = () => resolve('')
|
||||
img.src = dataUrl
|
||||
} catch (e) { resolve('') }
|
||||
})
|
||||
}
|
||||
|
||||
// ── 容量:随节点宽高实时算(放大 = 一页装更多)────────────────
|
||||
function capacityOf (width, height, density, hasHint) {
|
||||
const target = DENSITY[density] || DENSITY.S
|
||||
const innerW = Math.max(0, width - 4 - PAD_X)
|
||||
const innerH = Math.max(0, height - 4 - BAR_H - TOOLS_H - PAGER_H - (hasHint ? HINT_H : 0) - PAD_Y)
|
||||
const cols = Math.max(1, Math.floor((innerW + GAP) / (target + GAP)))
|
||||
const cell = Math.floor((innerW - (cols - 1) * GAP) / cols) || target
|
||||
const rows = Math.max(1, Math.floor((innerH + GAP) / (cell + GAP)))
|
||||
return { cols, rows, cell: Math.max(20, cell), capacity: Math.max(1, cols * rows) }
|
||||
}
|
||||
|
||||
function measure (host) {
|
||||
const rect = host.getBoundingClientRect()
|
||||
return { width: Math.round(rect.width || 0), height: Math.round(rect.height || 0) }
|
||||
}
|
||||
|
||||
// ── 数据读写 ────────────────────────────────────────────
|
||||
function itemsOf (node) {
|
||||
const d = (node && node.data) || {}
|
||||
return Array.isArray(d.items) ? d.items : []
|
||||
}
|
||||
function update (props, node, patch, snapshot) {
|
||||
try { if (snapshot && typeof props.onSnapshot === 'function') props.onSnapshot() } catch (e) { /* 撤销快照失败不影响写入 */ }
|
||||
try { props.onUpdate(node.id, patch) } catch (e) { /* 宿主不可写时保持只读 */ }
|
||||
}
|
||||
|
||||
// ── 外壳 ────────────────────────────────────────────────
|
||||
function buildShell (ctx, node, props, host) {
|
||||
const st = {
|
||||
nodeId: node.id,
|
||||
thumbs: new Map(), // key → dataURL(内存缓存)
|
||||
pending: new Map(), // key → Promise(并发去重:格子挂载和预生成会同时要同一张)
|
||||
missing: new Set(), // 失联文件的 key
|
||||
busy: '',
|
||||
checkedMissing: false,
|
||||
sig: '',
|
||||
cap: null, // 最近一次容量计算(拖拽排序换算页码要用)
|
||||
}
|
||||
const bar = el('div', { className: 'iwb-album-bar' })
|
||||
const track = el('span', { className: 'iwb-album-track' }, el('i', null))
|
||||
const modeLabel = el('label', { className: 'iwb-album-toggle' }, track, document.createTextNode('一图一任务'))
|
||||
modeLabel.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
modeLabel.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
// ⚠ 必须读 st.node(每次 sync 更新),不能读 buildShell 捕获的 node ——
|
||||
// 那是**挂载时**的旧数据,连点两次会一直算出同一个 next(实测:永远停在批量)。
|
||||
const cur = st.node || node
|
||||
const d = (cur && cur.data) || {}
|
||||
const next = d.albumMode === 'batch' ? 'per-image' : 'batch'
|
||||
update(st.props || props, cur, { albumMode: next })
|
||||
})
|
||||
const count = el('span', { className: 'iwb-album-count' })
|
||||
// 一键清空(2026-11-26 用户需求):只清本节点持有的 items,删源文件与画布存储一概不碰。
|
||||
// 走 snapshot:true ⇒ ⌘Z 能整批恢复,所以不加二次确认弹窗(多一步点击反而更烦)。
|
||||
const btnClear = el('button', { className: 'iwb-album-btn iwb-album-clear', title: '清空相册(⌘Z 可撤销;不会删除磁盘上的原文件)' }, '清空')
|
||||
bar.appendChild(modeLabel); bar.appendChild(count); bar.appendChild(btnClear)
|
||||
|
||||
const btnAdd = el('button', { className: 'iwb-album-btn', title: '选择本地图片(桌面端只引用,不复制字节)' }, '+ 添加图片')
|
||||
const btnDir = el('button', { className: 'iwb-album-btn', title: '按文件夹批量添加' }, '文件夹')
|
||||
const btnSettle = el('button', { className: 'iwb-album-btn', title: '把引用复制进画布存储(删源文件/分享画布前用)' }, '固化')
|
||||
const seg = el('span', { className: 'iwb-album-seg' })
|
||||
const segs = {}
|
||||
for (const key of ['S', 'M', 'L']) {
|
||||
const s = onTap(el('span', { title: key === 'S' ? '小格(默认)' : (key === 'M' ? '中格' : '大格') }, key), () => update(st.props || props, st.node || node, { density: key }))
|
||||
segs[key] = s; seg.appendChild(s)
|
||||
}
|
||||
const tools = el('div', { className: 'iwb-album-tools' }, [btnAdd, btnDir, btnSettle, seg])
|
||||
|
||||
const hint = el('div', { className: 'iwb-album-hint' })
|
||||
const grid = el('div', { className: 'iwb-album-grid' })
|
||||
const empty = el('div', { className: 'iwb-album-empty' }, [
|
||||
el('div', { className: 'box' }, '+'),
|
||||
el('div', null, '把图片拖到这里,或点「添加图片」选本地文件'),
|
||||
el('div', { style: { fontSize: '10px', opacity: '.85' } }, '支持 PNG / JPG / WebP / GIF / AVIF / SVG'),
|
||||
])
|
||||
const pager = el('div', { className: 'iwb-album-pager' })
|
||||
const onepage = el('div', { className: 'iwb-album-onepage' }, '全部图片一页展示')
|
||||
// 节点内 hover 预览层已于 1.1.1 移除(用户实测:鼠标移到放大镜上时预览层盖住图标,反而点不到)。
|
||||
// 现在只看大图走「点击放大镜 → 宿主全屏预览(props.onPreview)」,点图片外或 Esc 自动退出。
|
||||
|
||||
host.textContent = ''
|
||||
const root = el('div', { className: 'iwb-album' }, [bar, tools, hint, grid, empty, pager, onepage])
|
||||
host.appendChild(root)
|
||||
Object.assign(st, { root, bar, track, count, btnClear, btnAdd, btnDir, btnSettle, segs, grid, empty, pager, onepage, hint })
|
||||
|
||||
// 按钮绑定(用闭包里的当前 node/props:每次 sync 会更新 st.node/st.props)
|
||||
btnAdd.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
btnAdd.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, false) })
|
||||
btnDir.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
btnDir.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, true) })
|
||||
btnSettle.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
btnSettle.addEventListener('click', (e) => { e.stopPropagation(); settleAll(ctx, st) })
|
||||
btnClear.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
btnClear.addEventListener('click', (e) => { e.stopPropagation(); clearAll(ctx, st) })
|
||||
|
||||
// 拖拽入图:桌面端拿不到绝对路径 ⇒ 按「方案 1」复制进画布存储
|
||||
host.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation() })
|
||||
host.addEventListener('drop', (e) => {
|
||||
e.preventDefault(); e.stopPropagation()
|
||||
const files = Array.from((e.dataTransfer && e.dataTransfer.files) || [])
|
||||
if (files.length) importDropped(ctx, st, files)
|
||||
})
|
||||
return st
|
||||
}
|
||||
|
||||
// ── 同步(宿主每次重渲染都会调用;必须可增量)──────────────────
|
||||
function sync (ctx, st, node, props) {
|
||||
st.node = node; st.props = props
|
||||
const d = (node && node.data) || {}
|
||||
const items = itemsOf(node)
|
||||
const density = DENSITY[d.density] ? d.density : 'S'
|
||||
const mode = d.albumMode === 'batch' ? 'batch' : 'per-image'
|
||||
// 尺寸来源:**只认显式 node.h 或变体默认高度**(2026-11-26 修"插入后慢慢变矮")。
|
||||
// ⚠ 绝不能用 props.measuredH / 自身 getBoundingClientRect():插件节点体是内容撑开的,
|
||||
// 我们按它写回高度 ⇒ 卡片变矮 ⇒ 下次量到更矮 ⇒ 一路缩水。
|
||||
// 拖拽调整尺寸时宿主会把新高度写进 node.h,那才是权威值。
|
||||
const measured = measure(st.root)
|
||||
const cardW = Number(node.w) || measured.width || 300
|
||||
const cardH = Number(node.h) || DEFAULT_H
|
||||
const wantH = Math.max(120, Math.round(cardH) - 4) + 'px'
|
||||
if (st.root.style.height !== wantH) st.root.style.height = wantH
|
||||
const cap = capacityOf(cardW, cardH, density, mode === 'batch')
|
||||
st.cap = cap // 拖拽排序换算「本页第 i 格 → 全局第几格」要用(旧代码用格子数,把「+添加」也算进去了)
|
||||
const pages = Math.max(1, Math.ceil(items.length / cap.capacity))
|
||||
const page = Math.max(0, Math.min(pages - 1, Number(d.page) || 0))
|
||||
const from = page * cap.capacity
|
||||
const to = Math.min(items.length, from + cap.capacity)
|
||||
const selected = items.filter((it) => it && it.on !== false).length
|
||||
|
||||
// 一图一任务开关 / 计数 / 密度高亮 / 固化可用性
|
||||
st.track.className = 'iwb-album-track' + (mode === 'per-image' ? ' on' : '')
|
||||
st.count.innerHTML = ''
|
||||
st.count.appendChild(document.createTextNode('已选 '))
|
||||
st.count.appendChild(el('b', null, String(selected)))
|
||||
st.count.appendChild(document.createTextNode('/' + items.length + ' · 每页 ' + cap.capacity))
|
||||
for (const k in st.segs) st.segs[k].className = (density === k ? 'on' : '')
|
||||
const hasFileRef = items.some((it) => fileRefOf(it && it.src))
|
||||
st.btnSettle.style.display = hasFileRef ? '' : 'none'
|
||||
// 「文件夹」只在能做路径引用的宿主里有意义(桌面端)。旧写法 `canReference() || true` 恒真,
|
||||
// 于是在网页版点它永远没反应。网页版仍可用「+ 添加图片」走文件选择器。
|
||||
const canRef = !!(ctx.images && typeof ctx.images.canReference === 'function' && ctx.images.canReference())
|
||||
st.btnDir.style.display = canRef ? '' : 'none'
|
||||
st.btnClear.style.display = items.length ? '' : 'none'
|
||||
if (st.busy) { st.btnAdd.textContent = st.busy } else { st.btnAdd.textContent = '+ 添加图片' }
|
||||
|
||||
// 批量模式提示:N 张 → M 个任务(每组 ≤ 12)
|
||||
if (mode === 'batch' && items.length) {
|
||||
st.hint.style.display = ''
|
||||
st.hint.innerHTML = ''
|
||||
st.hint.appendChild(document.createTextNode('整本一次请求:'))
|
||||
st.hint.appendChild(el('b', null, items.length + ' 张 → ' + Math.ceil(items.length / 12) + ' 个任务'))
|
||||
st.hint.appendChild(document.createTextNode('(每组 ≤ 12 张)'))
|
||||
} else st.hint.style.display = 'none'
|
||||
|
||||
// 分页条 / 一页展示
|
||||
// 空节点不再显示「全部 0 张一页展示」那条灰条(2026-11-26):它压着空态提示,说的还是废话。
|
||||
const showPager = pages > 1
|
||||
const showOne = !showPager && items.length > 0
|
||||
st.pager.style.display = showPager ? '' : 'none'
|
||||
st.onepage.style.display = showOne ? '' : 'none'
|
||||
if (showOne) st.onepage.textContent = '全部 ' + items.length + ' 张一页展示 · 无需翻页'
|
||||
if (showPager) {
|
||||
st.pager.innerHTML = ''
|
||||
const pg = el('span', { className: 'iwb-album-pg' })
|
||||
const prev = onTap(el('span', { title: '上一页' }, '‹'), () => { if (page > 0) update(st.props, st.node, { page: page - 1 }) })
|
||||
const next = onTap(el('span', { title: '下一页' }, '›'), () => { if (page < pages - 1) update(st.props, st.node, { page: page + 1 }) })
|
||||
pg.appendChild(prev); pg.appendChild(el('b', null, (page + 1) + '/' + pages)); pg.appendChild(next)
|
||||
st.pager.appendChild(pg)
|
||||
const only = el('label', { className: 'iwb-album-mini' }, [
|
||||
el('span', { className: 'iwb-album-track' + (d.onlyPage === true ? ' on' : '') }, el('i', null)),
|
||||
document.createTextNode('仅本页参与'),
|
||||
])
|
||||
only.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
only.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
update(st.props, st.node, { onlyPage: !(d.onlyPage === true) })
|
||||
})
|
||||
st.pager.appendChild(only)
|
||||
}
|
||||
|
||||
// 仅本页参与:把可见区间写回 data.pageRange(宿主任务图据此过滤;关闭时清掉)
|
||||
const wantRange = (d.onlyPage === true) ? [from, to] : null
|
||||
const curRange = Array.isArray(d.pageRange) ? d.pageRange : null
|
||||
const rangeChanged = (!!wantRange !== !!curRange) || (wantRange && curRange && (wantRange[0] !== curRange[0] || wantRange[1] !== curRange[1]))
|
||||
if (rangeChanged || (Number(d.page) || 0) !== page) {
|
||||
update(st.props, st.node, { page: page, pageRange: wantRange })
|
||||
}
|
||||
|
||||
// 宫格(签名不变就不重建:避免每帧重排导致闪烁/丢拖拽态)
|
||||
const sig = [node.id, density, page, cap.capacity, mode, items.length, d.onlyPage === true ? 1 : 0,
|
||||
items.map((it) => thumbKeyOf(it) + (it && it.on === false ? ':0' : ':1')).join(','), Array.from(st.missing).join(',')].join('|')
|
||||
if (sig !== st.sig) {
|
||||
st.sig = sig
|
||||
st.grid.innerHTML = ''
|
||||
st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)'
|
||||
if (!items.length) {
|
||||
st.grid.style.display = 'none'; st.empty.style.display = ''
|
||||
} else {
|
||||
st.grid.style.display = ''; st.empty.style.display = 'none'
|
||||
for (let i = from; i < to; i++) st.grid.appendChild(cellOf(ctx, st, items[i], i, mode))
|
||||
if (to - from < cap.capacity) {
|
||||
const add = el('button', { className: 'iwb-album-cell iwb-album-add', title: '添加图片' }, [el('b', null, '+'), el('span', null, '添加')])
|
||||
add.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, st.root, false) })
|
||||
st.grid.appendChild(add)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)'
|
||||
}
|
||||
|
||||
// 失联检测(每个节点一次;文件被移动/删除时给出明确提示)
|
||||
if (!st.checkedMissing && items.some((it) => fileRefOf(it && it.src))) {
|
||||
st.checkedMissing = true
|
||||
checkMissing(ctx, st, items).then((changed) => { if (changed) { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } } })
|
||||
}
|
||||
}
|
||||
|
||||
// ── 单元格 ──────────────────────────────────────────────
|
||||
// 放大镜图标(内联 SVG,CSP 禁外部资源):圆 + 手柄,10px 下仍看得清
|
||||
function zoomIcon () {
|
||||
const NS = 'http://www.w3.org/2000/svg'
|
||||
const mk = (tag, attrs) => {
|
||||
const n = document.createElementNS(NS, tag)
|
||||
for (const k in attrs) n.setAttribute(k, attrs[k])
|
||||
return n
|
||||
}
|
||||
const svg = mk('svg', { viewBox: '0 0 24 24', 'aria-hidden': 'true' })
|
||||
svg.appendChild(mk('circle', { cx: 10, cy: 10, r: 7, fill: 'none', stroke: 'currentColor', 'stroke-width': 2.4 }))
|
||||
svg.appendChild(mk('path', { d: 'M15.2 15.2 21 21', fill: 'none', stroke: 'currentColor', 'stroke-width': 2.4, 'stroke-linecap': 'round' }))
|
||||
return svg
|
||||
}
|
||||
function cellOf (ctx, st, it, index, mode) {
|
||||
const src = it && it.src
|
||||
const path = fileRefOf(src)
|
||||
const key = thumbKeyOf(it)
|
||||
const on = !(it && it.on === false)
|
||||
const missing = path && st.missing.has(path)
|
||||
const btn = el('button', {
|
||||
className: 'iwb-album-cell' + (on ? ' sel' : ' off') + (missing ? ' missing' : ''),
|
||||
title: (it && it.name ? it.name : ('图 ' + (index + 1))) + (missing ? '(文件已不在原位置:点一下重新定位)' : ''),
|
||||
})
|
||||
const img = el('img', { alt: '', draggable: 'false' })
|
||||
const cached = st.thumbs.get(key)
|
||||
if (cached) img.src = cached
|
||||
// 不设 img.src = '':空字符串会向页面 URL 发一次请求(控制台 ERR_UNKNOWN_URL_SCHEME)。
|
||||
// 不设 src 属性时 <img> 什么都不做,缩略图到了再赋上即可。
|
||||
else loadThumb(ctx, st, it, key).then((url) => { if (url && img.isConnected !== false) img.src = url })
|
||||
btn.appendChild(img)
|
||||
btn.appendChild(el('span', { className: 'iwb-album-idx' }, String(index + 1)))
|
||||
// 批次角标(右上角那个「1」)已删除:顶栏「N 张 → M 个任务」已经说清楚,角标是重复信息,
|
||||
// 还会和删除按钮抢同一个角。位置让给了 ×。
|
||||
const del = el('span', { className: 'iwb-album-del', title: '移除(不删除磁盘上的原文件)' }, '×')
|
||||
del.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
del.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
const items = itemsOf(st.node).slice()
|
||||
items.splice(index, 1)
|
||||
// 删除后留在当前页(旧实现硬编码 page:0,第 2 页删一张直接跳回第 1 页)。
|
||||
// 只做「页数变少时往回收」,正常情况 page 不动。
|
||||
const capNow = st.cap || { capacity: 20 }
|
||||
const pagesNow = Math.max(1, Math.ceil(items.length / capNow.capacity))
|
||||
const pageNow = Math.max(0, Number((st.node.data || {}).page) || 0)
|
||||
update(st.props, st.node, { items: items, page: Math.min(pageNow, pagesNow - 1) }, true)
|
||||
})
|
||||
btn.appendChild(del)
|
||||
// 放大镜(右下角):点击 → 宿主全屏预览。1.1.1 去掉了 hover 预览(会盖住放大镜导致点不到,
|
||||
// 用户实测),只留「点一下看大图」这一条路径:宿主预览点图片外的空白或按 Esc 自动退出。
|
||||
const zoom = el('span', { className: 'iwb-album-zoom', title: '查看大图(点击空白处或按 Esc 关闭)' }, zoomIcon())
|
||||
zoom.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
zoom.addEventListener('click', (e) => { e.stopPropagation(); openFull(ctx, st, it) })
|
||||
btn.appendChild(zoom)
|
||||
btn.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
if (missing) { relocate(ctx, st, index); return }
|
||||
const items = itemsOf(st.node).slice()
|
||||
if (!items[index]) return
|
||||
items[index] = Object.assign({}, items[index], { on: !on })
|
||||
update(st.props, st.node, { items })
|
||||
})
|
||||
// 拖拽排序
|
||||
btn.addEventListener('pointerdown', (e) => {
|
||||
if (e.button !== 0) return
|
||||
const startX = e.clientX, startY = e.clientY
|
||||
let moved = false
|
||||
const target = { index: index }
|
||||
const onMove = (ev) => {
|
||||
const dx = ev.clientX - startX, dy = ev.clientY - startY
|
||||
if (!moved && Math.abs(dx) + Math.abs(dy) < 5) return
|
||||
moved = true
|
||||
btn.classList.add('dragging')
|
||||
const cells = Array.from(st.grid.querySelectorAll('.iwb-album-cell'))
|
||||
let hit = cells.length - 1
|
||||
for (let i = 0; i < cells.length; i++) {
|
||||
const r = cells[i].getBoundingClientRect()
|
||||
if (ev.clientX < r.left + r.width / 2 + (r.width * 0.1) && ev.clientY < r.bottom && ev.clientX > r.left - r.width) { hit = i; break }
|
||||
}
|
||||
cells.forEach((c, i) => c.classList.toggle('dropbefore', i === hit))
|
||||
target.index = hit
|
||||
}
|
||||
const onUp = () => {
|
||||
document.removeEventListener('pointermove', onMove)
|
||||
document.removeEventListener('pointerup', onUp)
|
||||
btn.classList.remove('dragging')
|
||||
Array.from(st.grid.querySelectorAll('.dropbefore')).forEach((c) => c.classList.remove('dropbefore'))
|
||||
if (!moved) return
|
||||
const items = itemsOf(st.node).slice()
|
||||
// 1.1.0 修跨页错位:本页起点 = page × **每页容量**(旧代码乘的是「本页格子数」,而格子数里
|
||||
// 还含末尾那个「+添加」格 ⇒ 第 2 页永远算少一格,把 21 号拖到第 2 位会插到全局第 13 位)。
|
||||
const capNow = st.cap || { capacity: 20 }
|
||||
const pageNow = Math.max(0, Number((st.node.data || {}).page) || 0)
|
||||
const pageStart = pageNow * capNow.capacity
|
||||
const realCount = Math.min(capNow.capacity, Math.max(0, items.length - pageStart))
|
||||
const srcIndex = index
|
||||
let dest = pageStart + Math.min(target.index, realCount)
|
||||
if (dest === srcIndex || dest < 0) return
|
||||
const [movedItem] = items.splice(srcIndex, 1)
|
||||
if (dest > srcIndex) dest -= 1
|
||||
items.splice(Math.max(0, Math.min(items.length, dest)), 0, movedItem)
|
||||
update(st.props, st.node, { items: items }, true)
|
||||
}
|
||||
document.addEventListener('pointermove', onMove)
|
||||
document.addEventListener('pointerup', onUp)
|
||||
})
|
||||
return btn
|
||||
}
|
||||
|
||||
// ── 缩略图取用:内存 → 插件文件 → 现做 ───────────────────
|
||||
// 并发去重(1.1.0):格子一挂载就各自要缩略图,而 addPaths 又顺序预热一遍 ⇒ 同一张图会被读两次盘。
|
||||
// 用 pending 表把同 key 的请求合成一个 Promise(否则导入 30 张会解 60 次原图,内存直接翻倍)。
|
||||
async function loadThumb (ctx, st, it, key) {
|
||||
if (st.thumbs.has(key)) return st.thumbs.get(key)
|
||||
const flight = st.pending && st.pending.get(key)
|
||||
if (flight) return flight
|
||||
const p = loadThumbInner(ctx, st, it, key).finally(() => { if (st.pending) st.pending.delete(key) })
|
||||
if (st.pending) st.pending.set(key, p)
|
||||
return p
|
||||
}
|
||||
async function loadThumbInner (ctx, st, it, key) {
|
||||
if (st.thumbs.has(key)) return st.thumbs.get(key)
|
||||
const name = thumbNameOf(key)
|
||||
try {
|
||||
if (ctx.files) {
|
||||
const got = await ctx.files.get(name)
|
||||
if (got && got.ok && got.url) { st.thumbs.set(key, got.url); return got.url }
|
||||
}
|
||||
} catch (e) { /* 没缓存就现做 */ }
|
||||
let dataUrl = ''
|
||||
const src = it && it.src
|
||||
try {
|
||||
if (fileRefOf(src)) dataUrl = await ctx.images.dataUrl(src)
|
||||
else if (typeof src === 'string') dataUrl = src
|
||||
else dataUrl = await ctx.images.dataUrl(src)
|
||||
} catch (e) { dataUrl = '' }
|
||||
if (!dataUrl) return ''
|
||||
const thumb = await makeThumb(dataUrl)
|
||||
if (!thumb) return ''
|
||||
st.thumbs.set(key, thumb)
|
||||
// 内存里已经有一张就够本会话用了;写盘失败(配额满)不影响显示
|
||||
try { if (ctx.files) await ctx.files.put(name, thumb) } catch (e) { /* ignore */ }
|
||||
return thumb
|
||||
}
|
||||
|
||||
// ── 看大图:只走宿主全屏预览(1.1.1 定了唯一交互)────────────
|
||||
// 历史:1.1.0 曾做「hover 放大镜 → 节点框内浮大图(pointer-events:none)+ 点击全屏」两套。
|
||||
// 实测否决:hover 一进就把整块节点压暗(预览层 z-index 9),放大镜本身被盖在下面 ⇒
|
||||
// 用户看到的是「滑过去就不能点了」。现在删掉 A,只保留 B:
|
||||
// 点放大镜 → props.onPreview 打开宿主预览层(铺满窗口);
|
||||
// 点图片外的空白 / 按 Esc → 宿主自己 onClose(见 src/ui-canvas-view.js 的 ImagePreview)。
|
||||
// 代价是「看一眼」也要点两下,但少一层状态,点到哪就是哪,不会再互相打架。
|
||||
function openFull (ctx, st, it) {
|
||||
const props = st.props || {}
|
||||
if (typeof props.onPreview !== 'function') return
|
||||
const fallback = st.thumbs.get(thumbKeyOf(it)) || ''
|
||||
const run = (url) => { try { props.onPreview(url || fallback) } catch (e) { /* ignore */ } }
|
||||
if (!ctx.images || typeof ctx.images.dataUrl !== 'function') { run(fallback); return }
|
||||
try {
|
||||
// 先给缩略图/原图都行,宿主预览层会再按需解析;读盘失败退回缩略图
|
||||
Promise.resolve(ctx.images.dataUrl(it && it.src)).then((u) => run(u)).catch(() => run(''))
|
||||
} catch (e) { run(fallback) }
|
||||
}
|
||||
|
||||
// ── 一键清空 ────────────────────────────────────────────
|
||||
function clearAll (ctx, st) {
|
||||
const items = itemsOf(st.node)
|
||||
if (!items.length) return
|
||||
st.thumbs.clear(); st.pending.clear(); st.missing.clear()
|
||||
st.checkedMissing = false // 清空后再导入要重新做一次失联检测
|
||||
update(st.props, st.node, { items: [], page: 0, pageRange: null }, true)
|
||||
st.sig = ''
|
||||
sync(ctx, st, st.node, st.props)
|
||||
}
|
||||
|
||||
// ── 导入:选择器 / 文件夹 / 拖入 / 固化 / 重新定位 ──────────
|
||||
async function pickFiles (ctx, st, host, directory) {
|
||||
if (st.busy) return
|
||||
const items = itemsOf(st.node).slice()
|
||||
// 桌面端:系统选择器给绝对路径 ⇒ 只引用(不复制字节)
|
||||
if (ctx.images && ctx.images.canReference()) {
|
||||
st.busy = '选择中…'; st.sig = ''; sync(ctx, st, st.node, st.props)
|
||||
try {
|
||||
const picked = await ctx.images.pick({ multiple: true, directory: !!directory })
|
||||
st.busy = ''
|
||||
if (!picked.length) { st.sig = ''; sync(ctx, st, st.node, st.props); return }
|
||||
// 目录要展开成图片文件:pick 返回目录路径本身不是图片,之前直接过滤 ⇒ 「文件夹」点了没反应
|
||||
let paths = []
|
||||
if (directory) {
|
||||
for (const dir of picked) {
|
||||
try { const got = await ctx.images.listImages(dir); for (const f of (got || [])) paths.push(f) } catch (e) { /* 单个目录失败不阻断 */ }
|
||||
}
|
||||
} else paths = picked.slice()
|
||||
if (!paths.length) { st.sig = ''; sync(ctx, st, st.node, st.props); return }
|
||||
await addPaths(ctx, st, paths)
|
||||
} catch (e) { st.busy = ''; st.sig = ''; sync(ctx, st, st.node, st.props) }
|
||||
return
|
||||
}
|
||||
// 网页版:没有路径 ⇒ 退回文件选择 + 复制进画布存储
|
||||
const input = document.createElement('input')
|
||||
input.type = 'file'; input.accept = 'image/*'; input.multiple = true
|
||||
input.style.display = 'none'
|
||||
document.body.appendChild(input)
|
||||
input.addEventListener('change', () => {
|
||||
const files = Array.from(input.files || [])
|
||||
document.body.removeChild(input)
|
||||
if (files.length) importDropped(ctx, st, files)
|
||||
})
|
||||
input.click()
|
||||
}
|
||||
|
||||
async function addPaths (ctx, st, paths) {
|
||||
const list = paths.filter(isImagePath)
|
||||
const items = itemsOf(st.node).slice()
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
st.busy = '导入 ' + (i + 1) + '/' + list.length; st.sig = ''; sync(ctx, st, st.node, st.props)
|
||||
const ref = await ctx.images.reference(list[i])
|
||||
if (!ref || !ref.ok) continue
|
||||
items.push({ src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
|
||||
}
|
||||
st.busy = ''
|
||||
st.checkedMissing = false // 新图要重新做一次失联检测(否则清空后再导入,检测永远不再跑)
|
||||
update(st.props, st.node, { items }, true)
|
||||
st.sig = ''
|
||||
sync(ctx, st, st.node, st.props)
|
||||
// 顺序预生成缩略图(避免一次读几十张原图造成内存尖峰)。
|
||||
// 1.1.0:进度写进「+ 添加图片」按钮(旧实现 busy 在这里已经清空 ⇒ 导入 500 张时界面像卡死);
|
||||
// 只改按钮文字、不重置 sig ⇒ 不触发整块宫格重建(重建 500 次比读盘本身还慢)。
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const it = items[i]
|
||||
const key = thumbKeyOf(it)
|
||||
if (!key || st.thumbs.has(key)) continue
|
||||
st.busy = '缩略图 ' + (i + 1) + '/' + items.length
|
||||
st.btnAdd.textContent = st.busy
|
||||
await loadThumb(ctx, st, it, key)
|
||||
}
|
||||
st.busy = ''
|
||||
st.btnAdd.textContent = '+ 添加图片'
|
||||
st.sig = ''
|
||||
sync(ctx, st, st.node, st.props)
|
||||
}
|
||||
|
||||
async function importDropped (ctx, st, files) {
|
||||
const items = itemsOf(st.node).slice()
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const f = files[i]
|
||||
if (!f || !/^image\//i.test(f.type || '')) continue
|
||||
st.busy = '复制 ' + (i + 1) + '/' + files.length; st.sig = ''; sync(ctx, st, st.node, st.props)
|
||||
const dataUrl = await new Promise((resolve) => {
|
||||
try { const r = new FileReader(); r.onload = () => resolve(String(r.result || '')); r.onerror = () => resolve(''); r.readAsDataURL(f) } catch (e) { resolve('') }
|
||||
})
|
||||
if (!dataUrl) continue
|
||||
let res = null
|
||||
try { res = await ctx.images.importDataUrl(dataUrl, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) }) } catch (e) { res = null }
|
||||
if (!res || !res.ok) continue
|
||||
const src = res.ref || res.data
|
||||
if (!src) continue
|
||||
const name = f.name || ('图 ' + (items.length + 1))
|
||||
items.push({ src, name: name, size: f.size || 0, on: true })
|
||||
const thumb = await makeThumb(dataUrl)
|
||||
// 键必须和 cellOf / loadThumb 完全一致(thumbKeyOf),否则写进缓存也命中不到
|
||||
if (thumb) {
|
||||
const key = thumbKeyOf(items[items.length - 1])
|
||||
st.thumbs.set(key, thumb)
|
||||
try { if (ctx.files) await ctx.files.put(thumbNameOf(key), thumb) } catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
st.busy = ''
|
||||
st.checkedMissing = false
|
||||
update(st.props, st.node, { items }, true)
|
||||
st.sig = ''
|
||||
sync(ctx, st, st.node, st.props)
|
||||
}
|
||||
|
||||
// 固化:把 __file 引用换成宿主存储引用(删源文件/分享画布前用)
|
||||
async function settleAll (ctx, st) {
|
||||
const items = itemsOf(st.node).slice()
|
||||
let done = 0
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const it = items[i]
|
||||
const path = fileRefOf(it && it.src)
|
||||
if (!path) continue
|
||||
st.busy = '固化 ' + (++done) + '…'; st.sig = ''; sync(ctx, st, st.node, st.props)
|
||||
try {
|
||||
const res = await ctx.images.importPath(path, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) })
|
||||
if (res && res.ok && (res.ref || res.data)) items[i] = Object.assign({}, it, { src: res.ref || res.data })
|
||||
} catch (e) { /* 单张失败不打断整批 */ }
|
||||
}
|
||||
st.busy = ''
|
||||
update(st.props, st.node, { items }, true)
|
||||
st.sig = ''
|
||||
sync(ctx, st, st.node, st.props)
|
||||
}
|
||||
|
||||
async function checkMissing (ctx, st, items) {
|
||||
let changed = false
|
||||
for (const it of items) {
|
||||
const path = fileRefOf(it && it.src)
|
||||
if (!path) continue
|
||||
try {
|
||||
const r = await ctx.images.stat(path)
|
||||
const missing = !(r && r.ok && r.exists)
|
||||
if (missing && !st.missing.has(path)) { st.missing.add(path); changed = true }
|
||||
if (!missing && st.missing.has(path)) { st.missing.delete(path); changed = true }
|
||||
} catch (e) { /* 检测失败按存在处理 */ }
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// 失联重定位:点失联格 → 选一张同名/任意图片替换
|
||||
async function relocate (ctx, st, index) {
|
||||
if (!ctx.images || !ctx.images.canReference()) return
|
||||
const items = itemsOf(st.node).slice()
|
||||
const cur = items[index]
|
||||
if (!cur) return
|
||||
const paths = await ctx.images.pick({ multiple: false })
|
||||
if (!paths || !paths.length) return
|
||||
const ref = await ctx.images.reference(paths[0])
|
||||
if (!ref || !ref.ok) return
|
||||
const oldPath = fileRefOf(cur.src)
|
||||
st.missing.delete(oldPath)
|
||||
items[index] = Object.assign({}, cur, { src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime })
|
||||
update(st.props, st.node, { items }, true)
|
||||
st.sig = ''
|
||||
sync(ctx, st, st.node, st.props)
|
||||
loadThumb(ctx, st, items[index], thumbKeyOf(items[index])).then(() => { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } })
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ── 注册 ────────────────────────────────────────────────
|
||||
global.IWBPluginHost.register({
|
||||
id: 'album',
|
||||
name: '相册',
|
||||
version: '1.1.1',
|
||||
apiVersion: 1,
|
||||
capabilities: ['nodeTypes', 'images', 'files'],
|
||||
settings: {
|
||||
keepOriginal: { type: 'boolean', label: '默认保留原图(不压缩)', desc: '开启后导入不进 1600 长边压缩,分辨率不损失(占用更高)。节点内可单独改。', default: true },
|
||||
},
|
||||
}, function (ctx) {
|
||||
ctx.nodes.register({
|
||||
id: 'album',
|
||||
title: '相册',
|
||||
icon: 'puzzle',
|
||||
width: 300,
|
||||
height: 470,
|
||||
ports: { in: true, out: true },
|
||||
defaults: { outKind: 'images', items: [], albumMode: 'per-image', density: 'S', page: 0, onlyPage: false, keepOriginal: ctx.settings.get('keepOriginal') !== false },
|
||||
render: function (node, props, host) {
|
||||
// 自愈(2026-11-26):旧版本/兜底路径建出来的节点可能没有 outKind,
|
||||
// 那样连线规则会把相册当普通插件节点(只能连中继)。这里补写一次默认值。
|
||||
try {
|
||||
const d0 = node && node.data
|
||||
if (d0 && d0.outKind !== 'images') {
|
||||
props.onUpdate(node.id, { outKind: 'images', items: Array.isArray(d0.items) ? d0.items : [] })
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
let st = STATE.get(host)
|
||||
if (!st || st.nodeId !== node.id) { st = buildShell(ctx, node, props, host); STATE.set(host, st) }
|
||||
try { sync(ctx, st, node, props) } catch (e) {
|
||||
// 渲染失败降级成一行可读文本(绝不让整块画布白屏)
|
||||
try { host.textContent = ''; const tip = document.createElement('div'); tip.className = 'iwb-hint'; tip.textContent = '相册渲染失败:' + String((e && e.message) || e); host.appendChild(tip) } catch (e2) { /* ignore */ }
|
||||
}
|
||||
},
|
||||
})
|
||||
return {}
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -0,0 +1,65 @@
|
||||
/* 相册节点体(2026-11-26)
|
||||
* 宿主只给一块空容器(.iwb-plugin-node-body),所有排版由这里决定。
|
||||
* 尺寸全部用像素而不是 rem:节点宽度是可拖拽的(264~600),rem 会跟着宿主字号漂移。
|
||||
*/
|
||||
.iwb-album { position: relative; display: flex; flex-direction: column; height: 100%; overflow: hidden; font-size: 11px; color: var(--iwb-node-text); }
|
||||
.iwb-album-bar, .iwb-album-tools, .iwb-album-pager, .iwb-album-onepage {
|
||||
display: flex; align-items: center; gap: var(--iwb-space-6); padding: var(--iwb-space-4) var(--iwb-space-8); flex: 0 0 auto;
|
||||
}
|
||||
.iwb-album-bar { border-bottom: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; }
|
||||
.iwb-album-tools { padding-top: var(--iwb-space-2); padding-bottom: var(--iwb-space-2); }
|
||||
.iwb-album-toggle { display: inline-flex; align-items: center; gap: var(--iwb-space-4); font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); white-space: nowrap; cursor: pointer; }
|
||||
.iwb-album-track { width: 22px; height: 12px; border-radius: 999px; background: var(--iwb-border); position: relative; flex: 0 0 auto; transition: background .15s; }
|
||||
.iwb-album-track i { position: absolute; top: 1.5px; left: 1.5px; width: 9px; height: 9px; border-radius: 50%; background: var(--iwb-panel); transition: left .15s; }
|
||||
.iwb-album-track.on { background: var(--iwb-brand); }
|
||||
.iwb-album-track.on i { left: 11.5px; }
|
||||
.iwb-album-count { margin-left: auto; font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.iwb-album-count b { color: var(--iwb-node-text); font-weight: 600; }
|
||||
.iwb-album-btn { height: 21px; padding: 0 var(--iwb-space-8); border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-chip); background: var(--iwb-panel); color: var(--iwb-node-text2); font-size: var(--iwb-font-2xs); display: inline-flex; align-items: center; gap: var(--iwb-space-4); cursor: pointer; white-space: nowrap; }
|
||||
.iwb-album-btn:hover { border-color: var(--iwb-brand); color: var(--iwb-node-text); }
|
||||
.iwb-album-btn.on { border-color: var(--iwb-brand); color: var(--iwb-node-text); }
|
||||
/* 清空:常驻在顶栏最右,只有相册里有图时才出现。hover 转红是为了和「添加」一类中性操作区分开。 */
|
||||
.iwb-album-clear { flex: 0 0 auto; padding: 0 var(--iwb-space-6); }
|
||||
.iwb-album-clear:hover { border-color: #c0392b; color: #c0392b; }
|
||||
.iwb-album-seg { margin-left: auto; display: inline-flex; border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-chip); overflow: hidden; }
|
||||
.iwb-album-seg span { width: 21px; height: 21px; display: inline-flex; align-items: center; justify-content: center; font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); background: var(--iwb-panel); cursor: pointer; }
|
||||
.iwb-album-seg span.on { background: var(--iwb-brand); color: var(--iwb-on-brand); }
|
||||
.iwb-album-grid { display: grid; gap: var(--iwb-space-4); padding: var(--iwb-space-2) var(--iwb-space-8) var(--iwb-space-6); overflow: hidden; align-content: start; flex: 1 1 auto; min-height: 0; }
|
||||
/* 格子固定正方形(2026-11-26):此前高度由图片比例决定 —— 4 张 16:9 宽图会变成 22px 细条、
|
||||
竖图撑到 167px,和 capacityOf() 按方形算的容量是两套账(最后一行常被裁一半)。
|
||||
aspect-ratio 让每一格高 = 宽,容量因此可精确预测,宫格也终于整齐。
|
||||
padding:0 必须显式写:<button> 的 UA 默认内边距会把图顶出边框。 */
|
||||
.iwb-album-cell { position: relative; aspect-ratio: 1 / 1; padding: 0; border-radius: var(--iwb-radius-chip); overflow: hidden; background: color-mix(in srgb, var(--iwb-border) 55%, transparent); border: 1px solid var(--iwb-border); cursor: grab; }
|
||||
.iwb-album-cell img { width: 100%; height: 100%; object-fit: cover; display: block; -webkit-user-drag: none; }
|
||||
.iwb-album-cell.off img { opacity: .38; }
|
||||
/* 选中线 2px → 1px(用户:太粗)。1px 在浅底上仍分得清「选中」与「描边」。 */
|
||||
.iwb-album-cell.sel { outline: 1px solid var(--iwb-brand); outline-offset: -1px; }
|
||||
.iwb-album-cell.missing { outline: 1px dashed #c0392b; outline-offset: -1px; }
|
||||
.iwb-album-cell.missing::after { content: '失联'; position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: var(--iwb-font-2xs); color: #c0392b; background: rgba(255,255,255,.72); }
|
||||
.iwb-album-cell.dragging { opacity: .45; }
|
||||
.iwb-album-cell.dropbefore { box-shadow: -3px 0 0 0 var(--iwb-brand); }
|
||||
.iwb-album-idx { position: absolute; left: var(--iwb-space-2); top: var(--iwb-space-2); min-width: 14px; height: 14px; padding: 0 var(--iwb-space-4); border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-size: var(--iwb-font-2xs); display: flex; align-items: center; justify-content: center; }
|
||||
/* 批次角标已移除(2026-11-26):顶栏「N 张 → M 个任务」已经说清楚,每格右上角再挂个「1」是重复信息。
|
||||
位置让给删除按钮:右下角要留给放大镜。 */
|
||||
.iwb-album-del { position: absolute; right: var(--iwb-space-2); top: var(--iwb-space-2); width: 15px; height: 15px; border-radius: 50%; background: var(--iwb-panel); color: var(--iwb-node-text2); font-size: 11px; line-height: 1; display: flex; align-items: center; justify-content: center; opacity: 0; cursor: pointer; }
|
||||
.iwb-album-cell:hover .iwb-album-del { opacity: 1; }
|
||||
/* 放大镜:右下角,hover 才出现(静息态不抢视觉,和 × 一致)。
|
||||
17px 圆 / 12px 图标:再小镜片就缩成一团白点。
|
||||
z-index 高于图与角标:1.1.0 时它被节点内预览层(z-index 9)盖住 ⇒ 用户反馈「滑过去就点不到」,
|
||||
那层已在 1.1.1 删除;这里仍显式抬一层,避免以后再加浮层时重犯。 */
|
||||
.iwb-album-zoom { position: absolute; right: var(--iwb-space-2); bottom: var(--iwb-space-2); z-index: 3; width: 17px; height: 17px; border-radius: 50%; background: var(--iwb-panel); color: var(--iwb-node-text2); display: flex; align-items: center; justify-content: center; opacity: 0; cursor: zoom-in; transition: opacity .12s; }
|
||||
.iwb-album-cell:hover .iwb-album-zoom, .iwb-album-cell:focus-within .iwb-album-zoom { opacity: 1; }
|
||||
.iwb-album-zoom:hover { color: var(--iwb-brand); }
|
||||
.iwb-album-zoom svg { width: 12px; height: 12px; display: block; }
|
||||
.iwb-album-add { border: 1px dashed var(--iwb-border); background: transparent; color: var(--iwb-node-text2); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--iwb-space-2); font-size: var(--iwb-font-2xs); border-radius: var(--iwb-radius-chip); cursor: pointer; }
|
||||
.iwb-album-add b { font-size: 15px; line-height: 1; font-weight: 600; }
|
||||
.iwb-album-pager { border-top: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; }
|
||||
.iwb-album-onepage { border-top: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; color: var(--iwb-node-text2); font-size: var(--iwb-font-2xs); }
|
||||
.iwb-album-pg { display: inline-flex; align-items: center; border: 1px solid var(--iwb-border); border-radius: var(--iwb-radius-chip); background: var(--iwb-panel); }
|
||||
.iwb-album-pg span { width: 17px; height: 17px; display: flex; align-items: center; justify-content: center; font-size: var(--iwb-font-2xs); cursor: pointer; color: var(--iwb-node-text2); }
|
||||
.iwb-album-pg b { font-weight: 600; color: var(--iwb-node-text); padding: 0 2px; font-size: var(--iwb-font-2xs); }
|
||||
.iwb-album-mini { display: inline-flex; align-items: center; gap: var(--iwb-space-4); margin-left: auto; font-size: var(--iwb-font-2xs); color: var(--iwb-node-text2); white-space: nowrap; }
|
||||
.iwb-album-hint { margin: 0 8px 4px; padding: 4px 6px; border-radius: var(--iwb-radius-chip); background: rgba(107,114,128,.10); border: 1px solid rgba(107,114,128,.22); color: var(--iwb-node-text2); font-size: var(--iwb-font-2xs); line-height: 1.45; }
|
||||
.iwb-album-hint b { color: var(--iwb-node-text); }
|
||||
.iwb-album-empty { flex: 1 1 auto; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--iwb-space-6); color: var(--iwb-node-text2); font-size: 11px; text-align: center; padding: 0 var(--iwb-space-12); }
|
||||
.iwb-album-empty .box { width: 66px; height: 50px; border: 1.5px dashed var(--iwb-border); border-radius: var(--iwb-radius-chip); display: flex; align-items: center; justify-content: center; font-size: var(--iwb-font-xl); color: var(--iwb-node-text2); }
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env node
|
||||
/* album 插件自测(v1.1.0,2026-11-26)
|
||||
*
|
||||
* 为什么要有它:这个插件此前**零自动化测试**(宿主侧 tests/album-task-graph-test.js 只覆盖任务展开)。
|
||||
* 而 1.1.0 动的是「宫格尺寸 = 分页容量」这条最脆的链:capacityOf() 里的常量必须和 styles.css 逐个对齐,
|
||||
* 错 1px 就会「最后一行被裁一半」,而那种错误肉眼要盯很久才发现。这里把它变成断言。
|
||||
*
|
||||
* 两部分:
|
||||
* 一、静态断言:源码 / 样式里的关键实现必须还在(防回归,不依赖浏览器)
|
||||
* 二、算术断言:把常量段 + capacityOf / thumbKeyOf 从 IIFE 里抽出来,在 vm 里真跑
|
||||
*
|
||||
* 浏览器渲染验证(方形格子、裁切、点击放大)不在这里 —— 那需要 playwright,
|
||||
* 跨仓依赖不适合当门禁。跑法见 README「验证」一节。
|
||||
*/
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import vm from 'node:vm'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = path.resolve(HERE, '..')
|
||||
const src = fs.readFileSync(path.join(ROOT, 'src/index.js'), 'utf8')
|
||||
const css = fs.readFileSync(path.join(ROOT, 'styles.css'), 'utf8')
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
|
||||
|
||||
let failed = 0
|
||||
const ok = (name, cond, extra) => {
|
||||
if (!cond) failed++
|
||||
console.log((cond ? '✓ ' : '✗ ') + name + (cond ? '' : (' » ' + (extra == null ? '' : extra))))
|
||||
}
|
||||
|
||||
// ── 一、版本与注册契约 ───────────────────────────────────────
|
||||
ok('package.json version = 1.1.1', pkg.version === '1.1.1', pkg.version)
|
||||
ok('manifest.version = 1.1.1', /version:\s*'1\.1\.1'/.test(src))
|
||||
ok('id = album', /id:\s*'album'/.test(src))
|
||||
ok('capabilities 含 nodeTypes / images / files',
|
||||
/capabilities:\s*\['nodeTypes',\s*'images',\s*'files'\]/.test(src))
|
||||
ok('默认 outKind = images(宿主靠它认「多图源」,决定连线白名单 + 任务展开)',
|
||||
/defaults:\s*\{[^}]*outKind:\s*'images'/.test(src))
|
||||
ok('端口 in/out 都在(相册要接提示词、要出图)', /ports:\s*\{\s*in:\s*true,\s*out:\s*true\s*\}/.test(src))
|
||||
|
||||
// ── 二、容量常量必须与 styles.css 对齐 ────────────────────────
|
||||
// 宿主全局 * { box-sizing: border-box },所以 CSS 的 height 已含 padding;JS 侧照抄即可。
|
||||
const cssGap = /\.iwb-album-grid\s*\{[^}]*gap:\s*var\(--iwb-space-4\)/.test(css) ? 4 : -1
|
||||
ok('宫格 gap = 4px(CSS 用 --iwb-space-4)', cssGap === 4)
|
||||
ok('JS GAP 与 CSS 一致(4)', /const GAP = 4\b/.test(src))
|
||||
ok('PAD_X = 16(左右各 --iwb-space-8)', /const PAD_X = 16\b/.test(src))
|
||||
ok('PAD_Y = 8(宫格 padding 2 + 6)', /const PAD_Y = 8\b/.test(src))
|
||||
ok('BAR_H = 26(顶栏 height: 26px)', /const BAR_H = 26\b/.test(src))
|
||||
ok('TOOLS_H = 25(工具条 padding 2+2 + 按钮 21)', /const TOOLS_H = 25\b/.test(src))
|
||||
ok('PAGER_H = 26(分页条 height: 26px)', /const PAGER_H = 26\b/.test(src))
|
||||
ok('HINT_H = 28(提示行 24 + margin-bottom 4)', /const HINT_H = 28\b/.test(src))
|
||||
ok('顶栏确实 height: 26px', /\.iwb-album-bar\s*\{[^}]*height:\s*26px/.test(css))
|
||||
ok('分页条确实 height: 26px', /\.iwb-album-pager\s*\{[^}]*height:\s*26px/.test(css))
|
||||
|
||||
// ── 三、把纯逻辑抽出来在 vm 里真跑 ────────────────────────────
|
||||
const from = src.indexOf(' const DENSITY')
|
||||
const to = src.indexOf(' // ── 数据读写')
|
||||
ok('能定位到常量段与 capacityOf(抽出来跑算术)', from > 0 && to > from, from + '/' + to)
|
||||
let sandbox = {}
|
||||
if (from > 0 && to > from) {
|
||||
// const / 箭头函数在 vm 顶层是词法的,不会自动挂到 sandbox 上 ⇒ 显式导出一份
|
||||
const code = src.slice(from, to) + '\n;globalThis.__album = { DENSITY: DENSITY, capacityOf: capacityOf, thumbKeyOf: thumbKeyOf, thumbNameOf: thumbNameOf }\n'
|
||||
sandbox = { document: { createElement: () => ({ style: {}, appendChild() {} }) }, setTimeout, clearTimeout, Math, String, Number, Array, Object, Map, Set, Promise, JSON, RegExp, console, window: {} }
|
||||
vm.createContext(sandbox)
|
||||
vm.runInContext(code, sandbox, { filename: 'album-slice.js' })
|
||||
Object.assign(sandbox, sandbox.__album || {})
|
||||
}
|
||||
|
||||
const cap = sandbox.capacityOf
|
||||
const DENSITY = sandbox.DENSITY
|
||||
ok('DENSITY 三档严格递增(旧值 M:48 < S:64 是 bug:中格比小格还小)',
|
||||
DENSITY && DENSITY.S < DENSITY.M && DENSITY.M < DENSITY.L, JSON.stringify(DENSITY))
|
||||
|
||||
if (typeof cap === 'function') {
|
||||
// 默认节点 300×470(DEFAULT_H),这是用户最常看到的那一档
|
||||
const s = cap(300, 470, 'S', false)
|
||||
const m = cap(300, 470, 'M', false)
|
||||
const l = cap(300, 470, 'L', false)
|
||||
ok('300×470 小格 = 4 列(实测渲染 4 列 68px)', s.cols === 4, JSON.stringify(s))
|
||||
ok('每页容量随档位递减 S > M > L(旧的 M 反而最多)',
|
||||
s.capacity > m.capacity && m.capacity > l.capacity,
|
||||
[s.capacity, m.capacity, l.capacity].join(' / '))
|
||||
ok('小格每页 20 张(批量导入的常见预期值)', s.capacity === 20, String(s.capacity))
|
||||
// 关键几何不变量:cols 个 cell + (cols-1) 个 gap 必须装得进内容宽度,
|
||||
// rows 个 cell + (rows-1) 个 gap 必须装得进内容高度。差 1px 就会让最后一行被裁。
|
||||
const fits = (w, h, d, hint) => {
|
||||
const c = cap(w, h, d, hint)
|
||||
const innerW = w - 4 - 16
|
||||
const innerH = h - 4 - 26 - 25 - 26 - (hint ? 28 : 0) - 8
|
||||
const needW = c.cols * c.cell + (c.cols - 1) * 4
|
||||
const needH = c.rows * c.cell + (c.rows - 1) * 4
|
||||
return { c, okW: needW <= innerW, okH: needH <= innerH, needW, needH, innerW, innerH }
|
||||
}
|
||||
let allFit = true
|
||||
const misses = []
|
||||
for (const w of [264, 280, 300, 360, 420, 520, 600]) {
|
||||
for (const h of [300, 380, 470, 560, 700]) {
|
||||
for (const d of ['S', 'M', 'L']) {
|
||||
for (const hint of [false, true]) {
|
||||
const r = fits(w, h, d, hint)
|
||||
if (!r.okW || !r.okH) { allFit = false; misses.push(w + 'x' + h + ' ' + d + (hint ? '+hint ' : ' ') + JSON.stringify([r.needW, r.innerW, r.needH, r.innerH])) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ok('35 种节点尺寸 × 3 档 × 有无提示行:算出的容量都能装进可视区(不会裁掉最后一行)',
|
||||
allFit, misses.slice(0, 3).join(' | '))
|
||||
const min = cap(180, 160, 'S', true)
|
||||
ok('极小节点也不返回 0 列 0 行(否则宫格空白)', min.cols >= 1 && min.rows >= 1 && min.capacity >= 1, JSON.stringify(min))
|
||||
}
|
||||
|
||||
// thumbKeyOf:固化后(src 变成 {__blob})不能退化成纯文件名(否则同名文件串味)
|
||||
const tk = sandbox.thumbKeyOf
|
||||
if (typeof tk === 'function') {
|
||||
const a1 = tk({ src: { __file: '/a/1.png' }, name: '1.png' })
|
||||
const a2 = tk({ src: { __file: '/b/1.png' }, name: '1.png' })
|
||||
ok('同名不同目录的本地图 → 不同键(旧实现两处都是 "1.png",缩略图互相覆盖)', a1 !== a2, a1 + ' vs ' + a2)
|
||||
const b1 = tk({ src: { __blob: 'x1' }, name: '1.png' })
|
||||
const b2 = tk({ src: { __blob: 'x2' }, name: '1.png' })
|
||||
ok('固化后按 __blob id 取键,不退化到文件名', b1 !== b2 && b1.indexOf('b:') === 0, b1 + ' vs ' + b2)
|
||||
ok('同一引用取键稳定(拖拽排序后不会重建缩略图)', tk({ src: { __file: '/a/1.png' }, name: '1.png' }) === a1)
|
||||
ok('键做成了文件安全的形式(t-<hash8>.jpg,符合插件文件白名单)',
|
||||
/^[a-z0-9][a-z0-9_-]{0,63}\.jpg$/.test(sandbox.thumbNameOf(a1)), sandbox.thumbNameOf(a1))
|
||||
} else ok('thumbKeyOf 可被抽取执行', false)
|
||||
|
||||
// ── 四、交互:清空 / 放大镜 / 固定方形 / 细边线 ────────────────
|
||||
ok('有「清空」按钮', /className:\s*'iwb-album-btn iwb-album-clear'/.test(src))
|
||||
ok('清空走快照(⌘Z 能整体撤销)',
|
||||
/function clearAll[\s\S]{0,700}update\(st\.props, st\.node, \{ items: \[\], page: 0, pageRange: null \}, true\)/.test(src))
|
||||
ok('清空只在有图时出现', /st\.btnClear\.style\.display = items\.length \? '' : 'none'/.test(src))
|
||||
ok('清空后重置失联检测(否则清空再导入永远不检测)', /function clearAll[\s\S]{0,600}st\.checkedMissing = false/.test(src))
|
||||
|
||||
ok('格子固定正方形(aspect-ratio: 1 / 1)', /\.iwb-album-cell\s*\{[^}]*aspect-ratio:\s*1 \/ 1/.test(css))
|
||||
ok('格子显式 padding: 0(button 默认内边距会把图顶出边框)', /\.iwb-album-cell\s*\{[^}]*padding:\s*0;/.test(css))
|
||||
ok('选中线 1px(用户:2px 太粗)', /\.iwb-album-cell\.sel\s*\{[^}]*outline:\s*1px solid/.test(css))
|
||||
ok('失联虚线同步 1px', /\.iwb-album-cell\.missing\s*\{[^}]*outline:\s*1px dashed/.test(css))
|
||||
|
||||
ok('放大镜元素存在(右下角)', /className:\s*'iwb-album-zoom'/.test(src))
|
||||
ok('放大镜点击进宿主全屏预览(props.onPreview)',
|
||||
/zoom\.addEventListener\('click',[\s\S]{0,120}openFull\(ctx, st, it\)/.test(src) &&
|
||||
/function openFull[\s\S]{0,700}props\.onPreview\(/.test(src))
|
||||
// 1.1.1 用户裁定:**只保留点击全屏(B)**。hover 方案(A)实测把放大镜盖住了 ⇒ 滑过去点不到。
|
||||
ok('不再有 hover 预览(pointerenter 触发 showPreview)', !/pointerenter'[\s\S]{0,80}showPreview/.test(src))
|
||||
ok('showPreview / hidePreview / 预览层代码彻底删除', !/function showPreview|function hidePreview/.test(src))
|
||||
ok('CSS 里没有节点内预览层(.iwb-album-preview)', !/iwb-album-preview/.test(css))
|
||||
ok('放大镜 z-index 高于图片与角标(不再被任何浮层压住)',
|
||||
/\.iwb-album-zoom\s*\{[^}]*z-index:\s*[1-9]/.test(css))
|
||||
ok('放大镜在键盘聚焦时也可见(focus-within,不只 hover)',
|
||||
/\.iwb-album-cell:focus-within \.iwb-album-zoom/.test(css))
|
||||
ok('放大镜提示文案说明「点空白 / Esc 关闭」', /title:\s*'查看大图(点击空白处或按 Esc 关闭)'/.test(src))
|
||||
|
||||
// ── 五、已修复的老 bug 必须有防回归断言 ───────────────────────
|
||||
ok('批次角标彻底移除(右上角那个「1」是重复信息)',
|
||||
!src.includes('iwb-album-batch') && !css.includes('iwb-album-batch'))
|
||||
ok('不再有 img.src = \'\'(会向页面 URL 发空请求,控制台报 ERR_UNKNOWN_URL_SCHEME)',
|
||||
!/\.src = ''/.test(src.split('\n').filter((l) => l.trim().indexOf('//') !== 0).join('\n')))
|
||||
ok('跨页拖拽用「每页容量」换算,不用「本页格子数」',
|
||||
/pageStart = pageNow \* capNow\.capacity/.test(src) && !/page \* cellCount/.test(src))
|
||||
ok('删除不再硬编码跳回第 1 页', !/\{ items, page: 0 \}/.test(src) && /page: Math\.min\(pageNow, pagesNow - 1\)/.test(src))
|
||||
ok('空节点不再显示「全部 0 张一页展示」(压着空态提示的废话)',
|
||||
/const showOne = !showPager && items\.length > 0/.test(src))
|
||||
ok('「文件夹」按钮不再 canReference() || true(网页版点了没反应)',
|
||||
!/\|\| true \? '' : 'none'/.test(src))
|
||||
ok('addPaths 里没有 keep 死变量', !/const keep = \(st\.node\.data/.test(src))
|
||||
ok('缩略图请求并发去重(st.pending,否则导入 30 张要解 60 次原图)',
|
||||
/const flight = st\.pending && st\.pending\.get\(key\)/.test(src))
|
||||
ok('缩略图预生成有进度(500 张导入时不会看起来卡死)', /st\.busy = '缩略图 '/.test(src))
|
||||
ok('新导入后重置 checkedMissing', /function addPaths[\s\S]{0,900}st\.checkedMissing = false/.test(src))
|
||||
|
||||
// ── 六、宿主契约不能碰 ───────────────────────────────────────
|
||||
ok('仍然只写 items / page / pageRange 这几个字段给宿主(不新增宿主不认识的键)',
|
||||
/outKind: 'images'/.test(src) && /pageRange: wantRange/.test(src))
|
||||
ok('只引用不复制:本地图仍写 { __file: 路径 }', /\{ __file: ref\.item\.path \}/.test(src))
|
||||
ok('缩略图仍存宿主插件沙箱(ctx.files),不塞进节点数据',
|
||||
/ctx\.files\.put\(name, thumb\)/.test(src) && !/thumbs[\s\S]{0,40}onUpdate/.test(src))
|
||||
ok('没有引入 import/export(必须是经典脚本 IIFE,CSP script-src self)',
|
||||
!/^\s*(import|export)\s/m.test(src) && /^;\(function \(global\)/m.test(src))
|
||||
ok('样式只能 JS 内联注入之外的地方没有新增 <style> 标签', !/<style/.test(src))
|
||||
|
||||
console.log('\n' + (failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过'))
|
||||
process.exit(failed ? 1 : 0)
|
||||
+13
-22
@@ -70,7 +70,7 @@
|
||||
|
||||
自写 STORE(无压缩)写入器,零依赖:
|
||||
|
||||
- **为什么不用 JSZip**:宿主 CSP 是 `script-src 'self'`,CDN 动态插 script 会被拦死(宿主 `storage-zip.js` 记着这条教训)。
|
||||
- **为什么不用 JSZip**:桌面宿主 CSP 是 `script-src 'self' blob:`,CDN 动态插 script 会被拦死(宿主 `storage-zip.js` 记着这条教训)。
|
||||
- **为什么 STORE**:图片本身已是 PNG/JPEG,DEFLATE 几乎不减体积,还白花 CPU。
|
||||
- **文件名 UTF-8**:写 general purpose bit 11(`0x0800`),中文名在 Windows 资源管理器 / macOS 归档实用工具里正常。
|
||||
⚠️ **macOS 命令行 `unzip`(Info-ZIP 6.0)不认这个标志位**,会解成乱码并报 `Illegal byte sequence` —— 是那个老工具的锅,
|
||||
@@ -80,7 +80,7 @@
|
||||
## CSP / 权限
|
||||
|
||||
- 只声明 `panels` + `canvas`(只读),**不要 `canvasWrite`** —— 本插件不写画布。
|
||||
- 抠图请求打到 `apiUrl`,CSP 只放行 `127.0.0.1` / `localhost` 的 `30092`;改别的地址会被浏览器拦。
|
||||
- 抠图请求打到 `apiUrl`,桌面宿主 CSP 只放行 `127.0.0.1` / `localhost` 的 `30092`;改别的地址会被拦。
|
||||
- `createObjectURL` 下载走 `a.click()`;`img-src` 放行 `blob:`,解码用 blob URL 并即时释放。
|
||||
|
||||
## 验证(开发用)
|
||||
@@ -93,39 +93,30 @@ mock 宿主 + 真实 Chromium,覆盖:manifest / 面板注册与挂载 / 列
|
||||
队列跑通 / **ZIP 用系统 `unzip -t` 验结构与 CRC + python3 zipfile 验中文名与 8 个条目 + PNG/JPEG magic** /
|
||||
抠图分支(mock `/rmbg`)/ 失败行内提示 / 参数持久化 / 静态检查(无 eval、无 `fetch(data:)`)。
|
||||
|
||||
需要 Playwright(可从宿主仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定)+ 系统 `unzip`、`python3`,不进 CI。
|
||||
需要 Playwright(可从桌面仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定)+ 系统 `unzip`、`python3`,不进 CI。
|
||||
|
||||
**发布后必须再跑一次真站**(mock 抓不到宿主 CSS / 真实 CSP / 真实面板挂载):
|
||||
**发布后必须再跑一次真机**(mock 抓不到宿主 CSS / 真实 CSP / 真实面板挂载):
|
||||
|
||||
```bash
|
||||
node batch-export/tools/e2e-site.mjs # 测试站
|
||||
IWB_BASE_URL=https://iwb.maqiart.eu.org node batch-export/tools/e2e-site.mjs # 正式站
|
||||
node batch-export/tools/e2e-site.mjs
|
||||
```
|
||||
|
||||
覆盖:真实 KV 加载 + SRI + 资源中心 tab 出现 + 面板挂载 + 列表 2 行 +
|
||||
覆盖:市场安装加载 + SRI + 资源中心 tab 出现 + 面板挂载 + 列表 2 行 +
|
||||
**勾选框与文字同行(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)** +
|
||||
队列跑通 + 下载 ZIP + python3 校验 4 条目 / CRC / PNG·JPEG magic / UTF-8 名。
|
||||
|
||||
## 发布
|
||||
|
||||
本仓只产出 `src/index.js`(手写单文件 IIFE)。发布走桌面仓的市场链路,见根 README「发布到市场」:
|
||||
|
||||
```bash
|
||||
cd /Users/qiqi/open/github/image-workbench-web
|
||||
cp /Users/qiqi/open/github/iwb-plugins/batch-export/src/index.js /tmp/plugin-batch-export.js
|
||||
# ⚠️ 必须把所有插件文件一起传入:发布器用「传入的文件」重建 plugins/index.json,不做合并
|
||||
cp /Users/qiqi/open/github/iwb-plugins/white-bg-800/src/index.js /tmp/plugin-white-bg-800.js
|
||||
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
|
||||
cp /Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js /tmp/plugin-image-annotate.js
|
||||
cp /Users/qiqi/open/github/iwb-plugins/blank-canvas/src/index.js /tmp/plugin-blank-canvas.js
|
||||
node scripts/plugins-publish.mjs /tmp/plugin-batch-export.js /tmp/plugin-white-bg-800.js \
|
||||
/tmp/plugin-xianyi-cutout.js /tmp/plugin-image-annotate.js /tmp/plugin-blank-canvas.js \
|
||||
--version batch-export=1.1.0 # 默认 dry-run,检查 diff 后再加 --upload
|
||||
npm run validate
|
||||
# 桌面仓:node scripts/sync-plugins-from-repo.js && node scripts/gen-market.js
|
||||
# 再把 market/ 上传到 NAS(market.maqiart.eu.org)
|
||||
```
|
||||
|
||||
发布后刷新即生效;新插件在「设置 → 插件」里**默认未启用**,需手动勾选。
|
||||
|
||||
⚠️ `--upload` 时脚本按清单顺序逐个 put,最后才 put `index.json`。代理抖动会让它在半路 `fetch failed` 退出,
|
||||
此时**清单可能已经指向还没上传成功的文件**(1.0.1 发布时踩过)⇒ 线上 fail-closed 直接不加载。
|
||||
稳妥做法:先把插件字节 put 上去,`curl` 确认 200 且大小对,再 put `index.json`。
|
||||
桌面仓同步脚本按白名单一次重建全部插件清单。改版本时同步 `package.json` 的 `version`
|
||||
与 `src/index.js` 里 manifest 的 `version`。发布后回读市场索引确认版本与哈希已更新,再在客户端市场安装验证。
|
||||
|
||||
## 版本记录
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/batch-export",
|
||||
"private": true,
|
||||
"version": "1.2.0",
|
||||
"version": "1.2.2",
|
||||
"description": "批量出图:资源中心面板里勾选 ref 节点,串行跑(可选本机抠图)→ 白底/透明合成 → 双版本编码 → 打包 ZIP 下载;行内可单张下载 JPG/PNG",
|
||||
"ibwPlugin": {
|
||||
"id": "batch-export",
|
||||
|
||||
+22
-12
@@ -454,37 +454,47 @@
|
||||
'.iwb-bx-name{flex:1;min-width:70px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
|
||||
'.iwb-bx-tag{font-size:11px;white-space:nowrap;color:var(--iwb-text2,#4d5668);',
|
||||
'max-width:46%;min-width:0;overflow:hidden;text-overflow:ellipsis}',
|
||||
'.iwb-bx-tag-ok{color:#1d9e75}',
|
||||
'.iwb-bx-tag-err{color:#d85a30}',
|
||||
// 状态色不能直接当文字色:宿主 --iwb-ok 亮色是 #22c55e,压在浅页面上对比只有 2.13。
|
||||
// 照 design-tokens.md §3 的 iwb-mk-badge 范例,用 color-mix 往 --iwb-text 压 18%,亮暗两端都读得清。
|
||||
'.iwb-bx-tag-ok{color:color-mix(in srgb,var(--iwb-ok,#1d9e75) 82%,var(--iwb-text,#1c2333))}',
|
||||
'.iwb-bx-tag-err{color:color-mix(in srgb,var(--iwb-err,#d85a30) 82%,var(--iwb-text,#1c2333))}',
|
||||
// 行内单张下载:常驻不悬浮(要一眼看出「这行能下什么」),无产物时灰掉但保留占位,
|
||||
// 避免产物出现时行宽突然变化导致列表跳动。
|
||||
'.iwb-bx-dl{flex:0 0 auto;padding:2px 6px;border-radius:5px;font-size:11px;line-height:1.5;',
|
||||
'font-family:ui-monospace,SFMono-Regular,Menlo,monospace;border:1px solid var(--iwb-border,#d5d9e0);',
|
||||
'background:transparent;color:var(--iwb-text2,#4d5668);cursor:pointer}',
|
||||
'.iwb-bx-dl-on{background:var(--iwb-layer,#f0f1f4);color:var(--iwb-text,#1c2333);border-color:var(--iwb-text2,#4d5668)}',
|
||||
'.iwb-bx-dl-on:hover{border-color:#2f6fed;color:#2f6fed}',
|
||||
'.iwb-bx-dl-on:hover{border-color:var(--iwb-brand,#2f6fed);color:var(--iwb-brand-text,#2f6fed)}',
|
||||
'.iwb-bx-dl[disabled]{opacity:.45;cursor:not-allowed;border-color:var(--iwb-border,#d5d9e0)}',
|
||||
'.iwb-bx-empty{padding:24px 12px;text-align:center;color:var(--iwb-text2,#4d5668)}',
|
||||
// 缩略图:小方图(30px)常驻在行首,跑完换成产物本身,一眼能对上「哪张图、出了什么」
|
||||
'.iwb-bx-thumb{width:30px;height:30px;flex:0 0 auto;object-fit:contain;border-radius:5px;',
|
||||
'border:1px solid var(--iwb-border,#d5d9e0);background:#fff;cursor:zoom-in;padding:1px}',
|
||||
'.iwb-bx-thumb-out{border-color:#1d9e75;cursor:zoom-in}',
|
||||
'border:1px solid var(--iwb-border,#d5d9e0);background:#fff/*iwb:content*/;cursor:zoom-in;padding:1px}',
|
||||
'.iwb-bx-thumb-out{border-color:var(--iwb-ok,#1d9e75);cursor:zoom-in}',
|
||||
'.iwb-bx-thumb-ph{background:var(--iwb-layer,#f0f1f4);cursor:default}',
|
||||
'.iwb-bx-done{display:none;align-items:center;gap:6px;padding:9px 12px;font-size:11px;',
|
||||
'color:#1d9e75;background:rgba(29,158,117,.08);border-top:1px solid var(--iwb-border,#d5d9e0)}',
|
||||
'color:color-mix(in srgb,var(--iwb-ok,#1d9e75) 82%,var(--iwb-text,#1c2333));',
|
||||
'background:color-mix(in srgb,var(--iwb-ok,#1d9e75) 8%,transparent);',
|
||||
'border-top:1px solid var(--iwb-border,#d5d9e0)}',
|
||||
'.iwb-bx-zoom{position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;',
|
||||
'background:rgba(0,0,0,.72);cursor:zoom-out}',
|
||||
'.iwb-bx-zoom img{max-width:86vw;max-height:86vh;border-radius:8px;background:#fff}',
|
||||
// 双类选择器:单靠 .iwb-bx-btn-hot 会被后定义的 .iwb-bx-btn 背景覆盖(同特异性,后者胜)
|
||||
'.iwb-bx-btn.iwb-bx-btn-hot{background:#1d9e75;border-color:#1d9e75;color:#fff}',
|
||||
'.iwb-bx-zoom img{max-width:86vw;max-height:86vh;border-radius:8px;background:#fff/*iwb:content*/}',
|
||||
// 主/热按钮此前是纯蓝 #2f6fed 实心 + 白字:与项目「全灰阶、无蓝」的配色约束冲突,
|
||||
// 且暗色下亮绿底压白字对比度不足。改成宿主语义色成对反相 + 状态色描边,
|
||||
// var() 兜底保留私有值,脱离宿主独立运行时不退化。
|
||||
'.iwb-bx-btn.iwb-bx-btn-hot{',
|
||||
'background:color-mix(in srgb,var(--iwb-ok,#1d9e75) 14%,transparent);',
|
||||
'border-color:color-mix(in srgb,var(--iwb-ok,#1d9e75) 82%,var(--iwb-text,#1c2333));',
|
||||
'color:color-mix(in srgb,var(--iwb-ok,#1d9e75) 82%,var(--iwb-text,#1c2333))}',
|
||||
'.iwb-bx-foot{display:flex;align-items:center;gap:8px;padding:10px 12px;',
|
||||
'border-top:1px solid var(--iwb-border,#d5d9e0)}',
|
||||
'.iwb-bx-prog{flex:1;height:4px;border-radius:2px;background:var(--iwb-border,#d5d9e0);overflow:hidden}',
|
||||
'.iwb-bx-prog i{display:block;height:100%;width:0;background:#2f6fed;transition:width .15s}',
|
||||
'.iwb-bx-prog i{display:block;height:100%;width:0;background:var(--iwb-brand-text,#2f6fed);transition:width .15s}',
|
||||
'.iwb-bx-btn{padding:5px 10px;border-radius:6px;border:1px solid var(--iwb-border,#d5d9e0);',
|
||||
'background:var(--iwb-layer,#f0f1f4);color:inherit;font:inherit;cursor:pointer;white-space:nowrap}',
|
||||
'.iwb-bx-btn[disabled]{opacity:.45;cursor:not-allowed}',
|
||||
'.iwb-bx-btn-primary{background:#2f6fed;border-color:#2f6fed;color:#fff}',
|
||||
'.iwb-bx-btn-primary{background:var(--iwb-text,#2f6fed);border-color:var(--iwb-text,#2f6fed);',
|
||||
'color:var(--iwb-layer,#fff)}',
|
||||
].join('')
|
||||
|
||||
function ensureStyle() {
|
||||
@@ -500,7 +510,7 @@
|
||||
global.IWBPluginHost.register({
|
||||
id: 'batch-export',
|
||||
name: '批量出图',
|
||||
version: '1.2.0',
|
||||
version: '1.2.2',
|
||||
apiVersion: 1,
|
||||
capabilities: ['panels', 'canvas'],
|
||||
settings: {
|
||||
|
||||
@@ -31,12 +31,13 @@
|
||||
- 合成:`canvas(w,h)` → `fillStyle='#ffffff'` → `fillRect` → `toDataURL('image/png')`。
|
||||
- 写回:`ctx.canvas.setNodeImage(nodeId, dataUrl)`(原地覆盖,`url` 清空)。注意宿主把 `canvasWrite` 的 API **合并进 `ctx.canvas`**,`ctx.canvasWrite` 并不存在 —— 但 manifest 的 `capabilities` 仍须同时声明 `canvas` 与 `canvasWrite`,否则拿不到写接口。
|
||||
- 空白判定:`node.type === 'ref' && !data.data && !data.url`(与上游 `isEmptyRefNode` 等价)。
|
||||
- 样式用宿主 CSS 变量(`--iwb-panel/--iwb-text/--iwb-border/--iwb-layer`),明暗主题自适应;CSP 允许 `style-src 'unsafe-inline'`。
|
||||
- 样式用宿主 CSS 变量(`--iwb-panel/--iwb-text/--iwb-border/--iwb-layer`),明暗主题自适应;桌面宿主 CSP 允许 `style-src 'unsafe-inline'`。
|
||||
|
||||
## 已知限制
|
||||
- `setNodeImage` 不改节点名,所以不会像上游那样命名为 `<名字>_blank_<W>x<h>.png`(节点名保持不变)。若需要文件名,得宿主开放"改节点名"的写接口。
|
||||
- 1K 纯白 PNG 的 dataURL 约 30–34 KB,落库时会被宿主引用化为 `{__blob}`(超过 3000 字符阈值),属正常路径。
|
||||
|
||||
## 发布
|
||||
与其它插件一致:先 `npm run validate`,再由宿主仓的 `scripts/plugins-publish.mjs` 以哈希名入库。
|
||||
⚠️ 发布时**必须把所有插件文件一起传入**(发布器用传入的文件重建清单,不做合并)。
|
||||
与其它插件一致:本仓只产出 `src/index.js`(手写单文件 IIFE),先 `npm run validate`,再走桌面仓的市场链路
|
||||
(同步 → 生市场 → 上传 `market/` 到 NAS),见根 README「发布到市场」。
|
||||
桌面仓同步脚本按白名单一次重建全部插件清单,改版本时同步 `package.json` 与 manifest 的 `version`。
|
||||
@@ -0,0 +1,121 @@
|
||||
# browser · 应用内浏览器
|
||||
|
||||
两种用法,共用同一套宿主命令:
|
||||
|
||||
- **画布节点**:网页直接长在画布上,跟着节点平移缩放,能和参考图并排对照。
|
||||
- **独立窗口**:资源中心 →「浏览器」面板,网页在单独窗口里打开,不占画布。
|
||||
|
||||
## 画布内的网页节点
|
||||
|
||||
> **需要客户端 v3.25.29+**。
|
||||
> v3.25.24~26 有「一动就白」(移动/缩放节点或画布后内容消失),v3.25.29 之前
|
||||
> 还有「地址栏被网页盖住」与「内容不跟着画布缩放」两个问题 —— 都已修好。
|
||||
> 旧客户端上插件会直接在节点里写明需要升级,不会只留一块白板。
|
||||
|
||||
画布空白处**右键 →「插件: 网页」**(插件节点不进双击菜单,这是宿主的既定规则),
|
||||
得到一个 560×520 的网页节点:
|
||||
|
||||
```
|
||||
[←][→][⟳] [ 地址栏 ] [− 100% +] | [↗][✕]
|
||||
┌──────────────────────────────────────────┐
|
||||
│ 网页本体(原生子 webview,盖在锚点上) │
|
||||
└──────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
| 控件 | 行为 |
|
||||
|---|---|
|
||||
| `←` `→` | 后退 / 前进(走页面自身的 history) |
|
||||
| `⟳` | 刷新;**加载中变成「停止」**,点了只中断请求,不销毁视图 |
|
||||
| 地址栏 | 回车加载,`Esc` 还原;**站内跳转后自动显示当前真实地址** |
|
||||
| `− 100% +` | 内容缩放设定框:点百分比可直接输入(如 `150`、`150%`),回车生效;双击回 100%;范围 25%~300% |
|
||||
| `↗` | 用独立窗口/浏览器面板打开当前页面(方便多屏、需要网址栏时) |
|
||||
| `✕` | 关闭网页但保留节点,点 `⟳` 或重新输入网址即可恢复 |
|
||||
|
||||
其它行为:
|
||||
|
||||
- 地址存进节点数据,下次打开画布自动恢复;标题为空时自动用站点名(多个网页节点并排时分得清)。
|
||||
- **内容缩放 = 该节点缩放 × 画布缩放**:缩小画布时网页像图片一样一起缩小,不会按原宽度重排。
|
||||
- 节点可以像普通节点那样拖动、缩放、编组、复制。
|
||||
- **拖动节点要用标题栏**:网页区域的鼠标事件由网页自己消费,这是原生子 webview 的物理属性。
|
||||
- 原生视图会被裁到「节点 ∩ 画布」,且上边界不越过工具栏 —— 按钮永远点得到。
|
||||
- 画布切到别的工作区、被模态遮罩挡住、节点完全移出画布时才隐藏;平移/缩放过程全程可见。
|
||||
- 缩到画布 15% 以下(节点体走 LOD 降级)时节点体会被替换,网页随之回收;放大回来会重建。
|
||||
|
||||
## 它解决什么
|
||||
|
||||
画布里的网页内容有两条死路,都走不通:
|
||||
|
||||
- **iframe**:主窗口 CSP 是 `default-src 'self'`,外部网址被拦;就算加了 `frame-src`,百度/GitHub 等站点都发 `X-Frame-Options` / `frame-ancestors`,拒绝被嵌。实测 GitHub、站酷、Figma、Pinterest 全部拒绝,只有维基/百度/B站/花瓣这类允许。
|
||||
- **`<a target=_blank>`**:桌面 webview 里点外链会把**整个应用**导航成网页(宿主 `ui-desktop-shell.js` 专门拦截了这种行为)。
|
||||
|
||||
正解是原生 webview:独立窗口用 `WebviewWindow`,画布节点用 `Window::add_child` 子 webview。两者加载的都是网站自己的页面,**不受主窗口 CSP 约束**,也没有任何 IPC 权限——既能正常上网,又碰不到宿主 API。
|
||||
|
||||
## 用法(独立窗口)
|
||||
|
||||
资源中心 →「浏览器」面板:
|
||||
|
||||
- 地址栏输入网址,`回车` 或点「打开」。没写协议自动补 `https://`。
|
||||
- 点书签快捷打开。默认四个:风格库 / 百度 / 必应 / GitHub。
|
||||
- 重复打开不同网址会**复用同一个窗口**:聚焦过去并导航到新地址,不会越开越多。
|
||||
- 地址栏下面一排控制:`← 后退` `→ 前进` `⟳ 刷新` `✕ 关闭`,左侧圆点显示窗口是否还开着、当前在哪个站。外部页里跳走之后从这里退回来,不用重新输网址。
|
||||
|
||||
书签自定义:设置 → 插件 →「应用内浏览器」→ `书签`,每行一个,格式 `名称 | 网址`(网址可省略 `https://`,`#` 开头是注释)。留空恢复默认。
|
||||
|
||||
## 依赖宿主命令(重要)
|
||||
|
||||
插件调用桌面仓的命令(`__TAURI__.core.invoke`),实现在 `image-workbench-desktop/src-tauri/src/lib.rs`。
|
||||
|
||||
**独立窗口:**
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `open_browser_window` | 打开/复用独立窗口并导航(原生 `navigate`,不往外部页面注入 JS) |
|
||||
| `browser_control` | `back` / `forward` / `reload` / `close` |
|
||||
| `browser_state` | 返回 `{ open, url }`,面板据此显示当前站点、启用或禁用按钮 |
|
||||
|
||||
**画布节点:**
|
||||
|
||||
| 命令 | 作用 |
|
||||
|---|---|
|
||||
| `canvas_webview_metrics` | 返回窗口边框尺寸(渲染层据此算「原生层 vs DOM」的坐标原点差) |
|
||||
| `canvas_webview_ensure` | 按节点 id 建子 webview(已存在则只校正 rect / zoom) |
|
||||
| `canvas_webview_bounds` | 位置/尺寸/可见性/缩放,渲染层按需推(热路径) |
|
||||
| `canvas_webview_navigate` | 导航到新地址 |
|
||||
| `canvas_webview_action` | `back` / `forward` / `reload` / `stop` / `close` |
|
||||
| `canvas_webview_state` | 返回 `{ open, url }` |
|
||||
| `canvas_webview_close_all` | 回收全部 `cwv-*` 子 webview(切工作区/退出时) |
|
||||
|
||||
**位置同步的三个坑(宿主 `src/canvas-webview.js` 与 `lib.rs` 里都有注释)**:
|
||||
|
||||
1. 子 webview 的 `LogicalPosition` 以**窗口边框**为原点,DOM 矩形以**内容视图**为原点,
|
||||
差一个标题栏高度(macOS 标准标题栏 32pt)。不补这一下,网页整体上浮压住工具栏。
|
||||
2. macOS 上 `hide()` 之后再 `show()` 会静默失效(都返回 Ok,网页永久不绘制)⇒ 隐藏一律用
|
||||
「挪到窗口外」。
|
||||
3. `get_webview_window("main")` 在出现任何子 webview 之后永久返回 `None` ⇒ 取窗口用
|
||||
`get_window("main")`。
|
||||
|
||||
子 webview 的 label 是 `cwv-<节点id>`,同样不在 capabilities 里 ⇒ 无 IPC 权限。
|
||||
插件把状态写到锚点属性上(`data-iwb-cwv` / `-url` / `-zoom` / `-paused`),
|
||||
宿主读属性驱动原生层,反向则通过 `document` 上的 `iwb-cwv-state` 事件回传加载态与真实地址。
|
||||
|
||||
**没有这些命令的宿主**(例如旧版客户端、或合成测试宿主):`open_browser_window` 会失败,插件自动降级到 `window.open`(系统默认浏览器),不会崩;导航按钮保持禁用。
|
||||
|
||||
## 契约
|
||||
|
||||
- manifest:`id: 'browser'`,`version: '1.4.0'`,`apiVersion: 1`,`capabilities: ['panels', 'nodeTypes']`。
|
||||
- 只注册一个面板与一个节点类型(`web`,无端口,宽 560 / 高 520)。
|
||||
- CSS 在脚本执行时就注入(`#iwb-browser-style`),不依赖面板 mount——避免存档直入时无样式。
|
||||
- 样式用宿主 CSS 变量(`--iwb-text` / `--iwb-layer` / `--iwb-border` 等),带兜底色,明暗主题都能看。
|
||||
|
||||
## 开发 / 测试
|
||||
|
||||
手写单文件 IIFE,`src/index.js` 即产物,无需构建。
|
||||
|
||||
```bash
|
||||
npm run validate # 契约校验
|
||||
node browser/tools/harness.mjs # 本地测试(纯 node,62 项:manifest / 面板 / URL 补全 /
|
||||
# 命令调用 / 回退 / 书签 / 画布节点工具栏 / 缩放框 /
|
||||
# 暂停与恢复 / 状态回填 / 编辑输入不被覆盖)
|
||||
```
|
||||
|
||||
改完从市场重新同步到桌面仓(见根 README「发布到市场」)。**新增插件要上架,必须把 `browser` 加进桌面仓 `sync-plugins-from-repo.js` 的白名单,并在 `plugins/meta.json` 补展示信息**;只在本地开发者模式用则不用。
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "@iwb-plugin/browser",
|
||||
"private": true,
|
||||
"version": "1.7.1",
|
||||
"description": "应用内浏览器:独立窗口打开网页,或在画布节点里内嵌网页(跟随画布缩放,可单独调内容缩放)",
|
||||
"ibwPlugin": {
|
||||
"id": "browser",
|
||||
"entry": "src/index.js",
|
||||
"apiVersion": 1
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,523 @@
|
||||
// 应用内浏览器插件的本地契约测试(纯 node,不依赖 playwright / 真浏览器)。
|
||||
//
|
||||
// 用最小 DOM / window stub 跑真实 src/index.js(IIFE),验证:
|
||||
// manifest 字段 / 面板注册 / CSS 脚本执行时就注入 / URL 补全与校验 /
|
||||
// 地址栏提交与书签点击都走 open_browser_window 命令 / 命令失败回退 window.open /
|
||||
// 无 Tauri 回退 / 书签自定义解析 /
|
||||
// 导航控制按钮的启用-禁用 / 后退走 browser_control / 状态行显示当前网址 /
|
||||
// 反复 mount 不累积 settings 订阅。
|
||||
//
|
||||
// 运行:node browser/tools/harness.mjs (退出码 0 = 全过)
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const ENTRY = path.resolve(HERE, '../src/index.js')
|
||||
const source = readFileSync(ENTRY, 'utf8')
|
||||
|
||||
let failed = 0
|
||||
const check = (name, ok, detail) => {
|
||||
if (!ok) failed++
|
||||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||||
}
|
||||
|
||||
// 深度按 class 找节点:书签条现在包在 .iwb-browser-bmwrap 里,不再是面板根的子节点
|
||||
const findClass = (root, cls) => {
|
||||
if (!root) return null
|
||||
const queue = [root]
|
||||
while (queue.length) {
|
||||
const n = queue.shift()
|
||||
if (n.className === cls) return n
|
||||
if (Array.isArray(n.children)) queue.push(...n.children)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// ---------- 极简 DOM stub(带可触发的事件监听) ----------
|
||||
function makeNode(tag) {
|
||||
const node = {
|
||||
tagName: String(tag || 'div').toUpperCase(),
|
||||
style: {},
|
||||
attrs: {},
|
||||
children: [],
|
||||
className: '',
|
||||
_text: '',
|
||||
_listeners: {},
|
||||
classList: {
|
||||
_set: new Set(),
|
||||
add(c) { this._set.add(c) },
|
||||
remove(c) { this._set.delete(c) },
|
||||
contains(c) { return this._set.has(c) },
|
||||
},
|
||||
set textContent(v) { this._text = String(v) },
|
||||
get textContent() { return this._text },
|
||||
setAttribute(k, v) { this.attrs[k] = String(v) },
|
||||
getAttribute(k) { return this.attrs[k] },
|
||||
removeAttribute(k) { delete this.attrs[k] },
|
||||
appendChild(c) { this.children.push(c); return c },
|
||||
addEventListener(name, fn) { (this._listeners[name] || (this._listeners[name] = [])).push(fn) },
|
||||
fire(name, ev) {
|
||||
const e = Object.assign({ preventDefault() {}, stopPropagation() {}, key: '' }, ev || {})
|
||||
;(this._listeners[name] || []).forEach((fn) => fn(e))
|
||||
},
|
||||
value: '',
|
||||
focus() { this._focused = true },
|
||||
blur() { this._focused = false },
|
||||
select() { this._selected = true },
|
||||
set innerHTML(v) { if (v === '') this.children = [] }
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
function makeDom() {
|
||||
const styles = new Map()
|
||||
return {
|
||||
_styles: styles,
|
||||
createElement(tag) { return makeNode(tag) },
|
||||
createTextNode(t) { return { _text: String(t), nodeType: 3 } },
|
||||
_listeners: {},
|
||||
activeElement: null,
|
||||
addEventListener(name, fn) { (this._listeners[name] || (this._listeners[name] = [])).push(fn) },
|
||||
dispatchEvent(ev) { (this._listeners[ev.type] || []).forEach((fn) => fn(ev)); return true },
|
||||
getElementById(id) { return styles.get(id) || null },
|
||||
head: { appendChild(n) { styles.set(n.id, n) } },
|
||||
documentElement: { appendChild(n) { styles.set(n.id, n) } }
|
||||
}
|
||||
}
|
||||
|
||||
function runPlugin({ invokeImpl, prefs, canvas } = {}) {
|
||||
const calls = []
|
||||
const doc = makeDom()
|
||||
let registered = null
|
||||
let panel = null
|
||||
let nodeType = null
|
||||
const settings = Object.assign({}, prefs || {})
|
||||
const settingsListeners = []
|
||||
let unsubscribed = 0
|
||||
|
||||
const hostObj = {
|
||||
IWBPluginHost: {
|
||||
register(manifest, factory) {
|
||||
registered = manifest
|
||||
factory({
|
||||
log() {},
|
||||
settings: {
|
||||
get(k) { return settings[k] },
|
||||
onChange(fn) {
|
||||
settingsListeners.push(fn)
|
||||
return function () { unsubscribed++ }
|
||||
}
|
||||
},
|
||||
ui: {
|
||||
registerPanel(p) { panel = p }
|
||||
},
|
||||
nodes: {
|
||||
register(v) { nodeType = v; return true }
|
||||
},
|
||||
// 旧宿主没有 canvasWrite:不传 canvas 就是那条路径(ctx.canvas 为 undefined)
|
||||
...(canvas ? { canvas } : {})
|
||||
})
|
||||
}
|
||||
},
|
||||
__TAURI__: invokeImpl
|
||||
? { core: { invoke: (name, args) => { calls.push({ name, args }); return invokeImpl(name, args) } } }
|
||||
: undefined,
|
||||
open(url) { calls.push({ name: 'window.open', args: { url } }); return null },
|
||||
URL
|
||||
}
|
||||
const sandbox = {
|
||||
window: hostObj, globalThis: hostObj,
|
||||
document: doc, URL, console, Promise, setTimeout, clearTimeout
|
||||
}
|
||||
vm.runInNewContext(source, sandbox, { filename: 'browser/src/index.js' })
|
||||
return {
|
||||
registered, panel, calls, doc, nodeType,
|
||||
get unsubscribed() { return unsubscribed },
|
||||
fireSetting: (name) => settingsListeners.forEach((fn) => fn(name)),
|
||||
setSetting: (k, v) => { settings[k] = v }
|
||||
}
|
||||
}
|
||||
|
||||
function mountPanel(panel, doc) {
|
||||
const root = doc.createElement('div')
|
||||
panel.mount(root)
|
||||
return root
|
||||
}
|
||||
|
||||
const openCalls = (r) => r.calls.filter((c) => c.name === 'open_browser_window')
|
||||
const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
// 默认:打开成功、browser_state 报「窗口未打开」
|
||||
const okInvoke = () => (name) => {
|
||||
if (name === 'browser_state') return Promise.resolve({ open: false, url: '' })
|
||||
return Promise.resolve(true)
|
||||
}
|
||||
|
||||
// ---------- manifest / 注册 / CSS ----------
|
||||
{
|
||||
const { registered, panel, doc } = runPlugin()
|
||||
check('manifest id = browser', registered && registered.id === 'browser')
|
||||
// 版本号只在一处维护(package.json),断言改为一致性检查,免得每次发版手工改测试
|
||||
const pkgVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
|
||||
check('manifest version 与 package.json 一致(' + pkgVersion + ')',
|
||||
registered && registered.version === pkgVersion, registered && registered.version)
|
||||
check('manifest apiVersion = 1', registered && registered.apiVersion === 1)
|
||||
check('manifest capabilities = panels + nodeTypes + canvasWrite', registered && JSON.stringify(registered.capabilities) === '["panels","nodeTypes","canvasWrite"]',
|
||||
registered && JSON.stringify(registered.capabilities))
|
||||
check('manifest 声明 bookmarks 设置', registered && !!registered.settings.bookmarks)
|
||||
check('注册了面板 browser-panel', !!panel && panel.id === 'browser-panel' && typeof panel.mount === 'function')
|
||||
check('CSS 在脚本执行时就注入(未 mount 已存在)', doc.getElementById('iwb-browser-style') !== null)
|
||||
}
|
||||
|
||||
// ---------- 面板 = 内嵌浏览器(结构) ----------
|
||||
{
|
||||
const { panel, doc } = runPlugin()
|
||||
let mountOk = true
|
||||
let root
|
||||
try { root = mountPanel(panel, doc) } catch (e) { mountOk = false; console.error(e) }
|
||||
check('mount 成功', mountOk)
|
||||
const bar = root && root.children.find((c) => c.className === 'iwb-cwv-bar')
|
||||
const stage = root && root.children.find((c) => c.className === 'iwb-cwv-stage')
|
||||
check('面板换成浏览器工具栏 + 内容区', !!bar && !!stage)
|
||||
const anchorOf = (r) => {
|
||||
const s = r.children.find((c) => c.className === 'iwb-cwv-stage')
|
||||
return s && s.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
|
||||
}
|
||||
const anchor = anchorOf(root)
|
||||
check('内容区里有原生网页锚点 panel:browser', !!anchor)
|
||||
check('锚点标记 scope=panel(不跟画布缩放)', anchor && anchor.attrs['data-iwb-cwv-scope'] === 'panel')
|
||||
check('未输入网址时锚点不带 url(不建视图)', anchor && anchor.attrs['data-iwb-cwv-url'] === undefined)
|
||||
const strip = findClass(root, 'iwb-browser-strip')
|
||||
const chips = strip ? strip.children.filter((c) => c.className === 'iwb-browser-chip') : []
|
||||
check('底部书签条默认 4 个 chip', chips.length === 4, '实际 ' + chips.length)
|
||||
const closeBtn = bar.children.find((c) => c.attrs.title && c.attrs.title.indexOf('关闭这个网页') >= 0)
|
||||
check('面板隐藏「✕ 关闭这个网页」(关掉面板就等于关闭)', !!closeBtn && closeBtn.style.display === 'none')
|
||||
}
|
||||
|
||||
// ---------- 地址栏提交:写锚点属性(不再开独立窗口) ----------
|
||||
{
|
||||
const r = runPlugin({ invokeImpl: okInvoke() })
|
||||
const root = mountPanel(r.panel, r.doc)
|
||||
const bar = root.children.find((c) => c.className === 'iwb-cwv-bar')
|
||||
const input = bar.children.find((c) => c.tagName === 'INPUT')
|
||||
const stage = root.children.find((c) => c.className === 'iwb-cwv-stage')
|
||||
const anchor = stage.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
|
||||
input.value = 'www.baidu.com'
|
||||
input.fire('keydown', { key: 'Enter' })
|
||||
check('回车不再调用 open_browser_window(内嵌,不开窗口)', openCalls(r).length === 0, JSON.stringify(r.calls))
|
||||
check('URL 自动补 https 且写进锚点', anchor.attrs['data-iwb-cwv-url'] === 'https://www.baidu.com/',
|
||||
anchor.attrs['data-iwb-cwv-url'])
|
||||
input.value = 'javascript:alert(1)'
|
||||
input.fire('keydown', { key: 'Enter' })
|
||||
check('非法协议被拒(锚点仍是上一个合法地址)',
|
||||
anchor.attrs['data-iwb-cwv-url'] === 'https://www.baidu.com/', anchor.attrs['data-iwb-cwv-url'])
|
||||
}
|
||||
|
||||
// ---------- 书签点击:导航当前内嵌浏览器 ----------
|
||||
{
|
||||
const r = runPlugin({ invokeImpl: okInvoke() })
|
||||
const root = mountPanel(r.panel, r.doc)
|
||||
const strip = findClass(root, 'iwb-browser-strip')
|
||||
const chips = strip.children.filter((c) => c.className === 'iwb-browser-chip')
|
||||
const stage = root.children.find((c) => c.className === 'iwb-cwv-stage')
|
||||
const anchor = stage.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
|
||||
chips[0].fire('click', {})
|
||||
check('书签点击写锚点 url', !!anchor.attrs['data-iwb-cwv-url'] && /^https:\/\//.test(anchor.attrs['data-iwb-cwv-url']),
|
||||
anchor.attrs['data-iwb-cwv-url'])
|
||||
check('书签点击同样不开独立窗口', openCalls(r).length === 0, JSON.stringify(r.calls))
|
||||
}
|
||||
|
||||
// ---------- 面板「↗」:把当前页放到画布上(canvasWrite) ----------
|
||||
{
|
||||
const created = []
|
||||
const r = runPlugin({
|
||||
invokeImpl: okInvoke(),
|
||||
canvas: { createNode: (type, x, y, data) => { created.push({ type, x, y, data }); return 'n-1' } }
|
||||
})
|
||||
const root = mountPanel(r.panel, r.doc)
|
||||
const bar = root.children.find((c) => c.className === 'iwb-cwv-bar')
|
||||
const input = bar.children.find((c) => c.tagName === 'INPUT')
|
||||
const stage = root.children.find((c) => c.className === 'iwb-cwv-stage')
|
||||
const anchor = stage.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
|
||||
const outBtn = bar.children.find((c) => c.attrs.title && c.attrs.title.indexOf('画布上打开') >= 0)
|
||||
check('面板工具栏有「在画布上打开」按钮', !!outBtn)
|
||||
input.value = 'pinterest.com'
|
||||
input.fire('keydown', { key: 'Enter' })
|
||||
outBtn.fire('click', {})
|
||||
check('点击后创建了 web 节点', created.length === 1 && created[0].type === 'web',
|
||||
JSON.stringify(created.map((c) => c.type)))
|
||||
check('新节点带上当前网址', created.length === 1 && created[0].data.url === 'https://pinterest.com/',
|
||||
created.length ? created[0].data.url : '(无)')
|
||||
check('新节点不带 paused(默认直接加载)', created.length === 1 && created[0].data.paused === false)
|
||||
check('放到画布时不再开独立窗口', openCalls(r).length === 0, JSON.stringify(r.calls))
|
||||
}
|
||||
|
||||
// ---------- 旧宿主(没有 canvasWrite):↗ 回退独立窗口,不报错 ----------
|
||||
{
|
||||
const r = runPlugin({ invokeImpl: okInvoke() })
|
||||
const root = mountPanel(r.panel, r.doc)
|
||||
const bar = root.children.find((c) => c.className === 'iwb-cwv-bar')
|
||||
const input = bar.children.find((c) => c.tagName === 'INPUT')
|
||||
const outBtn = bar.children.find((c) => c.attrs.title && c.attrs.title.indexOf('画布上打开') >= 0)
|
||||
input.value = 'example.com'
|
||||
input.fire('keydown', { key: 'Enter' })
|
||||
let threw = false
|
||||
try { outBtn.fire('click', {}) } catch (e) { threw = true }
|
||||
check('旧宿主点 ↗ 不抛异常', !threw)
|
||||
check('旧宿主点 ↗ 退回独立窗口', openCalls(r).length === 1, JSON.stringify(r.calls.map((c) => c.name)))
|
||||
}
|
||||
|
||||
// ---------- 无 Tauri:面板仍可用(内嵌视图由客户端建,插件只写属性) ----------
|
||||
{
|
||||
const r = runPlugin() // 无 __TAURI__
|
||||
const root = mountPanel(r.panel, r.doc)
|
||||
const bar = root.children.find((c) => c.className === 'iwb-cwv-bar')
|
||||
const input = bar.children.find((c) => c.tagName === 'INPUT')
|
||||
const stage = root.children.find((c) => c.className === 'iwb-cwv-stage')
|
||||
const anchor = stage.children.find((c) => c.attrs['data-iwb-cwv'] === 'panel:browser')
|
||||
input.value = 'example.com'
|
||||
input.fire('keydown', { key: 'Enter' })
|
||||
check('无 Tauri 时地址栏仍写入锚点(不弹系统浏览器)',
|
||||
anchor.attrs['data-iwb-cwv-url'] === 'https://example.com/' && r.calls.length === 0,
|
||||
JSON.stringify(r.calls))
|
||||
}
|
||||
|
||||
// ---------- 反复 mount 不累积设置订阅 ----------
|
||||
{
|
||||
const r = runPlugin()
|
||||
mountPanel(r.panel, r.doc)
|
||||
mountPanel(r.panel, r.doc)
|
||||
mountPanel(r.panel, r.doc)
|
||||
check('重复 mount 会解掉上一个设置订阅(3 次 mount ⇒ 解绑 2 次)', r.unsubscribed === 2, '实际 ' + r.unsubscribed)
|
||||
}
|
||||
|
||||
// ---------- 书签数据层(分组 / 排序 / 兼容旧文本) ----------
|
||||
{
|
||||
const r = runPlugin()
|
||||
const spec = r.registered.settings.bookmarks
|
||||
check('书签设置声明为 custom(交给插件自己渲染)', spec.type === 'custom' && typeof spec.render === 'function')
|
||||
const api = spec.api
|
||||
check('插件暴露了书签纯函数(供 harness 断言)', !!api && typeof api.parse === 'function')
|
||||
|
||||
// 空值 ⇒ 默认书签,且落在「常用」一个分组里
|
||||
const d0 = api.parse('')
|
||||
check('空值给默认书签', d0.groups.length === 1 && d0.groups[0].items.length === 4,
|
||||
JSON.stringify(d0.groups.map((g) => g.items.length)))
|
||||
|
||||
// 旧文本(老客户端/老用户)⇒ 自动迁成分组,不丢数据
|
||||
const d1 = api.parse('MDN | developer.mozilla.org\n# 注释行\n\nOpenAI|openai.com')
|
||||
check('旧文本格式迁成一个分组', d1.groups.length === 1 && d1.groups[0].items.length === 2,
|
||||
JSON.stringify(d1.groups.map((g) => g.items.length)))
|
||||
check('迁移后自动补协议', d1.groups[0].items[0].url === 'https://developer.mozilla.org/',
|
||||
d1.groups[0].items[0].url)
|
||||
|
||||
// 新 JSON 结构
|
||||
const src = {
|
||||
v: 2,
|
||||
groups: [
|
||||
{ id: 'g1', name: '设计', items: [{ id: 'i1', title: '花瓣', url: 'huaban.com' }, { id: 'i2', title: 'Behance', url: 'https://www.behance.net/' }] },
|
||||
{ id: 'g2', name: '空组', items: [] }
|
||||
]
|
||||
}
|
||||
const d2 = api.parse(JSON.stringify(src))
|
||||
check('JSON 分组解析(保留空分组)', d2.groups.length === 2 && d2.groups[1].items.length === 0)
|
||||
check('JSON 里的地址也走 normalizeUrl', d2.groups[0].items[0].url === 'https://huaban.com/', d2.groups[0].items[0].url)
|
||||
check('按分组取书签', api.items(d2, 'g1').length === 2 && api.items(d2, 'g2').length === 0)
|
||||
check('取全部书签', api.items(d2, '').length === 2)
|
||||
|
||||
// 空地址是「没填完的草稿行」:留在设置里,但不出现在面板
|
||||
const d3 = api.normalize({ groups: [{ id: 'g', name: 'x', items: [{ id: 'a', title: '待填', url: '' }, { id: 'b', title: '有', url: 'a.com' }] }] })
|
||||
check('空地址草稿行保留在数据里', d3.groups[0].items.length === 2)
|
||||
check('空地址草稿行不进面板', api.items(d3, '').length === 1)
|
||||
|
||||
// 排序算法
|
||||
const arr = [{ id: 'a' }, { id: 'b' }, { id: 'c' }]
|
||||
check('拖动排序:前移到后', api.move(arr.slice(), 0, 2).map((x) => x.id).join('') === 'bca')
|
||||
check('拖动排序:后移到前', api.move(arr.slice(), 2, 0).map((x) => x.id).join('') === 'cab')
|
||||
check('拖动排序:越界不动', api.move(arr.slice(), 0, 9).map((x) => x.id).join('') === 'abc')
|
||||
check('stringify 后再 parse 结构不丢', api.parse(api.stringify(d2)).groups[0].items.length === 2)
|
||||
}
|
||||
|
||||
// ---------- 面板:分组 chip 切换 ----------
|
||||
{
|
||||
const r = runPlugin()
|
||||
const twoGroups = {
|
||||
v: 2,
|
||||
groups: [
|
||||
{ id: 'g1', name: '设计', items: [{ id: 'i1', title: '花瓣', url: 'huaban.com' }] },
|
||||
{ id: 'g2', name: '工具', items: [{ id: 'i2', title: 'MDN', url: 'developer.mozilla.org' }, { id: 'i3', title: 'GitHub', url: 'github.com' }] }
|
||||
]
|
||||
}
|
||||
r.setSetting('bookmarks', JSON.stringify(twoGroups))
|
||||
const root = mountPanel(r.panel, r.doc)
|
||||
const gbar = findClass(root, 'iwb-browser-groups')
|
||||
const gchips = gbar ? gbar.children.filter((c) => String(c.className).indexOf('iwb-browser-gchip') === 0) : []
|
||||
check('多分组时出现分组条(全部 + 2 组)', gchips.length === 3, '实际 ' + gchips.length)
|
||||
const strip = findClass(root, 'iwb-browser-strip')
|
||||
const countChips = () => strip.children.filter((c) => c.className === 'iwb-browser-chip').length
|
||||
check('默认显示全部书签', countChips() === 3, '实际 ' + countChips())
|
||||
gchips[2].fire('click', {})
|
||||
check('点分组只显示该组书签', countChips() === 2, '实际 ' + countChips())
|
||||
gchips[1].fire('click', {})
|
||||
check('切到另一组', countChips() === 1, '实际 ' + countChips())
|
||||
gchips[0].fire('click', {})
|
||||
check('回到「全部」', countChips() === 3, '实际 ' + countChips())
|
||||
}
|
||||
|
||||
// ---------- 面板:只有一个分组时不显示分组条 ----------
|
||||
{
|
||||
const r = runPlugin()
|
||||
const root = mountPanel(r.panel, r.doc)
|
||||
const gbar = findClass(root, 'iwb-browser-groups')
|
||||
check('单分组隐藏分组条', !!gbar && gbar.style.display === 'none')
|
||||
}
|
||||
|
||||
// ---------- 画布内网页节点 ----------
|
||||
{
|
||||
const r = runPlugin({ invokeImpl: okInvoke() })
|
||||
const nt = r.nodeType
|
||||
check('注册了画布节点类型 web', !!nt && nt.id === 'web' && nt.title === '网页')
|
||||
check('节点类型无端口(网页节点不参与连线)', JSON.stringify(nt.ports) === '{"in":false,"out":false}')
|
||||
check('节点类型默认数据含 url/zoom/paused',
|
||||
nt.defaults && 'url' in nt.defaults && nt.defaults.zoom === 1 && nt.defaults.paused === false,
|
||||
JSON.stringify(nt.defaults))
|
||||
check('节点类型带自定义渲染函数', typeof nt.render === 'function')
|
||||
|
||||
const updates = []
|
||||
const props = { onUpdate(id, patch) { updates.push({ id, patch }) } }
|
||||
const host = r.doc.createElement('div')
|
||||
const node = { id: 'n1', data: { url: '' } }
|
||||
nt.render(node, props, host)
|
||||
|
||||
check('节点体切成 flex 列布局(iwb-cwv-body)', host.classList.contains('iwb-cwv-body'))
|
||||
const bar = host.children.find((c) => c.className === 'iwb-cwv-bar')
|
||||
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
|
||||
check('节点体含工具栏与内容区', !!bar && !!stage)
|
||||
check('工具栏在内容区之前(原生视图只盖内容区,不会压住按钮)',
|
||||
host.children.indexOf(bar) === 0 && host.children.indexOf(stage) === 1)
|
||||
const anchor = stage && stage.children.find((c) => c.className === 'iwb-cwv-anchor')
|
||||
check('内容区有原生 webview 锚点', !!anchor)
|
||||
check('锚点带节点 id(宿主据此摆位置)', anchor && anchor.attrs['data-iwb-cwv'] === 'n1',
|
||||
anchor && JSON.stringify(anchor.attrs))
|
||||
check('空地址时不写锚点 url', anchor && anchor.attrs['data-iwb-cwv-url'] === undefined)
|
||||
|
||||
const input = bar.children.find((c) => c.tagName === 'INPUT')
|
||||
const navBtns = bar.children.filter((c) => c.tagName === 'BUTTON')
|
||||
check('工具栏 5 个动作按钮(← → ⟳ ↗ ✕)', navBtns.length === 5, '实际 ' + navBtns.length)
|
||||
check('地址栏初始禁用全部动作按钮', navBtns.every((b) => b.disabled === true))
|
||||
|
||||
// 缩放设定框:− [100%] +,百分比是可输入的
|
||||
const zoomBox = bar.children.find((c) => c.className === 'iwb-cwv-zoom')
|
||||
const zpct = zoomBox && zoomBox.children.find((c) => c.tagName === 'INPUT')
|
||||
const zoomBtns = zoomBox ? zoomBox.children.filter((c) => c.tagName === 'BUTTON') : []
|
||||
check('工具栏有缩放设定框「− 100% +」',
|
||||
!!zpct && zpct.value === '100%' && zoomBtns.length === 2, zpct && zpct.value)
|
||||
check('缩放框排在地址栏之后、关闭按钮之前',
|
||||
bar.children.indexOf(input) < bar.children.indexOf(zoomBox)
|
||||
&& bar.children.indexOf(zoomBox) < bar.children.indexOf(navBtns[4]))
|
||||
check('锚点默认缩放 1', anchor.attrs['data-iwb-cwv-zoom'] === '1', JSON.stringify(anchor.attrs))
|
||||
|
||||
// 输入网址回车 → 写节点数据 + 立刻更新锚点(不等 React 重渲染)
|
||||
input.value = 'baidu.com'
|
||||
input.fire('keydown', { key: 'Enter' })
|
||||
check('回车提交写回节点 data.url', updates.length === 1 && updates[0].patch.url === 'https://baidu.com/',
|
||||
JSON.stringify(updates))
|
||||
check('空标题时自动用站点名(多个网页节点才分得清)',
|
||||
updates[0] && updates[0].patch.title === 'baidu.com', JSON.stringify(updates[0] && updates[0].patch))
|
||||
check('回车后锚点 url 同步(宿主下一帧即可导航)',
|
||||
anchor.attrs['data-iwb-cwv-url'] === 'https://baidu.com/', JSON.stringify(anchor.attrs))
|
||||
check('填了网址后动作按钮启用', navBtns.every((b) => b.disabled === false))
|
||||
|
||||
// 控制按钮 → 发 canvas_webview_action(不是 browser_control)
|
||||
navBtns[0].fire('click', {})
|
||||
const acts = r.calls.filter((c) => c.name === 'canvas_webview_action')
|
||||
check('后退按钮走 canvas_webview_action(back)',
|
||||
acts.length === 1 && acts[0].args.action === 'back' && acts[0].args.id === 'n1', JSON.stringify(acts))
|
||||
|
||||
// 缩放:+ 按钮一次 +10%,并把值写回节点;锚点属性立刻更新(宿主下一帧推 zoom)
|
||||
zoomBtns[1].fire('click', {})
|
||||
check('放大按钮把缩放调到 110%', zpct.value === '110%' && anchor.attrs['data-iwb-cwv-zoom'] === '1.1',
|
||||
zpct.value + ' / ' + anchor.attrs['data-iwb-cwv-zoom'])
|
||||
check('缩放值写回节点数据', updates.some((u) => u.patch.zoom === 1.1), JSON.stringify(updates))
|
||||
zoomBtns[0].fire('click', {})
|
||||
check('缩小按钮把缩放调回 100%', zpct.value === '100%', zpct.value)
|
||||
|
||||
// 直接输入百分比
|
||||
zpct.value = '150%'
|
||||
zpct.fire('keydown', { key: 'Enter' })
|
||||
check('缩放框支持直接输入百分比', anchor.attrs['data-iwb-cwv-zoom'] === '1.5', anchor.attrs['data-iwb-cwv-zoom'])
|
||||
zpct.value = '900%'
|
||||
zpct.fire('keydown', { key: 'Enter' })
|
||||
check('缩放上限 300%', anchor.attrs['data-iwb-cwv-zoom'] === '3', anchor.attrs['data-iwb-cwv-zoom'])
|
||||
zpct.value = '10%'
|
||||
zpct.fire('keydown', { key: 'Enter' })
|
||||
check('缩放下限 25%', anchor.attrs['data-iwb-cwv-zoom'] === '0.25', anchor.attrs['data-iwb-cwv-zoom'])
|
||||
|
||||
// ✕ 暂停:写 paused 到锚点与节点数据(宿主要看到它才不会立刻重建视图)
|
||||
const closeBtn = navBtns[4]
|
||||
closeBtn.fire('click', {})
|
||||
check('✕ 把节点标记为 paused(宿主据此关掉视图并保持关闭)',
|
||||
anchor.attrs['data-iwb-cwv-paused'] === '1'
|
||||
&& updates.some((u) => u.patch.paused === true), JSON.stringify(anchor.attrs))
|
||||
check('✕ 之后给出可继续的提示', /已关闭/.test(stage.children.find((c) => c.className === 'iwb-cwv-empty')._text))
|
||||
|
||||
// 暂停态点 ⟳:恢复加载(先解除 paused,再让宿主重建)
|
||||
const beforeResume = r.calls.filter((c) => c.name === 'canvas_webview_action').length
|
||||
navBtns[2].fire('click', {})
|
||||
check('暂停态点 ⟳ 恢复加载(不向已关闭的视图发命令)',
|
||||
anchor.attrs['data-iwb-cwv-paused'] === undefined
|
||||
&& updates.some((u) => u.patch.paused === false)
|
||||
&& r.calls.filter((c) => c.name === 'canvas_webview_action').length === beforeResume,
|
||||
JSON.stringify(updates.slice(-2)))
|
||||
|
||||
// 宿主回报状态:站内跳转后的真实地址要回填地址栏,加载中 ⟳ 变成「停止」
|
||||
r.doc.dispatchEvent({ type: 'iwb-cwv-state', detail: { id: 'n1', loading: true, url: 'https://baidu.com/s?wd=x' } })
|
||||
check('站内跳转后地址栏跟着页面地址走', input.value === 'https://baidu.com/s?wd=x', input.value)
|
||||
check('加载中 ⟳ 变「停止」', navBtns[2].getAttribute('data-act') === 'stop',
|
||||
navBtns[2].getAttribute('data-act'))
|
||||
r.doc.dispatchEvent({ type: 'iwb-cwv-state', detail: { id: 'n1', loading: false, url: 'https://baidu.com/s?wd=x' } })
|
||||
check('加载完成 ⟳ 复原', navBtns[2].getAttribute('data-act') === 'reload')
|
||||
|
||||
// 重渲染不能覆盖正在编辑的输入框(否则每敲一个字都被顶回去)
|
||||
node.data.url = 'https://www.baidu.com/'
|
||||
input.value = 'zhihu.com' // 用户正在输入,还没回车
|
||||
r.doc.activeElement = input
|
||||
nt.render(node, props, host)
|
||||
check('重渲染不覆盖正在编辑的输入', input.value === 'zhihu.com', input.value)
|
||||
|
||||
// 非法地址:标红且不写数据
|
||||
r.doc.activeElement = null
|
||||
const before = updates.length
|
||||
input.value = 'javascript:alert(1)'
|
||||
input.fire('keydown', { key: 'Enter' })
|
||||
check('非法协议被拒绝且不写回', updates.length === before && input.attrs['aria-invalid'] === 'true',
|
||||
JSON.stringify(input.attrs))
|
||||
}
|
||||
|
||||
// ---------- 无 Tauri 时节点给出明确提示 ----------
|
||||
{
|
||||
const r = runPlugin()
|
||||
const nt = r.nodeType
|
||||
const host = r.doc.createElement('div')
|
||||
nt.render({ id: 'n2', data: { url: 'https://www.baidu.com/' } }, { onUpdate() {} }, host)
|
||||
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
|
||||
const empty = stage.children.find((c) => c.className === 'iwb-cwv-empty')
|
||||
check('网页版节点显示「需要桌面客户端」提示', /桌面客户端/.test(empty._text), empty._text)
|
||||
}
|
||||
|
||||
// ---------- 旧客户端(有 Tauri、但没有画布 webview 引擎)必须提示升级 ----------
|
||||
{
|
||||
const r = runPlugin({ invokeImpl: okInvoke() })
|
||||
const nt = r.nodeType
|
||||
const host = r.doc.createElement('div')
|
||||
nt.render({ id: 'n3', data: { url: 'https://www.baidu.com/' } }, { onUpdate() {} }, host)
|
||||
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
|
||||
const empty = stage.children.find((c) => c.className === 'iwb-cwv-empty')
|
||||
check('旧客户端(无 canvas-webview 引擎)提示升级而不是白屏',
|
||||
/v3\.25\.24|更新客户端/.test(empty._text), empty._text)
|
||||
}
|
||||
|
||||
console.log('\n[harness] ' + (failed === 0 ? '全部通过' : failed + ' 项失败'))
|
||||
process.exit(failed === 0 ? 0 : 1)
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "@iwb-plugin/gallery",
|
||||
"private": true,
|
||||
"version": "1.7.0",
|
||||
"description": "图库:右栏图片墙(筛选/多选/预览/插入画布/下载/删除),数据由宿主 gallery 能力提供",
|
||||
"ibwPlugin": {
|
||||
"id": "gallery",
|
||||
"entry": "src/index.js",
|
||||
"apiVersion": 1,
|
||||
"style": "styles.css"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
// iwb-plugin: 图库 —— 右栏「图库」面板(宿主只提供 ctx.gallery 数据能力,界面全部在插件里)
|
||||
//
|
||||
// 依赖客户端能力:gallery(list/thumb/preview/download/insert/remove/onChanged)+ panels。
|
||||
// 数据:插件自己的配置(插入尺寸/图幅/时间筛选)存 ctx.data,不塞 settings。
|
||||
// 视觉:复用宿主的 .iwb-gal-* / .iwb-history-* 类名(宿主 style.css 保留这些样式)。
|
||||
//
|
||||
// v1.7.0(2026-11-24):
|
||||
// ① 订阅 ctx.gallery.onChanged —— 出图途中宿主每归档一张就通知,面板立刻长出新图;
|
||||
// 此前只有「面板重新可见且距上次拉取 >5s」一个入口,而生成时面板一直可见 ⇒ 永远不刷。
|
||||
// ② 格子「插入」补 insertK(与右键/顶部一致,尺寸档不再被忽略)。
|
||||
// ③ 插入/删除补「插入中…」状态,删除改成等宿主删完再重拉(固定 250ms 会拉到未删完的清单)。
|
||||
// 注:搜索框在 v1.6.1 已按用户意见移除,不再加回。
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
if (!global.IWBPluginHost) return
|
||||
|
||||
var PANEL_ID = 'gallery-panel'
|
||||
var DEF = { insertK: '1k', tile: 110, range: '' }
|
||||
// v1.6.2:图幅=**实际显示宽度上限**(此前只当「算列数」用,独列时会被拉到撑满面板,选「小」也很大)
|
||||
// v1.6.3:新增「极小」64px 档(面板窄时想一行看更多图)
|
||||
var TILES = [[64, '极小'], [80, '小'], [110, '中'], [150, '大'], [200, '特大']]
|
||||
var KS = [['orig', '原图'], ['2k', '2K'], ['1k', '1K'], ['0.5k', '0.5K']]
|
||||
var RANGES = [['', '全部'], ['today', '今天'], ['7d', '7 天'], ['30d', '30 天']]
|
||||
|
||||
function el (tag, attrs) {
|
||||
var node = document.createElement(tag)
|
||||
if (attrs) {
|
||||
for (var k in attrs) {
|
||||
if (!Object.prototype.hasOwnProperty.call(attrs, k)) continue
|
||||
var v = attrs[k]
|
||||
if (v === null || v === undefined) continue
|
||||
if (k === 'class') node.className = v
|
||||
else if (k === 'text') node.textContent = v
|
||||
else if (k === 'style') node.setAttribute('style', v)
|
||||
else node.setAttribute(k, v)
|
||||
}
|
||||
}
|
||||
// 变参子节点(第三位起),支持数组与字符串
|
||||
for (var i = 2; i < arguments.length; i++) append(node, arguments[i])
|
||||
return node
|
||||
}
|
||||
function append (node, v) {
|
||||
if (v === null || v === undefined || v === false) return
|
||||
if (Array.isArray(v)) { for (var i = 0; i < v.length; i++) append(node, v[i]); return }
|
||||
node.appendChild(typeof v === 'string' ? document.createTextNode(v) : v)
|
||||
}
|
||||
function clear (node) { while (node.firstChild) node.removeChild(node.firstChild) }
|
||||
|
||||
// v1.4.1:底栏按钮改用图标(窄栏里「刷新/设置」会被挤成竖排两行)
|
||||
var SVG_NS = 'http://www.w3.org/2000/svg'
|
||||
function iconBtn (label, build, title) {
|
||||
var b = el('button', { class: 'iwb-btn iwb-btn-sm iwb-gal-icobtn', title: title || label, 'aria-label': label })
|
||||
var svg = document.createElementNS(SVG_NS, 'svg')
|
||||
svg.setAttribute('viewBox', '0 0 16 16')
|
||||
svg.setAttribute('width', '14')
|
||||
svg.setAttribute('height', '14')
|
||||
svg.setAttribute('fill', 'none')
|
||||
svg.setAttribute('stroke', 'currentColor')
|
||||
svg.setAttribute('stroke-width', '1.5')
|
||||
svg.setAttribute('stroke-linecap', 'round')
|
||||
svg.setAttribute('stroke-linejoin', 'round')
|
||||
svg.setAttribute('aria-hidden', 'true')
|
||||
build(svg)
|
||||
b.appendChild(svg)
|
||||
return b
|
||||
}
|
||||
function svgPath (svg, d) {
|
||||
var p = document.createElementNS(SVG_NS, 'path')
|
||||
p.setAttribute('d', d)
|
||||
svg.appendChild(p)
|
||||
return p
|
||||
}
|
||||
function sel (options, value) {
|
||||
var s = el('select', { class: 'iwb-input iwb-select-compact' })
|
||||
for (var i = 0; i < options.length; i++) {
|
||||
var o = el('option', { value: String(options[i][0]), text: options[i][1] })
|
||||
if (String(options[i][0]) === String(value)) o.selected = true
|
||||
s.appendChild(o)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
function mount (host, ctx) {
|
||||
clear(host)
|
||||
host.classList.add('iwb-plugin-node-body')
|
||||
host.style.minHeight = '0'
|
||||
|
||||
var cfg = Object.assign({}, DEF)
|
||||
var items = []
|
||||
var thumbCache = {}
|
||||
var thumbPending = {} // 进行中的缩略图请求(v1.6.9)
|
||||
var total = 0
|
||||
var limit = 100
|
||||
var picked = {}
|
||||
var gridW = 320
|
||||
var raf = 0
|
||||
var failed = {} // v1.6.0:缩略图仍失败的 name 集合(据此显示「N 张失败」+ 全部重试)
|
||||
|
||||
var head = el('div', { class: 'iwb-gal-head' })
|
||||
var actions = el('div', { class: 'iwb-gal-actions' })
|
||||
head.appendChild(actions)
|
||||
|
||||
var grid = el('div', { class: 'iwb-history-grid' })
|
||||
var empty = el('div', { class: 'iwb-hint', text: '暂无图片 · 运行生图后会出现在这里' })
|
||||
var more = el('div', { class: 'iwb-history-more' })
|
||||
// v1.1.0:底部横栏 —— 左边张数/已选,右边三个设定(右对齐)
|
||||
var countEl = el('span', { class: 'iwb-gal-count', text: '0 / 0 张' })
|
||||
var pickedEl = el('span', { class: 'iwb-gal-sel', text: '' })
|
||||
var statusEl = el('span', { class: 'iwb-gal-status', text: '' })
|
||||
var failEl = el('span', { class: 'iwb-gal-fail', text: '' })
|
||||
failEl.style.display = 'none'
|
||||
failEl.addEventListener('click', function () { retryAll() })
|
||||
var refreshBtn = iconBtn('刷新', function (svg) {
|
||||
svgPath(svg, 'M13.2 6.4A5.4 5.4 0 1 0 13.4 9.4')
|
||||
svgPath(svg, 'M13.2 2.6v3.8H9.4')
|
||||
}, '刷新:重新向宿主拉取图库(图床恢复/外部改动后点这里)')
|
||||
refreshBtn.addEventListener('click', function () { load(true) })
|
||||
// v1.4.0:三个下拉不再占用前台(窄栏放不下、也显乱)——收进「设置」浮层,点按钮才展开。
|
||||
var setBtn = iconBtn('设置', function (svg) {
|
||||
var c1 = document.createElementNS(SVG_NS, 'circle')
|
||||
c1.setAttribute('cx', '8'); c1.setAttribute('cy', '8'); c1.setAttribute('r', '4.2')
|
||||
svg.appendChild(c1)
|
||||
var c2 = document.createElementNS(SVG_NS, 'circle')
|
||||
c2.setAttribute('cx', '8'); c2.setAttribute('cy', '8'); c2.setAttribute('r', '1.6')
|
||||
svg.appendChild(c2)
|
||||
for (var i = 0; i < 8; i++) {
|
||||
var a = i * Math.PI / 4
|
||||
var x1 = (8 + Math.cos(a) * 4.2).toFixed(2)
|
||||
var y1 = (8 + Math.sin(a) * 4.2).toFixed(2)
|
||||
var x2 = (8 + Math.cos(a) * 5.6).toFixed(2)
|
||||
var y2 = (8 + Math.sin(a) * 5.6).toFixed(2)
|
||||
svgPath(svg, 'M' + x1 + ' ' + y1 + 'L' + x2 + ' ' + y2)
|
||||
}
|
||||
}, '图库设置:插入尺寸 / 图幅 / 时间范围')
|
||||
setBtn.classList.add('iwb-gal-setbtn')
|
||||
setBtn.setAttribute('aria-expanded', 'false')
|
||||
var settings = el('div', { class: 'iwb-gal-settings', role: 'dialog', 'aria-label': '图库设置' })
|
||||
settings.style.display = 'none'
|
||||
// 2026-11-24:底栏加「打开本地图库目录」图标(文件夹),放在设置图标左边;只桌面端可用。
|
||||
var folderBtn = iconBtn('打开本地目录', function (svg) {
|
||||
svgPath(svg, 'M2 4.5h4l1.5 2H14v6.5H2z')
|
||||
}, '在系统文件管理器里打开本地图库目录(images/gallery)')
|
||||
folderBtn.addEventListener('click', function (e) {
|
||||
e.stopPropagation()
|
||||
if (!ctx.gallery || typeof ctx.gallery.openFolder !== 'function') { setStatus('仅桌面端可打开本地目录'); return }
|
||||
Promise.resolve(ctx.gallery.openFolder()).then(function (r) {
|
||||
if (r && r.ok === false) setStatus('打开失败:' + ((r && r.error) || '仅桌面端可用'))
|
||||
}).catch(function (err) { setStatus('打开失败:' + ((err && err.message) || err)) })
|
||||
})
|
||||
folderBtn.style.display = (typeof window !== 'undefined' && window.__TAURI__ && window.__TAURI__.core) ? '' : 'none'
|
||||
// v1.4.2:刷新与设置同放右侧工具组(此前刷新在左侧信息区,空间不足时会向右溢出、压住设置图标)
|
||||
var tools = el('div', { class: 'iwb-gal-tools' }, refreshBtn, folderBtn, setBtn)
|
||||
var foot = el('div', { class: 'iwb-gal-foot' },
|
||||
el('div', { class: 'iwb-gal-foot-left' }, countEl, pickedEl, failEl, statusEl), tools)
|
||||
var wrap = el('div', { class: 'iwb-history-embedded' }, [head, grid, more, empty, foot, settings])
|
||||
|
||||
function setOpen (open) {
|
||||
settings.style.display = open ? '' : 'none'
|
||||
setBtn.setAttribute('aria-expanded', open ? 'true' : 'false')
|
||||
setBtn.classList.toggle('iwb-gal-setbtn-on', !!open)
|
||||
if (open) document.addEventListener('pointerdown', onDocDown, true)
|
||||
else document.removeEventListener('pointerdown', onDocDown, true)
|
||||
}
|
||||
function onDocDown (e) {
|
||||
if (settings.contains(e.target) || setBtn.contains(e.target)) return
|
||||
setOpen(false)
|
||||
}
|
||||
setBtn.addEventListener('click', function (e) { e.stopPropagation(); setOpen(settings.style.display === 'none') })
|
||||
host.appendChild(wrap)
|
||||
|
||||
function count () { return Object.keys(picked).length }
|
||||
|
||||
// ---- v1.6.0 右键菜单:单张操作(插入 / 下载 / 预览 / 复制文件名 / 删除)----
|
||||
var menuEl = null
|
||||
function closeMenu () {
|
||||
if (menuEl && menuEl.parentNode) menuEl.parentNode.removeChild(menuEl)
|
||||
menuEl = null
|
||||
document.removeEventListener('pointerdown', onMenuDown, true)
|
||||
document.removeEventListener('keydown', onMenuKey, true)
|
||||
}
|
||||
function onMenuDown (e) { if (menuEl && !menuEl.contains(e.target)) closeMenu() }
|
||||
function onMenuKey (e) { if (e.key === 'Escape') closeMenu() }
|
||||
function openMenu (e, it) {
|
||||
e.preventDefault(); e.stopPropagation()
|
||||
closeMenu()
|
||||
var menu = el('div', { class: 'iwb-ctxmenu iwb-gal-menu', style: 'left:' + e.clientX + 'px;top:' + e.clientY + 'px' })
|
||||
menu.appendChild(el('div', { class: 'iwb-ctx-title', text: it.name }))
|
||||
function item (label, fn) {
|
||||
var b = el('button', { class: 'iwb-ctx-item', text: label })
|
||||
b.addEventListener('click', function (ev) { ev.stopPropagation(); closeMenu(); fn() })
|
||||
menu.appendChild(b)
|
||||
}
|
||||
item('插入画布', function () {
|
||||
setStatus('插入中…(取本地原图 → 按插入尺寸压缩)')
|
||||
Promise.resolve(ctx.gallery.insert([it.name], { insertK: cfg.insertK || '1k' }))
|
||||
.then(function () { setStatus('已插入:' + it.name) })
|
||||
.catch(function () { setStatus('插入失败') })
|
||||
})
|
||||
item('下载', function () { doDownload([it.name]) })
|
||||
item('预览大图', function () { try { ctx.gallery.preview(it.name) } catch (err) { /* ignore */ } })
|
||||
item('复制文件名', function () {
|
||||
try {
|
||||
var p = global.navigator && global.navigator.clipboard && global.navigator.clipboard.writeText(it.name)
|
||||
if (p && p.then) p.then(function () { setStatus('已复制文件名') }).catch(function () { setStatus('复制失败(剪贴板不可用)') })
|
||||
else setStatus('复制失败(剪贴板不可用)')
|
||||
} catch (err) { setStatus('复制失败(剪贴板不可用)') }
|
||||
})
|
||||
item('删除这张', function () {
|
||||
var C = global.IWBUIConfirm
|
||||
var ask = (C && C.askOrNative) ? C.askOrNative('删除「' + it.name + '」?不可恢复。', { title: '删除图片', okText: '删除' }) : Promise.resolve(global.confirm('删除「' + it.name + '」?'))
|
||||
ask.then(function (ok) {
|
||||
if (!ok) return
|
||||
// 先本地摘掉,避免删除后还渲染一格「图片已丢失」
|
||||
items = items.filter(function (x) { return x.name !== it.name })
|
||||
total = Math.max(0, total - 1)
|
||||
delete picked[it.name]
|
||||
render()
|
||||
// v1.7.0:等宿主真的删完再重拉(旧写法固定 setTimeout 250ms,磁盘慢/多张时会拉到还没删完的清单,
|
||||
// 格子里出现「图片已丢失」,用户以为删坏了)
|
||||
return Promise.resolve(ctx.gallery.remove([it.name])).then(function () { return load() }).catch(function () {})
|
||||
}).catch(function () {})
|
||||
})
|
||||
document.body.appendChild(menu)
|
||||
menuEl = menu
|
||||
setTimeout(function () {
|
||||
document.addEventListener('pointerdown', onMenuDown, true)
|
||||
document.addEventListener('keydown', onMenuKey, true)
|
||||
}, 0)
|
||||
}
|
||||
|
||||
// ---- v1.6.0 多选拖入画布:宿主 drop 只认单张,这里在捕获阶段接管整批 ----
|
||||
// 仅当 dataTransfer 带 application/x-iwb-gallery-batch 时生效,其余拖放行为完全不变。
|
||||
function onDocDrop (e) {
|
||||
var raw = ''
|
||||
try { raw = (e.dataTransfer && e.dataTransfer.getData('application/x-iwb-gallery-batch')) || '' } catch (err) { return }
|
||||
if (!raw) return
|
||||
var names = []
|
||||
try { names = JSON.parse(raw) } catch (err) { return }
|
||||
if (!names || names.length < 2) return
|
||||
e.preventDefault(); e.stopPropagation()
|
||||
setStatus('插入中…(' + names.length + ' 张)')
|
||||
Promise.resolve(ctx.gallery.insert(names, { insertK: cfg.insertK || '1k' })).then(function (r) {
|
||||
if (r && r.ok === false) { setStatus('批量插入失败'); return }
|
||||
setStatus('已插入 ' + names.length + ' 张')
|
||||
}).catch(function () { setStatus('批量插入失败') })
|
||||
}
|
||||
document.addEventListener('drop', onDocDrop, true)
|
||||
// v1.6.0:失败计数集中在底栏;点它 = 全部重试(整墙重挂,重新向宿主取缩略图)
|
||||
function updateFail () {
|
||||
var n = Object.keys(failed).length
|
||||
if (!n) { failEl.style.display = 'none'; failEl.textContent = ''; return }
|
||||
failEl.style.display = ''
|
||||
failEl.textContent = n + ' 张失败 · 重试'
|
||||
failEl.title = '点击重新加载这 ' + n + ' 张的缩略图'
|
||||
}
|
||||
function retryAll () {
|
||||
failed = {}
|
||||
updateFail()
|
||||
setStatus('重试中…')
|
||||
render()
|
||||
}
|
||||
function pickedNames () { return Object.keys(picked) }
|
||||
|
||||
function renderHead () {
|
||||
clear(actions)
|
||||
countEl.textContent = items.length + ' / ' + total + ' 张'
|
||||
pickedEl.textContent = count() ? ('已选 ' + count()) : ''
|
||||
var n = count()
|
||||
function btn (label, title0, fn, need, danger) {
|
||||
var b = el('button', { class: 'iwb-btn iwb-btn-sm' + (danger ? ' iwb-btn-danger' : '') + (need && !n ? ' iwb-gal-off' : ''), text: label, title: need && !n ? '先选中图片' : title0 })
|
||||
b.addEventListener('click', function () { if (need && !n) return; fn() })
|
||||
return b
|
||||
}
|
||||
actions.appendChild(btn('全选', '全选当前筛选结果', function () { for (var i = 0; i < items.length; i++) picked[items[i].name] = 1; render() }))
|
||||
actions.appendChild(btn('反选', '反选当前筛选结果', function () { for (var i = 0; i < items.length; i++) { var k = items[i].name; if (picked[k]) delete picked[k]; else picked[k] = 1 } render() }))
|
||||
actions.appendChild(btn('插入', '把选中的图片插入画布(尺寸按「设置 → 插入尺寸」)', function () {
|
||||
var names = pickedNames()
|
||||
var k = cfg.insertK || '1k'
|
||||
setStatus('插入中…(' + names.length + ' 张)')
|
||||
Promise.resolve(ctx.gallery.insert(names, { insertK: k })).then(function (r) {
|
||||
if (r && r.ok === false) { setStatus('插入失败'); return }
|
||||
setStatus('已插入 ' + names.length + ' 张(' + String(k).toUpperCase() + ')')
|
||||
}).catch(function () { setStatus('插入失败') })
|
||||
}, true))
|
||||
actions.appendChild(btn('下载', '下载选中的图片', function () { doDownload(pickedNames()) }, true))
|
||||
actions.appendChild(btn('删除', '删除选中的图片(不可恢复)', function () {
|
||||
var C = global.IWBUIConfirm
|
||||
var ask = C && C.askOrNative ? C.askOrNative('删除选中的 ' + n + ' 张图片?不可恢复。', { title: '删除图片', okText: '删除' }) : Promise.resolve(global.confirm('删除选中的 ' + n + ' 张图片?'))
|
||||
var names = pickedNames()
|
||||
ask.then(function (ok) {
|
||||
if (!ok) return
|
||||
// 先本地摘掉,避免删除后还渲染一格「图片已丢失」;随后再向宿主重拉(等它删完+刷新)
|
||||
items = items.filter(function (x) { return names.indexOf(x.name) < 0 })
|
||||
total = Math.max(0, total - names.length)
|
||||
picked = {}
|
||||
render()
|
||||
return Promise.resolve(ctx.gallery.remove(names)).then(function () {
|
||||
return load() // v1.7.0:等宿主真删完再重拉(固定延时会拉到未删完的清单)
|
||||
})
|
||||
}).catch(function () {})
|
||||
}, true, true))
|
||||
|
||||
}
|
||||
|
||||
// 设置浮层内容只建一次(不随每次 render 重建,避免下拉被重置)
|
||||
function buildSettings () {
|
||||
clear(settings)
|
||||
settings.appendChild(el('div', { class: 'iwb-gal-settings-title', text: '图库设置' }))
|
||||
function row (key, options, label, hint) {
|
||||
var s = sel(options, cfg[key])
|
||||
s.title = hint || label
|
||||
s.setAttribute('aria-label', label)
|
||||
s.addEventListener('change', function () {
|
||||
cfg[key] = s.value
|
||||
saveCfg()
|
||||
if (key === 'range') { limit = 100; load() } else if (key === 'tile') render()
|
||||
})
|
||||
return el('label', { class: 'iwb-gal-setrow' }, el('span', { class: 'iwb-gal-setlabel', text: label }), s)
|
||||
}
|
||||
settings.appendChild(row('insertK', KS, '插入尺寸', '插入画布时的图片尺寸'))
|
||||
settings.appendChild(row('tile', TILES, '图幅', '图库图片显示宽度'))
|
||||
settings.appendChild(row('range', RANGES, '时间范围', '按生成时间筛选'))
|
||||
}
|
||||
|
||||
function renderGrid () {
|
||||
clear(grid)
|
||||
var gap = 6
|
||||
// 每次重排都重新量一次宽度:面板显隐/停靠栏展开时 gridW 可能是旧值,
|
||||
// 只靠 ResizeObserver 会在「变成 0 再回来」期间漏掉,导致必须拖宽度才出图。
|
||||
var liveW = availableW()
|
||||
if (liveW > 0 && Math.abs(liveW - gridW) > 1) gridW = liveW
|
||||
if (!gridW) gridW = 320
|
||||
var tileW = Math.max(40, Number(cfg.tile) || 110)
|
||||
var n = Math.max(1, Math.floor((gridW + gap) / (tileW + gap)))
|
||||
// v1.6.6:列宽 = 均分宽度(铺满面板),图幅只决定「列数」——
|
||||
// 以前 min(图幅, 均分) 会留下右侧空白,看起来像没补齐。
|
||||
var colW = Math.max(40, (gridW - gap * (n - 1)) / n)
|
||||
var cols = []
|
||||
var heights = []
|
||||
for (var c = 0; c < n; c++) { cols.push([]); heights.push(0) }
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
var it = items[i]
|
||||
var ratio = (it.w && it.h) ? (it.h / it.w) : 1
|
||||
var min = 0
|
||||
for (var j = 1; j < n; j++) if (heights[j] < heights[min]) min = j
|
||||
cols[min].push(it)
|
||||
heights[min] += colW * ratio + gap
|
||||
}
|
||||
for (var ci = 0; ci < cols.length; ci++) {
|
||||
var col = el('div', { class: 'iwb-history-col', style: 'width:' + Math.round(colW) + 'px;flex:0 0 auto' })
|
||||
for (var k = 0; k < cols[ci].length; k++) col.appendChild(itemNode(cols[ci][k]))
|
||||
grid.appendChild(col)
|
||||
}
|
||||
empty.style.display = items.length ? 'none' : ''
|
||||
clear(more)
|
||||
if (total > items.length) {
|
||||
var b = el('button', { class: 'iwb-btn iwb-btn-sm', text: '显示更多(' + (total - items.length) + ' 张)' })
|
||||
b.addEventListener('click', function () { limit += 100; load() })
|
||||
more.appendChild(b)
|
||||
}
|
||||
}
|
||||
|
||||
function itemNode (it) {
|
||||
var on = !!picked[it.name]
|
||||
var box = el('div', { class: 'iwb-history-item' + (count() ? ' iwb-history-managed' : '') + (on ? ' iwb-history-selected' : '') })
|
||||
// 缩略图是**异步**的(ctx.gallery.thumb 返回 Promise):先占位,拿到地址再挂 img。
|
||||
// v1.2.0:加载失败自动重试 2 次(图片还没落盘/临时不可读),仍失败才显示可点击重试的占位。
|
||||
box.title = it.name + '(单击单选 · Shift+单击多选 · 双击放大 · 拖到画布=参考图节点)'
|
||||
var holder = el('div', { class: 'iwb-history-missing', text: '加载中…' })
|
||||
box.appendChild(holder)
|
||||
var tries = 0
|
||||
function fail (text) {
|
||||
tries = 999
|
||||
holder.textContent = text || '缩略图加载失败(点击重试)'
|
||||
holder.style.cursor = 'pointer'
|
||||
holder.onclick = function () { failed[it.name] = 1; tries = 0; boot() }
|
||||
failed[it.name] = 1
|
||||
updateFail()
|
||||
}
|
||||
function boot () {
|
||||
if (tries >= 999) return
|
||||
holder.style.cursor = ''
|
||||
holder.onclick = null
|
||||
holder.textContent = '加载中…'
|
||||
// v1.6.9:缩略图地址按名字缓存,且进行中的请求共享同一 Promise ——
|
||||
// 重排/重测会重建 DOM,不共享就会对同一张图重复取 N 次。
|
||||
var key = it.name
|
||||
if (thumbCache[key]) { var u0 = thumbCache[key]; Promise.resolve().then(function () { paint(u0) }).catch(function () { /* ignore */ }); return }
|
||||
if (!thumbPending[key]) {
|
||||
thumbPending[key] = Promise.resolve(ctx.gallery.thumb(key)).then(function (url) {
|
||||
if (url && typeof url === 'string') thumbCache[key] = url
|
||||
delete thumbPending[key]
|
||||
return url
|
||||
}, function (e) { delete thumbPending[key]; throw e })
|
||||
}
|
||||
thumbPending[key].then(paint).catch(function () { fail('缩略图加载失败(点击重试)') })
|
||||
}
|
||||
function paint (url) {
|
||||
if (!url || typeof url !== 'string') { fail('图片已丢失'); return }
|
||||
if (!box.isConnected) return
|
||||
var img = el('img', { src: url, alt: '', loading: 'eager', draggable: 'true' })
|
||||
if (it.w && it.h) img.setAttribute('style', 'aspect-ratio:' + it.w + ' / ' + it.h)
|
||||
img.addEventListener('load', function () {
|
||||
// naturalWidth=0 说明拿到的是坏图(空 data URL / 截断文件):按失败处理,别留白块
|
||||
if (!img.naturalWidth) { tries++; if (tries <= 2) { setTimeout(boot, 400 * tries); return } if (img.parentNode === box) box.replaceChild(holder, img); fail('缩略图加载失败(点击重试)'); return }
|
||||
if (holder.parentNode === box) box.replaceChild(img, holder)
|
||||
if (failed[it.name]) { delete failed[it.name]; updateFail() }
|
||||
})
|
||||
img.addEventListener('error', function () {
|
||||
tries++
|
||||
if (tries <= 2) { setTimeout(boot, 400 * tries); return }
|
||||
if (img.parentNode === box) box.replaceChild(holder, img)
|
||||
fail('缩略图加载失败(点击重试)')
|
||||
})
|
||||
img.addEventListener('click', function (e) { pick(it.name, !!(e && e.shiftKey)) })
|
||||
img.addEventListener('dblclick', function () { ctx.gallery.preview(it.name) })
|
||||
img.addEventListener('dragstart', function (e) {
|
||||
try {
|
||||
var names = (picked[it.name] && count() > 1) ? pickedNames() : [it.name]
|
||||
e.dataTransfer.setData('application/x-iwb-localref', names[0])
|
||||
e.dataTransfer.setData('application/x-iwb-gallery-orig', names[0])
|
||||
// 多选:额外带一批名字,由本插件在 document 捕获阶段接管(宿主 drop 只认单张)
|
||||
if (names.length > 1) {
|
||||
e.dataTransfer.setData('application/x-iwb-gallery-batch', JSON.stringify(names))
|
||||
setStatus('拖动 ' + names.length + ' 张')
|
||||
}
|
||||
e.dataTransfer.effectAllowed = 'copy'
|
||||
} catch (err) { /* ignore */ }
|
||||
})
|
||||
img.style.display = 'none'
|
||||
box.appendChild(img)
|
||||
// v1.6.9:坏图/超时兜底 —— 某些坏字节既不触发 load 也不触发 error,700ms 后直接判定失败(可点击重试)
|
||||
setTimeout(function () {
|
||||
try {
|
||||
if (!img.parentNode) return
|
||||
if (img.naturalWidth > 0) return
|
||||
if (img.parentNode === box) box.replaceChild(holder, img)
|
||||
fail('缩略图加载失败(点击重试)')
|
||||
} catch (e) { /* ignore */ }
|
||||
}, 2000)
|
||||
// 加载成功后再替换占位(避免破图标 + 长 title 占满格子)
|
||||
if (img.complete && img.naturalWidth > 0) { img.style.display = ''; if (holder.parentNode === box) box.replaceChild(img, holder) }
|
||||
else if (img.complete && !img.naturalWidth) { /* 立即失败(坏图)*/ tries++; if (tries <= 2) setTimeout(boot, 400 * tries); else { if (img.parentNode === box) box.replaceChild(holder, img); fail('缩略图加载失败(点击重试)') } }
|
||||
}
|
||||
boot()
|
||||
box.addEventListener('contextmenu', function (e) { openMenu(e, it) })
|
||||
var acts = el('div', { class: 'iwb-history-actions' })
|
||||
function act (label, title, fn) {
|
||||
var b = el('button', { class: 'iwb-btn iwb-btn-sm', text: label, title: title })
|
||||
b.addEventListener('click', function (e) { e.stopPropagation(); fn() })
|
||||
return b
|
||||
}
|
||||
acts.appendChild(act('插入', '插入到画布(参考图节点 · 尺寸按「设置 → 插入尺寸」)', function () {
|
||||
// v1.7.0:格子里的「插入」此前没带 insertK,宿主按默认 1k 处理 —— 与右键菜单/顶部「插入」不一致
|
||||
setStatus('插入中…')
|
||||
ctx.gallery.insert([it.name], { insertK: cfg.insertK || '1k' }).then(function () {
|
||||
setStatus('已插入:' + it.name)
|
||||
}).catch(function () { setStatus('插入失败') })
|
||||
}))
|
||||
acts.appendChild(act('下载', '下载到本地', function () { doDownload([it.name]) }))
|
||||
box.appendChild(acts)
|
||||
return box
|
||||
}
|
||||
|
||||
var statusTimer = 0
|
||||
function setStatus (text) {
|
||||
statusEl.textContent = text || ''
|
||||
clearTimeout(statusTimer)
|
||||
if (text) statusTimer = setTimeout(function () { statusEl.textContent = '' }, 4000)
|
||||
}
|
||||
function doDownload (names) {
|
||||
setStatus('下载中…')
|
||||
return Promise.resolve(ctx.gallery.download(names)).then(function (r) {
|
||||
var failed = (r && r.failed) || []
|
||||
var ok = (r && r.count) || 0
|
||||
if (failed.length) setStatus(failed.length + ' 张下载失败,可再点一次重试')
|
||||
else setStatus(ok ? ('已下载 ' + ok + ' 张') : '没有可下载的图片')
|
||||
}).catch(function () { setStatus('下载失败,可再点一次重试') })
|
||||
}
|
||||
|
||||
function pick (name, shift) {
|
||||
if (shift) { if (picked[name]) delete picked[name]; else picked[name] = 1 } else { picked = {}; picked[name] = 1 }
|
||||
render()
|
||||
}
|
||||
|
||||
function render () { renderHead(); renderGrid(); global.requestAnimationFrame(function () { try { measure() } catch (e) {} }); setTimeout(function () { try { measure() } catch (e) {} }, 150) }
|
||||
|
||||
function load (force) {
|
||||
if (force) setStatus('刷新中…')
|
||||
return Promise.resolve(ctx.gallery.list({ range: cfg.range, limit: limit })).then(function (r) {
|
||||
items = (r && r.items) || []
|
||||
total = (r && r.total) || items.length
|
||||
lastLoadAt = Date.now()
|
||||
failed = {}
|
||||
render()
|
||||
}).catch(function () { items = []; total = 0; render() })
|
||||
}
|
||||
|
||||
var saveTimer = 0
|
||||
function saveCfg () {
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(function () {
|
||||
try { var p = ctx.data && ctx.data.patch({ cfg: cfg }); if (p && p.catch) p.catch(function () {}) } catch (e) { /* 配置存不下不影响使用 */ }
|
||||
}, 200)
|
||||
}
|
||||
|
||||
// 宽度测量:列数只由「面板宽 / 图幅」决定
|
||||
// v1.6.5:面板刚挂载时 grid 宽度可能是 0,而 grid 宽度又取决于列宽 → RO 不会触发,图库一直空白。
|
||||
function availableW () {
|
||||
// v1.6.6:优先量「会随面板拉伸的外层容器」,而不是 grid 自身
|
||||
// (grid 现在是 flex-start + 内容宽度,面板变宽它不会变宽 → RO 不触发 → 列数永不补齐)
|
||||
var w = wrap ? wrap.clientWidth : 0
|
||||
if (!w && wrap && wrap.parentNode) w = wrap.parentNode.clientWidth
|
||||
if (!w) w = grid.clientWidth
|
||||
return w || 0
|
||||
}
|
||||
function measure () {
|
||||
var w = availableW()
|
||||
if (w > 0 && Math.abs(w - gridW) > 1) { gridW = w; renderGrid() }
|
||||
}
|
||||
var ro = typeof ResizeObserver === 'function' ? new ResizeObserver(function () { measure() }) : null
|
||||
if (ro) { if (wrap) ro.observe(wrap); if (wrap && wrap.parentNode) ro.observe(wrap.parentNode); ro.observe(grid) }
|
||||
measure()
|
||||
var tries = 0
|
||||
function retry () {
|
||||
if (gridW > 0 || tries++ > 40) { if (gridW <= 0) { gridW = Math.max(160, Number(cfg.tile) || 110) * 2; renderGrid() } return }
|
||||
measure()
|
||||
if (gridW <= 0) global.requestAnimationFrame(retry)
|
||||
}
|
||||
global.requestAnimationFrame(retry)
|
||||
// v1.6.7:再补几次延时重测(停靠栏展开动画、首帧布局未完成时能在 1s 内自愈)
|
||||
;[120, 400, 900].forEach(function (ms) { setTimeout(function () { try { measure(); if (gridW > 0) renderGrid() } catch (e) { /* ignore */ } }, ms) })
|
||||
|
||||
// v1.3.0:自动恢复 —— 面板重新可见(切回 tab / 窗口聚焦 / 后台回来)且距上次拉取 >5s 时重拉一次,
|
||||
// 这样图床恢复、后台补图后不必手动刷新;同时保留底部「刷新」按钮做即时重试。
|
||||
// v1.7.0:这只是**兜底**。主通道改成宿主主动通知(下面 onChanged)—— 生成途中面板一直是可见的,
|
||||
// 靠「可见性变化」触发永远等不到,用户看到的就是「生图完成但图库没图」。
|
||||
var lastLoadAt = 0
|
||||
var autoRefresh = function () {
|
||||
if (Date.now() - lastLoadAt < 5000) return
|
||||
load()
|
||||
}
|
||||
var unsubChanged = null
|
||||
var changedTimer = 0
|
||||
try {
|
||||
var G = ctx.gallery
|
||||
if (G && typeof G.onChanged === 'function') {
|
||||
unsubChanged = G.onChanged(function () {
|
||||
// 合并同一批的连续通知(一张图会触发「归档完成」一次),260ms 内只重拉一次
|
||||
clearTimeout(changedTimer)
|
||||
changedTimer = setTimeout(function () { load() }, 260)
|
||||
})
|
||||
}
|
||||
} catch (e) { /* 旧宿主没有 onChanged:退回可见性刷新 + 手动刷新 */ }
|
||||
try {
|
||||
if (typeof IntersectionObserver === 'function') {
|
||||
var io = new IntersectionObserver(function (entries) {
|
||||
for (var i = 0; i < entries.length; i++) {
|
||||
if (entries[i].isIntersecting) {
|
||||
// v1.6.7:面板真正可见后再量一次宽度并重排(首帧可能还是 0 宽)
|
||||
try { measure(); renderGrid() } catch (e) { /* ignore */ }
|
||||
autoRefresh()
|
||||
}
|
||||
}
|
||||
}, { threshold: 0.15 })
|
||||
io.observe(wrap)
|
||||
}
|
||||
document.addEventListener('visibilitychange', function () { if (!document.hidden) autoRefresh() })
|
||||
window.addEventListener('focus', autoRefresh)
|
||||
} catch (e) { /* 环境不支持则只保留手动刷新 */ }
|
||||
|
||||
// 先读配置,再拉列表
|
||||
Promise.resolve(ctx.data && ctx.data.read ? ctx.data.read() : {}).then(function (d) {
|
||||
if (d && d.cfg) cfg = Object.assign({}, DEF, d.cfg)
|
||||
buildSettings() // 设置浮层里的下拉要反映读到的配置
|
||||
return load()
|
||||
}).catch(function () { buildSettings(); load() })
|
||||
|
||||
return function dispose () {
|
||||
if (ro) { try { ro.disconnect() } catch (e) { /* ignore */ } }
|
||||
clearTimeout(changedTimer)
|
||||
try { if (typeof unsubChanged === 'function') unsubChanged() } catch (e) { /* ignore */ }
|
||||
try { document.removeEventListener('pointerdown', onMenuDown, true) } catch (e) { /* ignore */ }
|
||||
try { document.removeEventListener('keydown', onMenuKey, true) } catch (e) { /* ignore */ }
|
||||
try { document.removeEventListener('drop', onDocDrop, true) } catch (e) { /* ignore */ }
|
||||
closeMenu()
|
||||
}
|
||||
}
|
||||
|
||||
global.IWBPluginHost.register({
|
||||
id: 'gallery',
|
||||
name: '图库',
|
||||
version: '1.7.0',
|
||||
apiVersion: 1,
|
||||
capabilities: ['panels', 'gallery'],
|
||||
data: { schemaVersion: 1, maxBytes: 65536 },
|
||||
}, function (ctx) {
|
||||
ctx.ui.registerPanel({
|
||||
id: PANEL_ID,
|
||||
title: '图库',
|
||||
icon: 'ref',
|
||||
mount: function (host) { return mount(host, ctx) },
|
||||
})
|
||||
return {}
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -0,0 +1,79 @@
|
||||
/* 图库插件样式(v1.5.0)
|
||||
* 为什么放插件里:宿主 style.css 只在客户端发版时更新,而这里是「设置浮层/图标按钮/紧凑间距」这类
|
||||
* 高频视觉调整——随插件更新即可生效,不必重发桌面端。选择器均带 .iwb-gal-* / .iwb-history-* 前缀,
|
||||
* 且比宿主同名规则更具体(.iwb-gal-foot .iwb-gal-icobtn),宿主旧样式不会盖回来。
|
||||
*/
|
||||
|
||||
/* ---- 面板留白:边缘收小,避免窄栏里浪费空间 ---- */
|
||||
.iwb-history-embedded { padding: 6px 6px 4px; gap: 6px; }
|
||||
.iwb-history-embedded .iwb-history-grid { gap: 6px; padding: 0 0 2px; justify-content: flex-start; }
|
||||
/* 列宽由插件按「图幅」写死(style width),这里禁用宿主的 flex:1 拉伸 */
|
||||
.iwb-history-embedded .iwb-history-col { flex: 0 0 auto; gap: 6px; }
|
||||
|
||||
/* ---- 顶栏 ---- */
|
||||
.iwb-gal-head { display: flex; align-items: center; gap: 6px; min-height: 0; }
|
||||
.iwb-gal-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
|
||||
.iwb-gal-actions .iwb-btn-sm { padding: 2px 6px; }
|
||||
|
||||
/* ---- 底栏:左信息 / 右工具组 ---- */
|
||||
.iwb-gal-foot {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 6px;
|
||||
min-width: 0; padding-top: 6px; border-top: 1px solid var(--iwb-border);
|
||||
}
|
||||
.iwb-gal-foot-left { display: flex; align-items: center; gap: 6px; min-width: 0; flex: 0 1 auto; overflow: hidden; }
|
||||
.iwb-gal-count { font-size: 11px; color: var(--iwb-text2); white-space: nowrap; }
|
||||
.iwb-gal-sel { font-size: 11px; color: var(--iwb-brand); white-space: nowrap; }
|
||||
.iwb-gal-status { font-size: 11px; color: var(--iwb-text2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 0 1 auto; max-width: none; }
|
||||
.iwb-gal-tools { display: flex; align-items: center; gap: 0; flex: 0 0 auto; margin-left: auto; }
|
||||
|
||||
/* ---- 图标按钮:无外框、无底色,只在悬停时给一点反馈 ---- */
|
||||
.iwb-gal-foot .iwb-gal-icobtn,
|
||||
.iwb-gal-foot .iwb-gal-icobtn:hover,
|
||||
.iwb-gal-foot .iwb-gal-icobtn:active {
|
||||
width: 20px; height: 20px; min-width: 20px; padding: 0; box-sizing: border-box;
|
||||
display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto;
|
||||
border: 0; box-shadow: none; background: transparent; border-radius: 6px;
|
||||
color: var(--iwb-text2); line-height: 1; transform: none;
|
||||
}
|
||||
.iwb-gal-foot .iwb-gal-icobtn svg { display: block; pointer-events: none; }
|
||||
.iwb-gal-foot .iwb-gal-icobtn:hover { background: var(--iwb-layer2); color: var(--iwb-text); }
|
||||
.iwb-gal-foot .iwb-gal-icobtn:focus-visible { outline: 2px solid color-mix(in srgb, var(--iwb-brand) 60%, transparent); outline-offset: 1px; }
|
||||
.iwb-gal-setbtn-on { color: var(--iwb-brand); background: var(--iwb-layer2); }
|
||||
|
||||
/* ---- 设置浮层(三个下拉不占前台) ---- */
|
||||
.iwb-gal-settings {
|
||||
position: absolute; right: 8px; bottom: 34px; z-index: 30; width: 176px; max-width: calc(100% - 16px);
|
||||
display: flex; flex-direction: column; gap: 8px; padding: 8px 10px;
|
||||
background: var(--iwb-layer); border: 1px solid var(--iwb-border); border-radius: 8px;
|
||||
box-shadow: 0 6px 18px rgba(0, 0, 0, .14);
|
||||
}
|
||||
.iwb-gal-settings-title { font-size: 11px; font-weight: 600; color: var(--iwb-text2); }
|
||||
.iwb-gal-setrow { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 11px; color: var(--iwb-text2); }
|
||||
.iwb-gal-setlabel { flex: 0 0 auto; }
|
||||
.iwb-gal-setrow select { flex: 1 1 auto; width: auto; min-width: 58px; max-width: 92px; height: 22px; font-size: 11px; padding: 0 2px 0 4px; }
|
||||
|
||||
/* ---- 图片墙 ---- */
|
||||
.iwb-history-grid { overscroll-behavior: contain; }
|
||||
.iwb-history-embedded .iwb-history-item { position: relative; flex: none; width: 100%; }
|
||||
.iwb-history-embedded .iwb-history-item img {
|
||||
width: 100%; height: auto; display: block; object-fit: contain; margin: 0 auto;
|
||||
border-radius: 6px; border: 1px solid var(--iwb-border); background: var(--iwb-layer2); cursor: pointer;
|
||||
}
|
||||
.iwb-history-missing {
|
||||
display: flex; align-items: center; justify-content: center; text-align: center;
|
||||
min-height: 84px; padding: 8px; border-radius: 6px; border: 1px dashed var(--iwb-border);
|
||||
font-size: 11px; color: var(--iwb-text2); background: var(--iwb-layer2); word-break: break-all;
|
||||
}
|
||||
.iwb-history-actions { display: flex; gap: 4px; padding: 4px 2px 0; }
|
||||
.iwb-history-actions .iwb-btn-sm { padding: 2px 6px; font-size: 11px; }
|
||||
.iwb-history-more { display: flex; justify-content: center; padding: 4px 0 2px; }
|
||||
/* 只作用于图库自己的空态提示:不加前缀会泄漏到设置页等使用 .iwb-hint 的地方(文字被居中) */
|
||||
.iwb-history-embedded .iwb-hint { font-size: 11px; color: var(--iwb-text2); text-align: center; padding: 12px 6px; }
|
||||
/* ---- v1.6.0:失败统计 / 右键菜单标题(v1.6.1 去掉搜索框)---- */
|
||||
.iwb-gal-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
|
||||
.iwb-gal-fail {
|
||||
font-size: 11px; color: var(--iwb-err); cursor: pointer; white-space: nowrap;
|
||||
text-decoration: underline dotted; text-underline-offset: 2px;
|
||||
}
|
||||
.iwb-gal-fail:hover { color: var(--iwb-err); opacity: .85; }
|
||||
.iwb-gal-menu .iwb-ctx-title { max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "@iwb-plugin/grouplib",
|
||||
"private": true,
|
||||
"version": "1.0.5",
|
||||
"description": "节点组:左栏收藏的节点组列表(分组/改名/删除/拖入画布实例化),数据由宿主 grouplib 能力提供",
|
||||
"ibwPlugin": {
|
||||
"id": "grouplib",
|
||||
"entry": "src/index.js",
|
||||
"apiVersion": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
// iwb-plugin: 节点组库 —— 左侧「节点组」面板(宿主只提供 ctx.grouplib 数据能力,界面全部在插件里)
|
||||
//
|
||||
// 依赖客户端能力:grouplib(list/save/remove/instantiate/notify/onChanged)+ panels。
|
||||
// 数据仍在宿主持有(收藏的节点组快照 + 分组),插件不存副本,避免两份真相。
|
||||
// 视觉:复用宿主 .iwb-lib-* / .iwb-pcard / .iwb-chip / .iwb-gmgr-* 类名(style.css 已有)。
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
if (!global.IWBPluginHost) return
|
||||
|
||||
var PANEL_ID = 'grouplib-panel'
|
||||
|
||||
function el (tag, attrs) {
|
||||
var node = document.createElement(tag)
|
||||
if (attrs) {
|
||||
for (var k in attrs) {
|
||||
if (!Object.prototype.hasOwnProperty.call(attrs, k)) continue
|
||||
var v = attrs[k]
|
||||
if (v === null || v === undefined) continue
|
||||
if (k === 'class') node.className = v
|
||||
else if (k === 'text') node.textContent = v
|
||||
else if (k === 'style') node.setAttribute('style', v)
|
||||
else node.setAttribute(k, v)
|
||||
}
|
||||
}
|
||||
for (var i = 2; i < arguments.length; i++) append(node, arguments[i])
|
||||
return node
|
||||
}
|
||||
function append (node, v) {
|
||||
if (v === null || v === undefined || v === false) return
|
||||
if (Array.isArray(v)) { for (var i = 0; i < v.length; i++) append(node, v[i]); return }
|
||||
node.appendChild(typeof v === 'string' ? document.createTextNode(v) : v)
|
||||
}
|
||||
function clear (node) { while (node.firstChild) node.removeChild(node.firstChild) }
|
||||
|
||||
function ask (text, opts) {
|
||||
var C = global.IWBUIConfirm
|
||||
if (C && typeof C.askOrNative === 'function') return C.askOrNative(text, opts)
|
||||
return Promise.resolve(global.confirm(String(text)))
|
||||
}
|
||||
|
||||
function mount (host, ctx) {
|
||||
clear(host)
|
||||
host.classList.add('iwb-plugin-node-body')
|
||||
host.style.minHeight = '0'
|
||||
|
||||
var list = [] // [{id, name, group, ...snapshot}]
|
||||
var ggroups = [] // [{id, name}]
|
||||
var filter = 'all'
|
||||
var manage = false
|
||||
var picked = {} // id -> 1(管理模式多选)
|
||||
var editing = '' // 正在改名的 id
|
||||
var newOpen = false
|
||||
var managerOpen = false
|
||||
|
||||
var api = ctx.grouplib || {}
|
||||
|
||||
function notify (text, type) { try { api.notify && api.notify(text, type || 'ok') } catch (e) { /* ignore */ } }
|
||||
function groupsOf () {
|
||||
if (ggroups && ggroups.length) return ggroups
|
||||
var seen = []
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
var g = String((list[i] && list[i].group) || '').trim()
|
||||
if (g && !seen.some(function (x) { return x.name === g })) seen.push({ id: g, name: g })
|
||||
}
|
||||
return seen
|
||||
}
|
||||
function save (next, nextGroups) {
|
||||
var groups = next || list
|
||||
var gs = nextGroups || groupsOf()
|
||||
list = groups
|
||||
ggroups = gs
|
||||
render()
|
||||
return Promise.resolve(api.save({ groups: groups, groupGroups: gs })).then(function (r) {
|
||||
if (r && r.ok === false) { notify(r.error || '节点组保存失败,请重试', 'err'); return r }
|
||||
return r || { ok: true }
|
||||
}).catch(function () { notify('节点组保存失败,请重试', 'err') })
|
||||
}
|
||||
|
||||
var body = el('div', { class: 'iwb-lib-body' })
|
||||
var fixed = el('div', { class: 'iwb-lib-fixed' })
|
||||
var scrollBox = el('div', { class: 'iwb-lib-scroll' })
|
||||
var wrap = el('div', { class: 'iwb-groups-embedded' }, body)
|
||||
body.appendChild(fixed)
|
||||
body.appendChild(scrollBox)
|
||||
host.appendChild(wrap)
|
||||
|
||||
var loadError = '' // '' = 正常;否则是给用户看的原因(据此区分「真没收藏」和「能力没拿到」)
|
||||
function load () {
|
||||
if (typeof api.list !== 'function') {
|
||||
loadError = '节点组能力未就绪(客户端需 ≥ 3.25.56)'
|
||||
list = []; ggroups = []
|
||||
render()
|
||||
return Promise.resolve(false)
|
||||
}
|
||||
return Promise.resolve(api.list()).then(function (r) {
|
||||
loadError = ''
|
||||
list = (r && r.groups) || []
|
||||
ggroups = (r && r.groupGroups) || []
|
||||
render()
|
||||
return true
|
||||
}).catch(function (e) {
|
||||
loadError = '读取失败:' + ((e && e.message) || e || '未知错误')
|
||||
list = []; ggroups = []
|
||||
render()
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
function countOf (name) {
|
||||
if (name === 'all') return list.length
|
||||
if (name === '__none__') return list.filter(function (g) { return !String((g && g.group) || '').trim() }).length
|
||||
return list.filter(function (g) { return (g && g.group) === name }).length
|
||||
}
|
||||
function visible () {
|
||||
if (filter === '__none__') return list.filter(function (g) { return !String((g && g.group) || '').trim() })
|
||||
if (filter !== 'all') return list.filter(function (g) { return (g && g.group) === filter })
|
||||
return list.slice()
|
||||
}
|
||||
|
||||
function assignGroup (ids, group) {
|
||||
return save(list.map(function (x) { return ids.indexOf(x.id) >= 0 ? Object.assign({}, x, { group: group || '' }) : x }))
|
||||
.then(function () { notify('已移动到' + (group || '未分组')) })
|
||||
}
|
||||
|
||||
function openMenu (e, g) {
|
||||
e.preventDefault(); e.stopPropagation()
|
||||
closeMenu()
|
||||
var menu = el('div', { class: 'iwb-ctxmenu iwb-lib-group-menu', style: 'left:' + e.clientX + 'px;top:' + e.clientY + 'px' })
|
||||
menu.appendChild(el('div', { class: 'iwb-ctx-title', text: '移动到分组' }))
|
||||
var mk = function (label, value) {
|
||||
var b = el('button', { class: 'iwb-ctx-item', text: label })
|
||||
b.addEventListener('click', function () { closeMenu(); assignGroup([g.id], value) })
|
||||
menu.appendChild(b)
|
||||
}
|
||||
mk('未分组', '')
|
||||
groupsOf().forEach(function (gr) { mk(gr.name, gr.name) })
|
||||
document.body.appendChild(menu)
|
||||
menu._iwbOwner = wrap
|
||||
setTimeout(function () { document.addEventListener('pointerdown', onDocDown, true) }, 0)
|
||||
}
|
||||
var openMenuEl = null
|
||||
function closeMenu () {
|
||||
if (openMenuEl && openMenuEl.parentNode) openMenuEl.parentNode.removeChild(openMenuEl)
|
||||
openMenuEl = null
|
||||
document.removeEventListener('pointerdown', onDocDown, true)
|
||||
var old = document.querySelector('.iwb-lib-group-menu')
|
||||
if (old && old.parentNode) old.parentNode.removeChild(old)
|
||||
}
|
||||
function onDocDown (e) {
|
||||
var m = document.querySelector('.iwb-lib-group-menu')
|
||||
if (m && m.contains(e.target)) return
|
||||
closeMenu()
|
||||
}
|
||||
|
||||
// ---- 分组管理弹窗 ----
|
||||
var modalHost = null
|
||||
function openManager () {
|
||||
closeManager()
|
||||
managerOpen = true
|
||||
var mask = el('div', { class: 'iwb-modal-mask' })
|
||||
var modal = el('div', { class: 'iwb-modal iwb-modal-sm' })
|
||||
var head = el('div', { class: 'iwb-modal-head' })
|
||||
var title = el('span', { class: 'iwb-toolbar-title' })
|
||||
var closeBtn = el('button', { class: 'iwb-btn iwb-btn-sm', title: '关闭', text: '✕' })
|
||||
closeBtn.addEventListener('click', closeManager)
|
||||
head.appendChild(title); head.appendChild(closeBtn)
|
||||
var bodyEl = el('div', { class: 'iwb-modal-body' })
|
||||
modal.appendChild(head); modal.appendChild(bodyEl)
|
||||
mask.appendChild(modal)
|
||||
mask.addEventListener('wheel', function (e) { e.stopPropagation() })
|
||||
mask.addEventListener('pointerdown', function (e) { if (e.target === mask) closeManager() })
|
||||
document.body.appendChild(mask)
|
||||
modalHost = mask
|
||||
renderManager(title, bodyEl)
|
||||
}
|
||||
function closeManager () {
|
||||
managerOpen = false
|
||||
if (modalHost && modalHost.parentNode) modalHost.parentNode.removeChild(modalHost)
|
||||
modalHost = null
|
||||
render()
|
||||
}
|
||||
function renderManager (title, bodyEl) {
|
||||
var gs = groupsOf()
|
||||
title.textContent = '管理节点组分组(' + gs.length + ')'
|
||||
clear(bodyEl)
|
||||
if (!gs.length) bodyEl.appendChild(el('div', { class: 'iwb-hint', text: '暂无分组。可在下方新建。' }))
|
||||
gs.forEach(function (g, i) {
|
||||
var row = el('div', { class: 'iwb-gmgr-row' })
|
||||
var nameEl = el('span', { class: 'iwb-gmgr-name', text: g.name })
|
||||
row.appendChild(nameEl)
|
||||
row.appendChild(el('span', { class: 'iwb-gmgr-count', text: countOf(g.name) + ' 组' }))
|
||||
var rn = el('button', { class: 'iwb-btn iwb-btn-sm', title: '重命名', text: '重命名' })
|
||||
rn.addEventListener('click', function () {
|
||||
var input = el('input', { class: 'iwb-input iwb-grow', value: g.name })
|
||||
row.replaceChild(input, nameEl)
|
||||
input.focus(); input.select()
|
||||
var commit = function () {
|
||||
var n = String(input.value || '').trim()
|
||||
if (!n || n === g.name) { renderManager(title, bodyEl); return }
|
||||
if (groupsOf().some(function (x) { return x.name === n })) { renderManager(title, bodyEl); return }
|
||||
var ng = groupsOf().map(function (x) { return x.name === g.name ? { id: n, name: n } : x })
|
||||
var nl = list.map(function (x) { return x.group === g.name ? Object.assign({}, x, { group: n }) : x })
|
||||
if (filter === g.name) filter = n
|
||||
save(nl, ng).then(function () { if (managerOpen) openManager() })
|
||||
}
|
||||
input.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') { e.preventDefault(); commit() }
|
||||
if (e.key === 'Escape') renderManager(title, bodyEl)
|
||||
})
|
||||
input.addEventListener('blur', commit)
|
||||
})
|
||||
row.appendChild(rn)
|
||||
var up = el('button', { class: 'iwb-btn iwb-btn-sm', title: '上移', text: '↑' })
|
||||
up.disabled = i === 0
|
||||
up.addEventListener('click', function () { swap(i, -1) })
|
||||
row.appendChild(up)
|
||||
var down = el('button', { class: 'iwb-btn iwb-btn-sm', title: '下移', text: '↓' })
|
||||
down.disabled = i === gs.length - 1
|
||||
down.addEventListener('click', function () { swap(i, 1) })
|
||||
row.appendChild(down)
|
||||
var del = el('button', { class: 'iwb-btn iwb-btn-sm iwb-btn-danger', title: '删除分组(组内节点组移至未分组)', text: '删除' })
|
||||
del.addEventListener('click', function () {
|
||||
ask('删除节点组分组「' + g.name + '」?组内节点组将移至「未分组」(不删除节点组)。', { title: '删除分组', okText: '删除' }).then(function (ok) {
|
||||
if (!ok) return
|
||||
var ng = groupsOf().filter(function (x) { return x.name !== g.name })
|
||||
var nl = list.map(function (x) { return x.group === g.name ? Object.assign({}, x, { group: '' }) : x })
|
||||
if (filter === g.name) filter = 'all'
|
||||
save(nl, ng).then(function () { if (managerOpen) openManager() })
|
||||
})
|
||||
})
|
||||
row.appendChild(del)
|
||||
bodyEl.appendChild(row)
|
||||
})
|
||||
var addRow = el('div', { class: 'iwb-row' })
|
||||
var input = el('input', { class: 'iwb-input iwb-grow', placeholder: '新分组名称' })
|
||||
var addBtn = el('button', { class: 'iwb-btn', text: '+ 添加' })
|
||||
var doAdd = function () {
|
||||
var n = String(input.value || '').trim()
|
||||
if (!n) return
|
||||
if (groupsOf().some(function (x) { return x.name === n })) { input.value = ''; return }
|
||||
input.value = ''
|
||||
save(list, groupsOf().concat([{ id: n, name: n }])).then(function () { if (managerOpen) openManager() })
|
||||
}
|
||||
input.addEventListener('keydown', function (e) { if (e.key === 'Enter') doAdd() })
|
||||
addBtn.addEventListener('click', doAdd)
|
||||
addRow.appendChild(input); addRow.appendChild(addBtn)
|
||||
bodyEl.appendChild(addRow)
|
||||
}
|
||||
function swap (i, dir) {
|
||||
var gs = groupsOf().slice()
|
||||
var ni = i + dir
|
||||
if (ni < 0 || ni >= gs.length) return
|
||||
var t = gs[i]; gs[i] = gs[ni]; gs[ni] = t
|
||||
save(list, gs).then(function () { if (managerOpen) openManager() })
|
||||
}
|
||||
|
||||
// ---- 渲染 ----
|
||||
function render () {
|
||||
clear(fixed); clear(scrollBox)
|
||||
var gs = groupsOf()
|
||||
|
||||
var topRow = el('div', { class: 'iwb-row' })
|
||||
var mgBtn = el('button', { class: 'iwb-btn iwb-btn-sm' + (manage ? ' iwb-btn-primary' : ''), text: manage ? '退出管理' : '管理' })
|
||||
mgBtn.addEventListener('click', function () { manage = !manage; picked = {}; render() })
|
||||
topRow.appendChild(mgBtn)
|
||||
var refresh = el('button', { class: 'iwb-btn iwb-btn-sm', title: '重新向宿主拉取节点组', text: '↻' })
|
||||
refresh.addEventListener('click', function () { load() })
|
||||
topRow.appendChild(refresh)
|
||||
if (manage && Object.keys(picked).length) {
|
||||
var mv = el('select', { class: 'iwb-input' })
|
||||
mv.appendChild(el('option', { value: '__move__', text: '移动到分组…' }))
|
||||
mv.appendChild(el('option', { value: '', text: '未分组' }))
|
||||
gs.forEach(function (g) { mv.appendChild(el('option', { value: g.name, text: g.name })) })
|
||||
mv.addEventListener('change', function () {
|
||||
if (mv.value === '__move__') return
|
||||
var ids = Object.keys(picked)
|
||||
picked = {}
|
||||
assignGroup(ids, mv.value)
|
||||
})
|
||||
topRow.appendChild(mv)
|
||||
}
|
||||
fixed.appendChild(topRow)
|
||||
|
||||
// 分类胶囊:宿主 .iwb-lib-chips 是 nowrap(配 .iwb-lib-chips-scroll 才单行滚动),
|
||||
// 分组多时右侧胶囊会被面板宽度裁掉看不见 ⇒ 这里改成「适应面板宽度自动换行」,
|
||||
// 换行规则在插件自带 styles.css 的 .iwb-glp-chips 里(样式随插件发,不用等客户端发版)
|
||||
var chips = el('div', { class: 'iwb-lib-chips iwb-glp-chips' })
|
||||
function chip (label, value, count, extra) {
|
||||
var b = el('button', { class: 'iwb-chip' + (filter === value ? ' iwb-chip-active' : '') + (extra || ''), title: value === '__none__' ? '未分组;拖拽节点组卡片到此 = 移出分组' : (value === 'all' ? '' : '拖拽节点组卡片到此 = 移动到该分组') })
|
||||
b.appendChild(document.createTextNode(label))
|
||||
b.appendChild(el('span', { class: 'iwb-chip-count', text: String(count) }))
|
||||
b.addEventListener('click', function () { newOpen = false; filter = value; render() })
|
||||
b.addEventListener('dragover', function (e) { e.preventDefault(); e.stopPropagation() })
|
||||
b.addEventListener('drop', function (e) {
|
||||
e.preventDefault(); e.stopPropagation()
|
||||
var gid = e.dataTransfer && e.dataTransfer.getData('application/x-iwb-groupid')
|
||||
if (!gid) return
|
||||
assignGroup([gid], value === 'all' || value === '__none__' ? '' : value)
|
||||
})
|
||||
return b
|
||||
}
|
||||
chips.appendChild(chip('全部', 'all', list.length))
|
||||
chips.appendChild(chip('未分组', '__none__', countOf('__none__'), ' iwb-chip-drop'))
|
||||
gs.forEach(function (g) { chips.appendChild(chip(g.name, g.name, countOf(g.name), ' iwb-chip-drop')) })
|
||||
var addChip = el('button', { class: 'iwb-chip iwb-glp-add iwb-chip-add', title: '新建分组', text: '+' })
|
||||
addChip.addEventListener('click', function () { newOpen = !newOpen; render() })
|
||||
chips.appendChild(addChip)
|
||||
var mgChip = el('button', { class: 'iwb-chip iwb-glp-add iwb-chip-add', title: '管理分组(重命名 / 排序 / 删除)', text: '⚙' })
|
||||
mgChip.addEventListener('click', openManager)
|
||||
chips.appendChild(mgChip)
|
||||
fixed.appendChild(chips)
|
||||
|
||||
if (newOpen) {
|
||||
var row = el('div', { class: 'iwb-row' })
|
||||
var inp = el('input', { class: 'iwb-input iwb-grow', placeholder: '新分组名称' })
|
||||
var ok = el('button', { class: 'iwb-btn iwb-btn-primary', text: '确定' })
|
||||
var no = el('button', { class: 'iwb-btn', text: '取消' })
|
||||
ok.addEventListener('click', function () {
|
||||
var n = String(inp.value || '').trim()
|
||||
if (n && !groupsOf().some(function (x) { return x.name === n })) save(list, groupsOf().concat([{ id: n, name: n }]))
|
||||
filter = n || filter
|
||||
newOpen = false
|
||||
render()
|
||||
})
|
||||
no.addEventListener('click', function () { newOpen = false; render() })
|
||||
inp.addEventListener('keydown', function (e) { if (e.key === 'Enter') ok.click() })
|
||||
row.appendChild(inp); row.appendChild(ok); row.appendChild(no)
|
||||
fixed.appendChild(row)
|
||||
setTimeout(function () { try { inp.focus() } catch (e) { /* ignore */ } }, 0)
|
||||
}
|
||||
|
||||
// 卡片
|
||||
var cards = el('div', { class: 'iwb-lib-cards' })
|
||||
var items = visible()
|
||||
items.forEach(function (g) {
|
||||
var isEditing = editing === g.id
|
||||
var card = el('div', {
|
||||
class: 'iwb-glp-card iwb-pcard' + (isEditing ? ' iwb-pcard-editing' : '') + (manage && picked[g.id] ? ' iwb-pcard-selected' : ''),
|
||||
'data-manage': manage ? '1' : '0',
|
||||
draggable: isEditing ? 'false' : 'true',
|
||||
title: manage ? '单击选中 · 右上「移动到分组」' : '双击改名 · 拖到画布实例化 · 右键移动到分组',
|
||||
})
|
||||
card.addEventListener('dragstart', function (e) {
|
||||
if (isEditing) return
|
||||
try { card.classList.add('iwb-glp-dragging') } catch (err) { /* ignore */ }
|
||||
try {
|
||||
e.stopPropagation()
|
||||
e.dataTransfer.setData('application/x-iwb-group', JSON.stringify(g.id))
|
||||
e.dataTransfer.setData('application/x-iwb-groupid', g.id)
|
||||
e.dataTransfer.effectAllowed = 'copy'
|
||||
} catch (err) { /* ignore */ }
|
||||
})
|
||||
card.addEventListener('dragend', function () {
|
||||
try { card.classList.remove('iwb-glp-dragging') } catch (err) { /* ignore */ }
|
||||
})
|
||||
card.addEventListener('contextmenu', function (e) {
|
||||
if (manage) { e.preventDefault(); picked[g.id] = picked[g.id] ? 0 : 1; render(); return }
|
||||
openMenu(e, g)
|
||||
})
|
||||
card.addEventListener('dblclick', function (e) {
|
||||
e.stopPropagation()
|
||||
if (manage) return
|
||||
editing = g.id
|
||||
render()
|
||||
})
|
||||
|
||||
var rowEl = el('div', { class: 'iwb-row' })
|
||||
if (isEditing) {
|
||||
var input = el('input', { class: 'iwb-input iwb-grow iwb-pname-input', value: g.name || '', placeholder: '组名' })
|
||||
var cancel = false
|
||||
var commit = function () {
|
||||
if (cancel) return
|
||||
editing = ''
|
||||
var n = String(input.value || '').trim() || g.name
|
||||
if (n !== g.name) save(list.map(function (x) { return x.id === g.id ? Object.assign({}, x, { name: n }) : x }))
|
||||
else render()
|
||||
}
|
||||
input.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') { e.stopPropagation(); commit() }
|
||||
if (e.key === 'Escape') { e.stopPropagation(); cancel = true; editing = ''; render() }
|
||||
})
|
||||
input.addEventListener('blur', commit)
|
||||
rowEl.appendChild(input)
|
||||
setTimeout(function () { try { input.focus(); input.select() } catch (e) { /* ignore */ } }, 0)
|
||||
} else {
|
||||
var nameEl = el('span', { class: 'iwb-pname', title: '双击改名', text: g.name || '分组' })
|
||||
rowEl.appendChild(nameEl)
|
||||
var btns = el('span', { class: 'iwb-pbtns' })
|
||||
var del = el('button', { class: 'iwb-btn iwb-btn-sm iwb-btn-danger', title: '删除节点组', text: '✕' })
|
||||
del.addEventListener('click', function (e) {
|
||||
e.stopPropagation()
|
||||
ask('删除节点组「' + (g.name || '') + '」?', { title: '删除节点组', okText: '删除' }).then(function (ok) {
|
||||
if (!ok) return
|
||||
list = list.filter(function (x) { return x.id !== g.id })
|
||||
render()
|
||||
Promise.resolve(api.remove(g.id)).catch(function () {})
|
||||
})
|
||||
})
|
||||
btns.appendChild(del)
|
||||
rowEl.appendChild(btns)
|
||||
}
|
||||
card.appendChild(rowEl)
|
||||
if (manage) {
|
||||
card.addEventListener('click', function () {
|
||||
picked[g.id] = picked[g.id] ? 0 : 1
|
||||
if (!picked[g.id]) delete picked[g.id]
|
||||
render()
|
||||
})
|
||||
} else {
|
||||
card.addEventListener('click', function (e) { e.stopPropagation() })
|
||||
}
|
||||
cards.appendChild(card)
|
||||
})
|
||||
scrollBox.appendChild(cards)
|
||||
if (!items.length) {
|
||||
var hint = loadError
|
||||
? loadError
|
||||
: (list.length
|
||||
? '当前分组下没有节点组(共 ' + list.length + ' 个,切到「全部」查看)'
|
||||
: '宿主返回 0 个收藏节点组。画布编组后点组右上角「收藏」,或用右键菜单「收藏选中节点」。')
|
||||
scrollBox.appendChild(el('div', { class: 'iwb-hint iwb-glp-empty', text: hint }))
|
||||
}
|
||||
}
|
||||
|
||||
// 宿主侧变化(画布收藏节点组 / 其它标签页同步)→ 重拉
|
||||
var off = null
|
||||
try { off = api.onChanged && api.onChanged(function () { load() }) } catch (e) { /* ignore */ }
|
||||
|
||||
load()
|
||||
|
||||
return function dispose () {
|
||||
try { if (typeof off === 'function') off() } catch (e) { /* ignore */ }
|
||||
closeMenu()
|
||||
if (modalHost && modalHost.parentNode) modalHost.parentNode.removeChild(modalHost)
|
||||
modalHost = null
|
||||
}
|
||||
}
|
||||
|
||||
global.IWBPluginHost.register({
|
||||
id: 'grouplib',
|
||||
name: '节点组',
|
||||
version: '1.0.5',
|
||||
apiVersion: 1,
|
||||
capabilities: ['panels', 'grouplib'],
|
||||
data: { schemaVersion: 1, maxBytes: 65536 },
|
||||
}, function (ctx) {
|
||||
ctx.ui.registerPanel({
|
||||
id: PANEL_ID,
|
||||
title: '节点组',
|
||||
icon: 'group',
|
||||
// 宿主只调用 mount(node)(一个参数):必须在这里把工厂 ctx 注入,否则面板里 ctx 是 undefined ⇒ 首渲染抛异常 ⇒ 整块空白
|
||||
mount: function (host) { return mount(host, ctx) },
|
||||
})
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -0,0 +1,42 @@
|
||||
/* grouplib(节点组)自带样式
|
||||
作用域全部带 .iwb-glp-*,不影响宿主与其他插件;样式随插件发布,不必等客户端发版。 */
|
||||
|
||||
/* 分类胶囊「适应面板宽度」自动换行。
|
||||
宿主的 .iwb-lib-chips 是 flex-wrap: nowrap(配合 .iwb-lib-chips-scroll 才做单行横向滚动),
|
||||
分组多时右侧胶囊会被面板宽度裁掉、看不见也用不了。
|
||||
这里用双类选择器提高优先级(不依赖样式注入顺序),让它按宽度折行。 */
|
||||
.iwb-lib-chips.iwb-glp-chips {
|
||||
flex-wrap: wrap;
|
||||
row-gap: 6px;
|
||||
}
|
||||
|
||||
/* + / ⚙ 是动作按钮,不是分组名:不参与压缩,并与最后一个分组稍作分隔 */
|
||||
.iwb-glp-chips .iwb-glp-add {
|
||||
flex: 0 0 auto;
|
||||
margin-left: 2px;
|
||||
}
|
||||
|
||||
/* v1.0.4(2026-11-21):卡片交互态 + 空态 + 拖拽反馈。
|
||||
颜色只走宿主 token(--iwb-plugin-* / --iwb-*),不写死。 */
|
||||
.iwb-glp-card { transition: background .12s ease, border-color .12s ease; }
|
||||
.iwb-glp-card .iwb-pname { font-weight: 600; }
|
||||
/* 删除按钮:平时隐藏,悬停/键盘聚焦才出现,减少视觉噪音 */
|
||||
.iwb-glp-card .iwb-pbtns { opacity: 0; transition: opacity .12s ease; }
|
||||
.iwb-glp-card:hover .iwb-pbtns,
|
||||
.iwb-glp-card:focus-within .iwb-pbtns { opacity: 1; }
|
||||
/* 管理模式的选中标记:右上角圆点 */
|
||||
.iwb-glp-card[data-manage="1"]::after {
|
||||
content: ''; position: absolute; right: 8px; top: 8px; width: 12px; height: 12px;
|
||||
border-radius: 50%; border: 1.5px solid var(--iwb-border2, #b9bfca); background: transparent;
|
||||
}
|
||||
.iwb-glp-card[data-manage="1"].iwb-pcard-selected::after {
|
||||
background: var(--iwb-brand, #6b7280); border-color: var(--iwb-brand, #6b7280);
|
||||
}
|
||||
/* 拖拽中:半透明 + 轻微缩放,明确"正在搬运" */
|
||||
.iwb-glp-dragging { opacity: .55; }
|
||||
/* 空态:虚线框 */
|
||||
.iwb-glp-empty {
|
||||
margin: 4px 0; padding: 12px 12px; border-radius: 10px; text-align: center;
|
||||
border: 1px dashed var(--iwb-border2, #b9bfca); color: var(--iwb-text2, #4d5668);
|
||||
font-size: 12px; line-height: 1.7;
|
||||
}
|
||||
+220
-43
@@ -16,10 +16,10 @@
|
||||
|
||||
### 移植改动之一:CSP 适配
|
||||
`plugin/editor/dom.js` 的 `loadImage()`:上游用 `fetch(dataURL)` 把 dataURL 转成 blob URL(避免 `img.src` 在整个编辑会话里
|
||||
持有几十 MB 的 base64 字符串)。但宿主 CSP 是 `connect-src 'self' https: …`,**不含 `data:`** ⇒ `fetch(data:)` 必被浏览器拦,
|
||||
每次打开编辑器都产生一次 CSP 违规(上游的 `catch` 回退让它「还能用」,所以功能看起来正常、只在控制台报错)。
|
||||
持有几十 MB 的 base64 字符串)。合成宿主的 CSP 常把 `connect-src` 限为 `'self' https:`、**不含 `data:`** ⇒ `fetch(data:)` 被拦
|
||||
(桌面客户端的 CSP 含 `data:`,但测试用的合成宿主按更严策略跑,故仍按最严口径处理)。
|
||||
现改为**纯本地解码**(`atob` → `Uint8Array` → `Blob` → blob URL),与上游行为一致(同样拿到 blob URL),且不依赖 CSP/网络。
|
||||
> 这类问题**只有带 CSP 的真站能测出来**(无 CSP 的 mock 页永远绿)。真实站点用例见 `image-annotate/tools/e2e-site.mjs`。
|
||||
> 这类问题**只有带 CSP 的真机/合成宿主能测出来**(无 CSP 的 mock 页永远绿)。用例见 `image-annotate/tools/e2e-site.mjs`。
|
||||
|
||||
### v1.1:选区、便利版 UI、单张输出
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
侧栏保留调色板全量 + 笔刷大小(滑杆/数字/快捷点)+ 缩放行。
|
||||
|
||||
- 测试:`node image-annotate/tools/harness.mjs`(合成宿主,发布前,79 项);
|
||||
`node image-annotate/tools/e2e-site.mjs`(真站 CSP/SRI,发布后)。
|
||||
`node image-annotate/tools/e2e-site.mjs`(桌面客户端 CSP/SRI,发布后)。
|
||||
|
||||
## v1.2.2
|
||||
|
||||
@@ -234,6 +234,188 @@ P 下双击 = 结束当前路径(`commitPenPath`),不再进节点编辑。
|
||||
- 文字 / 形状 / 钢笔会被直接栅格化进结果层(PS 合并矢量层也是这个结果)。
|
||||
- 结果层落回「原最低参与层」的位置,`assignLayerZ` 重新连续编号,不产生重复 z。
|
||||
|
||||
## v1.20.1:吸管 + 色值整组右对齐 / 色值框 124 → 96
|
||||
|
||||
用户截图:「吸色与色值部分有问题,他现在是左对齐,就会因为前面的颜色属性浮动,我需要他不浮动,
|
||||
你可以改为右对齐看看,设置框可以小一些,现在长了」。
|
||||
|
||||
```
|
||||
[文字●][描边●][底色●] ⌖ [ #2F6FED ] │ 📌
|
||||
↑ 这一段整组钉在右侧
|
||||
```
|
||||
|
||||
- v1.20 只把**图钉**推到最右,吸管与色值还紧跟 tab —— 文字工具多出「底色」tab 时这一组就整体右移一次,
|
||||
切回形状又左移一次,视线每次都要重新找。现在 `.iwb-color-pop-tools` 把
|
||||
**吸管 + 色值 + 竖线 + 图钉**整组包住并 `margin-left: auto`,左侧剩余空隙全由 tab 组吸收。
|
||||
- 右组前那条竖线删掉:右对齐后它只会孤零零悬在空白里,空隙本身已经把「选槽 / 取色」分开了。
|
||||
留下的那条竖线是分隔「图钉」这个常驻开关,位置固定。
|
||||
- 色值框 `124 → 96px`(用户「设置框可以小一些,现在长了」):#RRGGBB 在 13px 等宽下约 55px,
|
||||
加 padding 仍有 30px 余量。它现在是右组里的一颗「读数」,不该比吸管/图钉更重。
|
||||
- 回归断言从「宽度不变」升级为「**逐像素坐标不变**」:`sig = [吸管左, 色值左, 图钉左, 图钉右]`,
|
||||
两 tab 与三 tab 两种上下文下 `597,629,738,762` 必须完全相同,且图钉右边缘贴住头部右边界(`rightPinned`)。
|
||||
|
||||
## v1.20.0:去色下移成常用色第一格 / 头部全部定宽,不再被自动布局抵掉
|
||||
|
||||
用户截图反馈:「如果是文本元素的时候,就会把那个去色按钮给丢掉…可以让这些颜色选项一直保持在上面,
|
||||
只是说不可用的时候是灰色。那个吸色、去色,数值框可以就固定了,避免自动布局给它抵掉」,
|
||||
随后补一句「或者你把去色按钮放在常用颜色的第一个」。
|
||||
|
||||
**根因**:头部一行本来就是「3 个 tab + 竖线 + 吸管 + 色值 + 去色 + 图钉」,440px 的面板里
|
||||
content 只有 416px,文字工具多出「底色」tab 时已经超出 3px —— 色值框当时是 `flex: 0 1 150px`,
|
||||
自己缩到 147 顶着,再去掉一份宽度,`去色` 就被 flex 压没了(不是被 `hidden` 藏起来的)。
|
||||
|
||||
**做法(两条一起做,正好互相成全)**:
|
||||
|
||||
```
|
||||
[文字●][描边●][底色●] │ ⌖ [ #2F6FED ] │ 📌
|
||||
常用色 [⊘][🔴][🟠][🟡][🟢][🟩][🔵][🩷]
|
||||
[⚪][⚫灰][⚫][🟥][🟩][🟦][🟪] ← 去色 = 第一格,永远在
|
||||
```
|
||||
|
||||
- **去色 = 常用色网格第一格**(20px 圆、虚线边框 + 斜圈图标、间距跟色块完全一致)。
|
||||
位置永远固定,切到文字色 / 未闭合钢笔这类「去掉就等于删对象」的上下文——
|
||||
**不再 hidden,改成 `disabled` + 32%→42% 不透明度**,title 写明原因
|
||||
(「去色不可用:文字色去掉就等于把文字删了」),hover 反馈也随 `:disabled` 关掉。
|
||||
- **头部元素全部定宽**:色值框 `flex: 0 0 124px`(原来是可缩的 150px)、吸管 26、图钉 24、tab 不可压缩。
|
||||
加上「底色」tab 后色值框宽度与图钉右边缘**一格像素都不动**,harness 有专门的回归断言
|
||||
(`hexW: [124,124]`、`pinR: [762,762]`)。
|
||||
- 常用色 16 → 15(亮紫 `#aa44ff` 让位给去色第一格,深紫 `#6b4fbb` 还在),
|
||||
去色 + 15 色正好仍是 8 列 × 2 行,不出现第 3 行孤零零一个色块。
|
||||
- 删掉 `:has(> .iwb-color-pop-none[hidden]) > .iwb-color-pop-bar { display: none }`:
|
||||
去色不再隐藏,竖线也就没有「悬空」问题,头部结构变成纯静态。
|
||||
|
||||
测试:harness 231 项(新增「去色是第一格 / 加底色 tab 后头部纹丝不动 / 文字色下去色置灰」3 条,
|
||||
另有 4 条旧断言从看 `.hidden` 改成看 `.disabled`);桌面客户端 e2e 40 项(改为校验 `noneFirst` + 15 色)。
|
||||
|
||||
## v1.19.0:右栏调色模块退场 / 头部一行装完 / 常用色 16 个 + 最近两排
|
||||
|
||||
用户一段话:「右边栏的调色模块就可以去掉了,然后还去一个去色按钮,可以放在钉住按钮的左边,
|
||||
用竖线分割,然后我希望最近色多几个…把吸色与色值数放在钉住按钮的一排,那下面的最近色就可以放两排了。
|
||||
后宽度可以再多一点点,就是让颜色按钮一排可以放 8 个,那你就需要多加 4 个常用色」。
|
||||
|
||||
**1) 右栏常驻调色面板删除。**
|
||||
色板现在只有工具栏弹层一处。v1.16 加它是因为「不想每次点开弹层」,但 v1.18 的钉住已经解决了同一件事——
|
||||
弹层钉住后本来就是一个常开的浮层,右栏那份是同样内容的第二个副本,还占着最显眼的位置。
|
||||
顺带少了一层「同一份 DOM 两套 CSS 布局」的分支,改色板不用再担心改了这头没那头。
|
||||
|
||||
**2) 头部一行装完**:调色槽 │ 吸管 + 色值 │ 去色 │ 图钉
|
||||
|
||||
```
|
||||
[描边●][填充●] │ ⌖ [ #FFD400 ] │ [⊘ 去色] │ 📌
|
||||
```
|
||||
|
||||
- 吸管与色值从右列搬到头部,body 的整块高度都留给色块 —— 这是「最近色能放两排」的前提。
|
||||
- 「无」改名**去色**,挪到图钉左边、用 1px 竖线隔开:调色时「这一项不上色」和「钉住」都是随手要按的开关。
|
||||
对描边/填充/底色都生效,title 随当前槽变。
|
||||
- 没有可去色的上下文(没选中对象、文字色这种单槽)时它本来就隐藏,**它前面那条竖线跟着一起藏**
|
||||
(`:has(> .iwb-color-pop-none[hidden])`),否则头部右侧会留一截悬空的「||」。
|
||||
> v1.20 已推翻:隐藏 ⇒ 置灰 disabled,且整颗下移到常用色第一格(见上一节)。
|
||||
- 「去色 | 图钉」整组用 `margin-left: auto` 贴最右,色值框固定 150px 不被拉成长条
|
||||
(拉长后视觉重心全跑到输入框上,色块反倒成了配角)。tab 加 `flex: 0 0 auto; white-space: nowrap`——
|
||||
宽度不够时该缩的是色值框,不是把「描边」压成竖排两个字。
|
||||
> v1.20 已改:色值框收紧到定宽 124px 且不再可缩 —— 就是「该缩的是色值框」这条把去色缩没了。
|
||||
|
||||
**3) 色块 8 列 × 2 行,常用色 12 → 16,最近色 6 → 16。**
|
||||
|
||||
第一行是 8 个饱和亮色,第二行是 4 个中性色 + 4 个同色系「深一档」:
|
||||
|
||||
```
|
||||
亮:#ff4444 #ff8a00 #ffd400 #4cd964 #00bfa5 #4488ff #aa44ff #ff66aa
|
||||
常:#ffffff #d0d0d0 #808080 #000000 #c0392b #0f9d58 #1677ff #6b4fbb
|
||||
```
|
||||
|
||||
加的那 4 个(深红/深绿/深蓝/深紫)在浅色底图上比亮色稳,做描边不刺眼。色块 18 → 20px。
|
||||
弹层 **380×153 → 440×157**(宽度 +16%,高度只 +4px —— 多出来的一排被「吸管+色值上移」抵掉了)。
|
||||
|
||||
两个刻意的决定:
|
||||
|
||||
- **弹层宽度写死 440px**。绝对定位元素是 shrink-to-fit,宽度会跟着最长内容走:
|
||||
文字工具多出「底色」tab 时头部变宽,弹层当场变宽 17px 再跳回来,定位还得重算。
|
||||
- **分隔线从 `#313244` 提到 `#3b3b4e`**。没有小标题时,这条线是唯一能看出「常用 / 最近」分界的东西,
|
||||
按原色画在深底上几乎看不见。
|
||||
|
||||
**验证**:harness 229 项、桌面客户端 e2e 40 项全绿。新增 harness 断言:头部四个控件同一水平线 + 去色在图钉左边 +
|
||||
两者之间有竖线 + 三 tab(文字工具)时头部不横向溢出、常用色 16 个严格 8 列 2 行、最近色网格 8 列 2 排、
|
||||
弹层宽高区间、右栏第一个模块是「图片调节」且无 `[data-color-surface]`。
|
||||
|
||||
## v1.18.0:色板可以「钉住」+ 右列竖向收窄 + 撤销组搬进工具条
|
||||
|
||||
用户两句话:「这个弹出的调色气泡,加一个功能就是让他能够钉住,在需要调色的时候不用每次都要点开」
|
||||
「右边的数值、常用色、最近色你看下能不能竖向排…顺序改为设置、常用色、最近,这三项不用标题,
|
||||
用细横线分割」;另加「这几个图标移动到工具栏的最右边」(撤销 / 重做 / 还原)。
|
||||
|
||||
**钉住**:色板弹层右上角一颗图钉(`data-action="pinColorPop"`)。
|
||||
|
||||
- 钉住时点画布、点别处都不收起 —— 这就是它存在的全部意义(要收就再点一次图钉或按 Esc)。
|
||||
- 状态写 `ctx.settings.colorPopPinned`,跨会话记住:钉过一次就一直钉着,下次打开仍是钉住的。
|
||||
- 图钉用**绝对定位**钉在头部右上角(头部留 `padding-right: 26px` 让位),
|
||||
这样「无」按钮的显隐不会把它挤来挤去。
|
||||
- 激活态用琥珀色描边 + 淡底,不旋转角度:45° 的图钉在 13px 下看着像歪掉的问号。
|
||||
|
||||
**右列竖向**:原来「吸管+HEX | 常用色 | 最近」是横向并排、靠小标题分组,
|
||||
弹层宽 630px 且「常用色 / 最近」各占一行标题。现在三块竖着叠、块间 1px 细线、**不要标题**:
|
||||
|
||||
```
|
||||
[ 取色器 ] │ [吸管 #FF4444] ← 设置
|
||||
│ ─────────────
|
||||
│ ●●●●●● ●●●●●● ← 常用色(6 列 × 2 行)
|
||||
│ ─────────────
|
||||
│ ●●●●●● ← 最近(6 列,上限收到 6 个正好一行)
|
||||
```
|
||||
|
||||
弹层从 **630×157 → 380×153**:宽度砍掉 40%,高度基本不变(标题行省下来的高度被 6 列更窄的网格吃掉)。
|
||||
色块 22px → 18px;「最近」上限 8 → 6,否则 8 个会折成第二行,把面板顶高 23px,和「更紧凑」相反。
|
||||
|
||||
同一份 DOM 右栏常驻面板也在用,那边靠 `.iwb-editor-colors .iwb-color-pop-side { display: contents }`
|
||||
把新加的 `.iwb-color-pop-side` 这层拆掉,走自己原来的竖排,pin 按钮在右栏 `display: none`。
|
||||
|
||||
**撤销组搬位**:撤销 / 重做 / 还原从顶栏 `.iwb-editor-history` 移到画布底部工具栏最右(视图快捷之后)。
|
||||
理由是这三个是画画时会连着按的操作,手在画布上,不该抬头去顶栏找。顶栏只剩会话组(新建/覆盖/退出)与输出。
|
||||
三个按钮本来就和工具按钮同为 32×32 `.iwb-editor-action` 样式,搬过去不用改尺寸。
|
||||
|
||||
**验证**:harness 228 项(新增 5 项:右列竖排几何 + 1px 分隔线 + 无标题、弹层尺寸 ≤ 460×175、
|
||||
钉住后点画布不收起且写进 settings、取消钉住后点画布立即收起、撤销组是 tools 最后子元素且与工具同轴)。
|
||||
改了两条老断言:顶栏不再有 `.iwb-editor-history`;`[data-action="reset"]` 的查询范围从 header 改成 tools。
|
||||
|
||||
## v1.17.0:描边也能是「无色」+ 一边无色时 Shift+X 照样交换
|
||||
|
||||
用户两句话:「让矢量图形与钢笔的描边色也可以去掉」「描边与填充有一个是无色的时候可以交换,
|
||||
现在是不可以的」。
|
||||
|
||||
### 描边的第三态
|
||||
|
||||
以前描边只有「什么颜色」,没有「有没有」。现在形状对象多一个 `strokeOn`(缺省 = 有,
|
||||
老对象与历史快照没有这个字段一律当有描边,不需要数据迁移):
|
||||
|
||||
- `drawShape()` 里所有 `ctx.stroke()` 都按 `strokeOn` 跳过。**不能用 `lineWidth = 0` 实现**——
|
||||
canvas 会忽略 0 并保留上一次的线宽,且改回需要记住原值;
|
||||
- 「无」按钮出现在**描边槽**(色板头部 / 右栏面板同一份 DOM),点一下只关外框、颜色留着,
|
||||
下次选色直接恢复(与「文字描边宽度 0 时选色自动给 6px」同一条逻辑,选色共用一张快照,撤销一步);
|
||||
- 「只描边」的形状去掉描边会整体消失,所以**顺手切实心** —— 结果是「一个没有框的色块」,
|
||||
而不是「对象凭空没了」;反过来在选项栏点「描边」也会自动恢复 `strokeOn`;
|
||||
- 只有**「去掉后还看得见」才给「无」**:矩形/圆形、闭合钢笔可以;箭头、未闭合钢笔不给
|
||||
(判据复用 `fillSlotOn()`,与「填充槽存不存在」同一份逻辑);
|
||||
- 视觉:工具栏描边格与色板 tab 画红斜杠(复用 `.is-none`),选项栏描边色块置灰(`.is-off`)。
|
||||
|
||||
### Shift+X:交换的是「颜色 + 有无」
|
||||
|
||||
以前只交换颜色值,所以「无填充」时按 X 看不出任何变化(只有一个颜色,被判定为「无需交换」)。
|
||||
现在交换整份状态:
|
||||
|
||||
- 两边都有色 → 颜色对调,开关不动(v1.13.1 的语义保留);
|
||||
- 只有一边有色 → 有色那边连同颜色整体换到另一边(无填充 + 有色描边 ⇄ 有色填充 + 无描边);
|
||||
- 填充色还在「跟随描边色」(`fillColor=null`)→ 只换有无,颜色继续跟随,不拆成独立色;
|
||||
- 两边都无色、或箭头/未闭合钢笔(换完什么都不剩)→ toast 提示,不写历史。
|
||||
|
||||
`__debug().shapes` 增加 `strokeOn`,harness 补 7 条(描边像素清零、三处 UI 斜杠态、
|
||||
「无描边」后再点「无填充」的对称保护、选色恢复描边、钢笔闭合可去描边、
|
||||
未闭合不给入口、一边无色可交换并回退)。
|
||||
|
||||
### v1.17.1:对称保护
|
||||
|
||||
「无描边」后再去点「无填充」,两者都无色会让对象彻底隐形。填充的「无」现在也会检查描边:
|
||||
若描边已关就自动恢复,与「无描边时顺手切实心」正好对称 —— 两条路径都不会产出看不见的对象。
|
||||
|
||||
## v1.16.0:右栏常驻调色面板 + 可拖宽度 + 整体字号提升
|
||||
|
||||
用户三句话拆成四件事:面板文字偏小、右栏要能拖宽、把调色面板(含常用色)搬进右栏、
|
||||
@@ -425,10 +607,10 @@ applyTextStyle(textBtn.dataset.optText, textBtn.dataset.value, true)
|
||||
|
||||
三条硬约束:
|
||||
|
||||
1. **CSP 拦死了第三方字体**。宿主 `_headers` 是 `default-src 'self'`,`font-src` 回落它,
|
||||
`https:` 只放给了 `img-src` / `connect-src`。Google Fonts 或任何字体 CDN 都会被浏览器直接拒绝。
|
||||
1. **CSP 不放行第三方字体**。桌面宿主 CSP 是 `default-src 'self'`,`font-src` 只放行 `data:`,
|
||||
不放行 `https:`。Google Fonts 或任何字体 CDN 都会被拦。
|
||||
2. **中文字体太大**。本机参照:宋体 2.3MB、楷体 2.2MB、苹方全字重 64MB;插件产物现在 392KB,
|
||||
内联等于涨 5–150 倍。子集化到 3500 常用字约 0.8–1.5MB/个,能接受,但要放宿主静态目录,
|
||||
内联等于涨 5–150 倍。子集化到 3500 常用字约 0.8–1.5MB/个,能接受,但要改宿主 CSP/资源,
|
||||
发布链得一起改。
|
||||
3. **异步字体的时序坑**。Web 字体异步加载,字体没 ready 就 `measureText`,量出来的是 fallback
|
||||
的宽度 —— 选中框和实际字形错位,导出还可能画成 fallback。系统字体同步可用,没有这个问题。
|
||||
@@ -774,11 +956,11 @@ Esc 取消不留空对象、选择工具未选中仍有 3 个图标、只选颜
|
||||
顶栏「导出」左边新增「复制」:把当前结果编码成 PNG 塞进 `ClipboardItem`,
|
||||
可直接粘到聊天窗口 / 后台上传框,**不关闭编辑器**。
|
||||
|
||||
- 走 `toPngBlob()`,优先 `createImageBitmap` —— 宿主页 CSP 常禁 `img-src: blob:`,
|
||||
用 `new Image()` 解码会直接失败。
|
||||
- 走 `toPngBlob()`,优先 `createImageBitmap` —— 稳妥起见不依赖 `img-src: blob:` 放行
|
||||
(合成宿主的 CSP 常禁 blob:,用 `new Image()` 解码会失败)。
|
||||
- 失败必须**说清楚**:非安全上下文(如 `about:blank`)没有 `navigator.clipboard`,
|
||||
提示「当前浏览器不支持复制图片,请用「导出」下载」,而不是静默无反应。
|
||||
真实 https / localhost 下已验证可用(`navigator.clipboard.read()` 能读回 `image/png`)。
|
||||
提示「当前环境不支持复制图片,请用「导出」下载」,而不是静默无反应。
|
||||
桌面客户端下已验证可用(`navigator.clipboard.read()` 能读回 `image/png`)。
|
||||
|
||||
### 两条踩过的坑
|
||||
|
||||
@@ -795,7 +977,7 @@ Esc 取消不留空对象、选择工具未选中仍有 3 个图标、只选颜
|
||||
|
||||
## v1.8.3:图层面板交互修复(滑杆能拖、图层能拖排)
|
||||
|
||||
线上两个反馈,根子在同一个属性上:
|
||||
用户反馈的两个问题,根子在同一个属性上:
|
||||
|
||||
1. **不透明度滑杆只能点、不能拖** —— 点了滑杆轨道数值会跳,但按住拖动毫无反应。
|
||||
2. **图层拖不动排序** —— 拖了松手顺序不变,看起来像没实现。
|
||||
@@ -862,17 +1044,14 @@ harness 里专门有一条用例守着它。
|
||||
|
||||
## v1.8.1:修复 SRI 加载失败(发布通道改内容寻址)
|
||||
|
||||
v1.8.0 上线后线上报「脚本完整性校验失败(integrity 不符或加载失败)」,插件直接不可用。
|
||||
v1.8.0 上线后报「脚本完整性校验失败(integrity 不符或加载失败)」,插件直接不可用。
|
||||
|
||||
原因不在插件代码,在发布通道:`scripts/plugins-publish.sh` 用的是**固定文件名**
|
||||
`plugin-image-annotate.js`,而清单里的 `integrity` 随内容每次变化。
|
||||
客户端只要还留着旧字节(浏览器磁盘/内存缓存、中间代理),新 integrity 就对不上 ⇒ SRI 判失败。
|
||||
`no-cache + ETag` 的语义只是「可缓存但须回源校验」,管不住已经骗到手的旧副本。
|
||||
原因不在插件代码,在发布通道:早期用的是**固定文件名** `plugin-image-annotate.js`,
|
||||
而清单里的 `integrity` 随内容每次变化。客户端只要还留着旧字节,新 integrity 就对不上 ⇒ SRI 判失败。
|
||||
|
||||
修法:文件名改为内容寻址 `plugin-image-annotate.<sha256前12位>.js`,与 `plugins-publish.mjs`
|
||||
的 `storedNameOf` 对齐。内容变 ⇒ 文件名变 ⇒ 新版本必然是新 URL,SRI 必中;
|
||||
同时命中 Functions 的 `IMMUTABLE_JS_RE`,拿到 `public, max-age=31536000, immutable`,
|
||||
355KB 的产物不必每次 304 回源协商。
|
||||
修法:文件名改为内容寻址 `plugin-image-annotate.<sha256前12位>.js`。内容变 ⇒ 文件名变 ⇒
|
||||
新版本必然是新 URL,SRI 必中。这正是现在桌面仓同步脚本 `sync-plugins-from-repo.js` 的做法
|
||||
(它按 sha256 前 12 位命名并重建带 SRI 的清单),所以这条坑不会再踩。
|
||||
|
||||
插件本体代码与 v1.8.0 逐字相同,`src/index.js` 只有 manifest 里的版本号不同。
|
||||
|
||||
@@ -1015,35 +1194,33 @@ npm run validate # 契约校验
|
||||
|
||||
> 注意:banner 的**注释**里也不能出现 id + 冒号 + 单引号的组合,否则会被校验器当成 manifest 抢走(踩过一次)。
|
||||
|
||||
## 发布(按 HANDBOOK 第八节:先提交 → 合主干 → 再发布)
|
||||
## 发布
|
||||
源码与产物先提交进本仓(`src/index.js` 是 esbuild 产物,必须提交;CI 只校验不构建):
|
||||
|
||||
```bash
|
||||
# 1) 源码与产物先落库,并确保 HEAD 已在 origin/main(脚本会强制校验这两条)
|
||||
cd /Users/qiqi/open/github/iwb-plugins
|
||||
npm run build -- image-annotate && npm run validate
|
||||
git add image-annotate && git commit -m "feat(image-annotate): v1.7.0 ..." && git push
|
||||
git switch main && git merge --ff-only <你的分支> && git push
|
||||
|
||||
# 2) 用带守卫的发布脚本(旧 plugins-publish.mjs 会绕过校验,不要再用)
|
||||
cd /Users/qiqi/open/github/image-workbench-web
|
||||
scripts/plugins-publish.sh image-annotate \
|
||||
/Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js 1.7.0
|
||||
|
||||
# 3) 脚本会打 annotated tag 但不会推,手动补
|
||||
git -C /Users/qiqi/open/github/iwb-plugins push origin [email protected]
|
||||
# 提交并推送本仓改动
|
||||
```
|
||||
脚本的三道前置校验:工作区干净、HEAD 是 `origin/main` 的祖先、`wrangler.toml` 有 KV namespace。
|
||||
任一条不满足直接拒发(紧急热修才用 `IWB_PUBLISH_SKIP_CHECKS=1`,事后必须补合并与 tag)。
|
||||
|
||||
发布脚本**默认与线上清单合并**(本次没传的插件原样保留),只传自己的文件即可;`--remove` 才是从清单移除。
|
||||
版本两处一起改:`package.json`(构建时注入 manifest)+ 脚本第 3 个参数。上传后回读校验清单与本地一致。
|
||||
发布后刷新即生效(KV 为测试站/正式站共享;新插件在插件管理里**默认未启用**,需手动开启)。
|
||||
再走桌面仓的市场链路(见根 README「发布到市场」):
|
||||
|
||||
```bash
|
||||
cd /Users/qiqi/open/github/image-workbench-desktop
|
||||
node scripts/sync-plugins-from-repo.js # 内容寻址命名 + SRI,重建清单
|
||||
node scripts/gen-market.js # 生成 market/index.json
|
||||
# 把 market/ 上传到 NAS /vol8/web/iwb-market/(market.maqiart.eu.org)
|
||||
```
|
||||
|
||||
桌面仓同步脚本按白名单一次重建全部插件清单,新版本文件名随内容哈希变化 ⇒ 不会撞旧 SRI。
|
||||
版本以 `package.json` 为准(构建时注入 manifest),改版本后重新构建再提交。
|
||||
发布后回读市场索引确认版本与哈希已更新,再在客户端市场安装验证——不能只看命令退出码。
|
||||
|
||||
## 验证(可选,开发用)
|
||||
`tools/e2e-site.mjs`:**带 CSP 的真实站点**端到端(真 KV 加载 + 浏览器 SRI + 漂浮菜单 → 编辑器 → 覆盖/新建),
|
||||
`tools/e2e-site.mjs`:**桌面客户端**端到端(市场安装 + SRI + 漂浮菜单 → 编辑器 → 覆盖/新建),
|
||||
另含 v1.0.5 的图层顺序回归:画图形 + 粘贴截图 → 唯一高亮、点重叠区选中最上层截图、四个排序按钮逐一生效、原图始终在最底。
|
||||
需要 Playwright(可从宿主仓 `node_modules` 或全局解析),**不进 CI**(本仓 CI 只跑 `npm run validate`,不联网、无依赖)。
|
||||
需要 Playwright(可从桌面仓 `node_modules` 或全局解析),**不进 CI**(本仓 CI 只跑 `npm run validate`,不联网、无依赖)。
|
||||
|
||||
```bash
|
||||
IWB_BASE_URL=https://test.image-workbench-web.pages.dev node image-annotate/tools/e2e-site.mjs
|
||||
node image-annotate/tools/e2e-site.mjs
|
||||
```
|
||||
> 为什么值得留着:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在 mock 下永远绿,只有真站能抓出来。
|
||||
> 为什么值得留着:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在 mock 下永远绿,只有真机能抓出来。
|
||||
@@ -1,6 +1,6 @@
|
||||
# 简化版 PS(Image Editor Lite)目标与实施分析
|
||||
|
||||
> 基线:`image-annotate` v1.0.5(`plugin-image-annotate.cfecb6e2ec17.js`),宿主 `image-workbench-web` 插件 API v1。
|
||||
> 基线:`image-annotate` v1.0.5(`plugin-image-annotate.cfecb6e2ec17.js`),桌面宿主 `image-workbench-desktop` 插件 API v1。
|
||||
> 本文只做目标定义、差距分析、UI/架构/分期设计,**不含代码改动**。改动前先确认文末「待拍板」一节。
|
||||
>
|
||||
> **范围裁定(用户确认)**:只做**单张图片**的编辑与输出,**不做批量出图 / 多图队列 / 批量导出**;
|
||||
@@ -86,7 +86,7 @@
|
||||
| 视图 | `editor/viewport.js` | zoom 0.1–10、自由平移、`overlayPad` 交互外扩、`getPos()` 统一坐标换算 |
|
||||
| 输出 | `editor/index.js#exportResult` | 固定 PNG `toBlob` → `glue.js` 转 dataURL → `setNodeImage` / `createImageNode` |
|
||||
| 内存 | `editor/index.js#releaseEditorMemory` | `close()` 释放所有像素、原图、历史;**会话状态不保留** |
|
||||
| 宿主 | `plugin/glue.js` | 只对 `ref` 节点暴露;`ctx.canvas.*`;`ctx.storage` 是宿主提供的小 KV(localStorage),**不是像素仓库** |
|
||||
| 宿主 | `plugin/glue.js` | 只对 `ref` 节点暴露;`ctx.canvas.*`;`ctx.storage` 是宿主提供的小容量命名空间 KV,**不是像素仓库** |
|
||||
|
||||
---
|
||||
|
||||
@@ -151,7 +151,7 @@
|
||||
| overlay 单 canvas 多用 | 裁剪遮罩、选中框、笔刷环、放置预览、提示文字全在 `S.overlayCanvas`,共用 `clearOverlay()`;**加蚂蚁线必然互相擦除** | P0 |
|
||||
| `editor.css` 补丁堆积 | 1340 行,后半段大量 `!important`;工具栏 `position:absolute; top:68px`,撤销按钮 `right:154px` 等魔数;`.iwb-editor-footer` 空且 `display:none`;`.iwb-editor-zoom-hint` 绝对定位 | P0 |
|
||||
| 无响应式 / 无亮色主题 | 窄窗口下 290px 图层面板 + 44px 工具栏挤压画布 | P5 |
|
||||
| 关闭即清空 | 无草稿、无二次编辑;`ctx.storage` 只是 localStorage 小 KV | P5 |
|
||||
| 关闭即清空 | 无草稿、无二次编辑;`ctx.storage` 只是宿主提供的小容量命名空间 KV | P5 |
|
||||
|
||||
---
|
||||
|
||||
@@ -290,14 +290,14 @@ getCompositeCanvas() // 当前这一张
|
||||
|
||||
| 期 | 交付 | 验收 |
|
||||
| --- | --- | --- |
|
||||
| **P0 地基 + 轻量 UI** | 精简顶栏、就地选项栏、状态栏、图层面板可收起、命令层、状态机、overlay 分层、toast、CSS 重构、快捷键映射层、定义 `resetDraw` 语义、放置免二次确认 | 功能零变化;**高频动作点击层级 ≤1**、无新增弹窗;真站 e2e 22/22 全绿;`npm run build` + `npm run validate`;发布契约 6/6 |
|
||||
| **P0 地基 + 轻量 UI** | 精简顶栏、就地选项栏、状态栏、图层面板可收起、命令层、状态机、overlay 分层、toast、CSS 重构、快捷键映射层、定义 `resetDraw` 语义、放置免二次确认 | 功能零变化;**高频动作点击层级 ≤1**、无新增弹窗;桌面客户端 e2e 22/22 全绿;`npm run build` + `npm run validate`;发布契约 6/6 |
|
||||
| **P1 选区核心** | 矩形/椭圆/多边形/套索;加选减选、全选/反选/取消、羽化、蚂蚁线;**选区浮动操作条 + 右键菜单**;复制/剪切到新层、Delete 清除(**仅当前层**)、填充/描边;附带「还原原图」与「≤500KB」预设 | 框选后浮动条一步完成复制;Ctrl+J 新层像素正确且原层不变;**Delete 后其它层像素原样、当前层挖空且可撤销**;base 锁定提示;「还原原图」后只剩 base 且 Ctrl+Z 能全恢复;预设输出 ≤500KB;选区与裁剪/放置互斥;三条入口结果一致 |
|
||||
| **P2 图像与裁剪** | 非破坏性裁剪(路线 1)、画布大小、图像大小、90° 旋转 / 翻转、尺寸预设(点击即用)、裁剪可撤销 | 裁剪后图层数不减、Ctrl+Z 能回退;文字/形状 `rotation` 保留;800×800 预设尺寸精确 |
|
||||
| **P3 图层增强** | 缩略图、重命名、混合模式、图层蒙版(选区→蒙版)、多选/简化编组、历史面板 | 蒙版可显隐/删除且不影响原像素;混合模式在合成与导出一致 |
|
||||
| **P4 单张输出** | PNG/JPG/WebP + 质量 + ≤500KB 策略 + 背景切换 + 下载/剪贴板 + 记住上次预设 | 单张导出尺寸/体积达标;透明像素正确;导出不污染画布;**无队列、无批量入口** |
|
||||
| **P5 打磨** | 右键菜单补全、全量快捷键、草稿、亮色主题、响应式、无障碍 | 窄窗口可用;草稿只存元数据不存像素 |
|
||||
|
||||
每一期都走同一条发布链:`plugin/editor/*.js` → `npm run build -- image-annotate` → `npm run validate` → **先提交源码并合进 `origin/main`** → 宿主仓 `scripts/plugins-publish.sh image-annotate <插件路径> <版本>`(带守卫,拒发脏工作区/未合主干)→ 补推 tag → 真站 e2e(带 CSP)。版本两处同步(`package.json` + 脚本参数),禁止手改 `plugins/index.json`。
|
||||
每一期都走同一条发布链:`plugin/editor/*.js` → `npm run build -- image-annotate` → `npm run validate` → 提交源码进本仓 → 桌面仓 `node scripts/sync-plugins-from-repo.js` + `node scripts/gen-market.js`(内容寻址 + SRI,自动重建清单)→ 上传 `market/` 到 NAS → 客户端市场安装验证(带 CSP)。版本以 `package.json` 为准(构建时注入 manifest),禁止手改桌面仓 `plugins/index.json`。
|
||||
|
||||
### 6.1 实施进度(v1.1.0,2026-11-04 已交付)
|
||||
|
||||
@@ -311,6 +311,7 @@ getCompositeCanvas() // 当前这一张
|
||||
| 工具参数解耦与选项栏 | ✅ v1.2.0:`S.shapeLineWidth` / `S.textSize` 独立于 `S.brushSize`;选项栏按工具出参数(画笔三参、形状线宽+填充、文字字号、选区形状/羽化),与右侧面板双向同步 |
|
||||
| P3 图层增强 | 🟡 v1.7:缩略图 / 重命名 / 多选 / 不透明度滑杆已补;混合模式 / 图层蒙版 / 编组未做 |
|
||||
| P4 单张输出 | ✅ PNG/JPG/WebP、透明/白底、800×800(长边 80%)、≤500KB 迭代降质、下载、设置记忆;无队列 |
|
||||
| 描边「无色」+ X 交换整份状态(v1.17.0 / v1.17.1) | ✅ 形状对象新增 `strokeOn`(缺省有描边,老对象/历史快照无此字段照旧),`drawShape()` 按它跳过 `ctx.stroke()`(不能用 `lineWidth=0`:canvas 忽略 0 且丢失原值);「无」按钮扩到**描边槽**,只关外框、颜色留着,选色即恢复(共用一张快照);去掉描边后会把「只描边」的形状顺手切实心,避免对象消失;箭头与未闭合钢笔不给入口(判据复用 `fillSlotOn()`)。Shift+X 从「只交换颜色」升级为**交换颜色 + 有无**:一边有色时连同颜色整体换到另一边,填充「跟随描边色」时只换有无不拆独立色,两边都无色或换完一无所有则提示不执行。v1.17.1 补对称保护:先无描边再点「无填充」时自动恢复描边,杜绝隐形对象 |
|
||||
| 右栏调色面板 / 可拖宽度 / 字号(v1.16.0) | ✅ 调色面板从「只弹层」变成「右栏常驻 + 弹层保留」,两处共用同一份 DOM(`dom.js#colorSurfaceHtml`),按 `[data-color-surface]` 各绑一次交互、`updateColorUI` 改遍历同步(HEX / SV / 色相 / 「无」显隐 / 常用色与最近色高亮);右栏宽度统一到 CSS 变量 `--iwb-side-w`(原三处硬编码 240/240/220),手柄 9px 热区、范围 220–520 且 ≤ 窗口 45%、默认 280、双击复位、写 `settings.sideWidth` 记忆;字号在 CSS 末尾用 `#iwb-editor-overlay` 前缀集中 +1 档(面板行名 12.5 / 标题 13 / 状态栏 12 / 选项栏 13 / 颜色 tab 12.5),调节名称列 46→50、数值框 36→40 |
|
||||
| 调节基准跨图串用修复(v1.15.1) | ✅ 退出编辑器后 `sourceCache`(key = `layer.id`,原图恒为 `'base'`)与 `S.adjust` 未清 ⇒ 第二张图一拖滑杆就把上一张图的像素重算上来,且 `ensureAdjustTarget()` 因 `layerId` 相同而跳过重拍基准。新增 `resetAdjustCache()`,在 `resetState()` 与 `releaseEditorMemory()` 双路径清空;`__debug()` 增 `adjustCacheSize` 观测口,harness 补「退出→重开」三条断言 |
|
||||
| 图片调节(v1.15.0) | ✅ 右侧栏新增 11 项连续调色:曝光(±2EV)/明度/对比度/阴影/高光/色相/饱和度/温度/色调/锐度/清晰度。走 `getImageData` 逐像素(CSS filter 做不到阴影高光的分区蒙版、白平衡的通道增益、锐化的卷积);拖动用长边 ≤900 的降采样预览(6.7ms),松手才全量(4000² 144ms)。`source` + 每层 `sourceCache` 保证永远从基准重算不叠加;撤销后滑块归零并重拍基准。顺带修强度:增强 brightness 1.12→1.4、高对比 contrast 1.4→1.6 |
|
||||
@@ -325,7 +326,7 @@ getCompositeCanvas() // 当前这一张
|
||||
| 历史快照升级 | ✅ `snapshotState()` 记录完整图层集合(含 image 引用),能撤销「新建/删除图层」,这是复制新层与还原原图可撤销的前提 |
|
||||
| 历史面板 / 多选 / 亮色主题 / 草稿 | ⏳ P3/P5 |
|
||||
|
||||
**浮动操作条已按 §8 决策先做出来上线,等待用户真站体验后裁定**;它是纯视图(只调 `runCommand`),替换或移除不影响选区命令。
|
||||
**浮动操作条已按 §8 决策先做出来上线,等待用户在桌面客户端体验后裁定**;它是纯视图(只调 `runCommand`),替换或移除不影响选区命令。
|
||||
|
||||
---
|
||||
|
||||
@@ -340,11 +341,11 @@ getCompositeCanvas() // 当前这一张
|
||||
| CSP | 单文件经典脚本 IIFE;禁 `eval` / `new Function` / ESM / CDN;样式 JS 注入 `<style>`;`toBlob` 要求 origin-clean ⇒ 远程图片必须 `fetch → blob → dataURL`(现有 `onPaste` 已按此实现) |
|
||||
| 宿主争抢 paste | 宿主在 window 气泡阶段也监听粘贴(建 ref 节点 + 下载)。编辑器继续在 document 捕获阶段 `stopImmediatePropagation()`。新增「复制选区到系统剪贴板」需要 `ClipboardItem` + 用户手势 + 权限,失败必须有 toast 降级 |
|
||||
| 选项栏横向排布 | `.iwb-editor-optionbar-body` 是 `overflow-x: auto` 的 flex。**任何 `margin-left: auto` 都会把其后内容整组推到最右**,排满时直接滚出可视区 —— `v1.9.1` 就是 `.iwb-opt-sep` 带了 `auto`,导致选区按钮在选择工具下「消失」。留白只允许放在末尾的 `.iwb-opt-hint`;中文双字按钮必须 `white-space: nowrap`,否则会竖排 |
|
||||
| 草稿持久化 | `ctx.storage` 是 localStorage 命名空间小 KV(`get/set/remove/keys`),**不能塞像素**;`ctx.settings` 适合存输出预设与面板开合。若要做工程草稿,只能存元数据 + 宿主节点引用;真要存图层像素需插件自建 IndexedDB 库(必须自带 `onupgradeneeded` 建表,宿主踩过这个坑)或与宿主协商新能力 |
|
||||
| 草稿持久化 | `ctx.storage` 是宿主提供的命名空间小 KV(`get/set/remove/keys`),**不能塞像素**;`ctx.settings` 适合存输出预设与面板开合。若要做工程草稿,只能存元数据 + 宿主节点引用;真要存图层像素需插件自建 IndexedDB 库(必须自带 `onupgradeneeded` 建表,宿主踩过这个坑)或与宿主协商新能力 |
|
||||
| 节点模型 | 宿主 `setNodeImage` / `createImageNode` 只收一张图;导出即扁平化。要做「可继续编辑的工程」需要宿主侧支持节点附加数据 ⇒ 属于跨仓变更,P5 再评估 |
|
||||
| 上游关系 | 编辑器移植自 `iwb-plaus/iwb-cutout-extension`,README 已警告 1.0.5 的 z 序修复不能整目录覆盖回去。P0 的大改等于正式分叉,应在 README 明确改为「一次性移植 + 独立演进」,避免以后误回灌 |
|
||||
| 发布契约 | 文件名 `plugin-image-annotate.js`、id 一致、SRI、内容寻址名、清单合并、tag 反查;脚本守卫强制「工作区干净 + HEAD 已在 origin/main」 |
|
||||
| 测试 | 本地 mock 探针(直接注入 `src/index.js` + mock host)用于发布前验证;真站 e2e(CSP / KV / SRI)用于发布后验证;两者都保留 |
|
||||
| 发布契约 | 文件名 `plugin-image-annotate.<sha12>.js`(内容寻址)、id 一致、SRI;桌面仓同步脚本按白名单重建市场清单;版本以 `package.json` 为准 |
|
||||
| 测试 | 本地 mock 探针(直接注入 `src/index.js` + mock host)用于发布前验证;桌面客户端 e2e(CSP / 市场安装 / SRI)用于发布后验证;两者都保留 |
|
||||
|
||||
---
|
||||
|
||||
@@ -357,7 +358,7 @@ getCompositeCanvas() // 当前这一张
|
||||
| 1 | **选区 `Delete` 只作用当前图层** | 用 `S.selection.path` 对**当前活动层**做 `destination-out`,不动其它层;`base` 处于锁定态时给 toast 提示「原图层已锁定,请先解锁」,不提供「清所有可见层」入口。清除走 `execute()`,可 Ctrl+Z。 |
|
||||
| 2 | **「清空标注」=全部还原** | 一键回到**刚打开这张图时的初始态**:删除所有非 `base` 图层(含粘贴/导入/选区复制产生的层)、清空所有绘制像素、复位变换与选区、保留 `base` 原始像素。整步记一个历史快照,**可撤销**。按钮标签改为「还原原图」避免歧义;不再留空白层。 |
|
||||
| 3 | **≤500KB 做成输出预设** | 输出面板新增可切换预设「电商 800×800 · ≤500KB」:尺寸 800×800、长边占比 80%(640px)、透明 PNG 或白底 JPG **由用户当前选的单一格式决定,一次只产一个结果**;编码质量迭代到 ≤500KB。预设选择存 `ctx.settings`,下次打开沿用。默认仍是「原尺寸 PNG」,不默认启用预设。 |
|
||||
| 4 | **浮动操作条:先做,体验后定** | 本轮按 §4.1 实现选区旁的浮动条并上线,供用户真站体验;「好不好用、要不要保留/换位置/改内容」由体验结论决定,**不作为开工前置条件**。实现上保持它是纯视图(`floating.js` 只调用命令层),日后替换或移除不影响选区功能。 |
|
||||
| 4 | **浮动操作条:先做,体验后定** | 本轮按 §4.1 实现选区旁的浮动条并上线,供用户在桌面客户端体验;「好不好用、要不要保留/换位置/改内容」由体验结论决定,**不作为开工前置条件**。实现上保持它是纯视图(`floating.js` 只调用命令层),日后替换或移除不影响选区功能。 |
|
||||
|
||||
配套已按推荐默认落地(无需再问):不设菜单栏、数字键 1–0 保留兼容、`Ctrl+V` 维持「贴为新图层」、选区贴入用 `Ctrl+Shift+V`、正式分叉不回灌 `iwb-plaus`、优先级 **P0 → P1**,输出预设随 P1 一起带上(改动小)。
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/image-annotate",
|
||||
"private": true,
|
||||
"version": "1.16.0",
|
||||
"version": "1.20.7",
|
||||
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
|
||||
"ibwPlugin": {
|
||||
"id": "image-annotate",
|
||||
|
||||
@@ -232,6 +232,10 @@
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
/* 撤销 / 重做 / 还原(v1.18):搬进工具条末端后需要一个 flex 容器,
|
||||
否则三个 button 之间是 inline-block 的空隙,和左边 4px gap 的工具按钮对不齐。 */
|
||||
.iwb-editor-history { display: flex; align-items: center; gap: 4px; }
|
||||
|
||||
.iwb-editor-tool, .iwb-editor-action {
|
||||
background: #313244;
|
||||
border: none;
|
||||
@@ -273,7 +277,6 @@
|
||||
.iwb-editor-params .iwb-editor-zoom { margin-left: auto; order: 20; }
|
||||
.iwb-editor-top-colors { display: none; }
|
||||
|
||||
.iwb-editor-colors { display: flex; gap: 4px; }
|
||||
.iwb-editor-color {
|
||||
width: 20px; height: 20px;
|
||||
border-radius: 50%;
|
||||
@@ -1783,17 +1786,33 @@
|
||||
|
||||
|
||||
.iwb-editor-color-pop {
|
||||
position: absolute; z-index: 60; display: flex; flex-direction: column; align-items: stretch; gap: 9px;
|
||||
padding: 10px 12px; border-radius: 12px;
|
||||
position: absolute; z-index: 60; display: flex; flex-direction: column; align-items: stretch; gap: 7px;
|
||||
/* 固定宽度(不是让内容撑):绝对定位元素是 shrink-to-fit,宽度会跟着最长内容走 ——
|
||||
文字工具多出「底色」tab 时头部变宽,弹层当场变宽 17px 再跳回来,定位也要重算。
|
||||
440 = 内容 416(SV 176 + 8 + 色相 16 + 10 + 1 + 10 + 色块 195)+ 左右 padding 22 + 边框 2。 */
|
||||
box-sizing: border-box; width: 440px;
|
||||
padding: 9px 11px; border-radius: 12px;
|
||||
background: rgba(24, 24, 37, 0.97); border: 1px solid #313244;
|
||||
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.55);
|
||||
-webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);
|
||||
}
|
||||
.iwb-editor-color-pop[hidden] { display: none; }
|
||||
/* 弹层头部:说明现在调的是描边还是填充,并可直接换;右侧是「无」(仅填充) */
|
||||
/* 弹层头部(v1.19 一行装完):
|
||||
调哪个槽(描边/填充/底色)│ 吸管 + 色值 │ 去色 │ 图钉
|
||||
原来「吸管 + 色值」在右列占一整块,现在提到头部,body 的整块高度都留给色块。 */
|
||||
.iwb-color-pop-head { display: flex; align-items: center; gap: 6px; }
|
||||
/* 竖线:分隔「调哪个槽 / 取色工具 / 去色·钉住」三组,比空白更清楚,又不加边框重量 */
|
||||
.iwb-color-pop-bar { width: 1px; height: 16px; background: #313244; flex: 0 0 auto; }
|
||||
/* 「吸管 + 色值 + 图钉」整组贴最右(margin-left:auto,v1.20.1)。
|
||||
v1.20 只推图钉、吸管与色值紧跟 tab —— tab 从 2 个变 3 个(文字工具加「底色」),
|
||||
这组就整块左右浮一次。现在 tab 组独占左侧、空隙全给它吸收,右组从第一条竖线起整体钉住。 */
|
||||
.iwb-color-pop-tools { margin-left: auto; display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }
|
||||
|
||||
.iwb-color-pop-tab {
|
||||
display: inline-flex; align-items: center; gap: 5px; height: 24px; padding: 0 9px;
|
||||
/* 不许被压缩、不许折行:头部一行要同时装下 tab + 吸管 + 色值 + 去色 + 图钉,
|
||||
宽度不够时该缩的是色值框(flex:0 1),不是把「描边」压成竖排两个字 */
|
||||
flex: 0 0 auto; white-space: nowrap;
|
||||
border: 1px solid transparent; border-radius: 7px; background: #232334;
|
||||
color: #a6adc8; font: 500 11.5px/1 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif;
|
||||
cursor: pointer;
|
||||
@@ -1810,41 +1829,93 @@
|
||||
background-image: linear-gradient(135deg, transparent calc(50% - 1px), #f38ba8 calc(50% - 1px), #f38ba8 calc(50% + 1px), transparent calc(50% + 1px));
|
||||
}
|
||||
.iwb-color-pop-tab[hidden] { display: none; }
|
||||
/* 去色(v1.20,用户 2026-11-10):头部那颗带文字的按钮下移到「常用色第一格」,
|
||||
尺寸、间距跟色块完全一致(20px 圆),只是画虚线边框 + 斜圈图标 ——
|
||||
它是开关不是色块,所以不用填充色表达状态,只换边框/图标色。
|
||||
永远显示(不可用时不 hidden,只 disabled + 变灰),位置才记得住、头部也不重排。 */
|
||||
.iwb-color-pop-none {
|
||||
margin-left: auto; display: inline-flex; align-items: center; gap: 5px; height: 24px; padding: 0 9px;
|
||||
border: 1px dashed #585b70; border-radius: 7px; background: transparent; color: #a6adc8;
|
||||
font: 500 11.5px/1 -apple-system, BlinkMacSystemFont, "PingFang SC", sans-serif; cursor: pointer;
|
||||
flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 20px; height: 20px; padding: 0; margin: 0; box-sizing: border-box;
|
||||
border: 1px dashed #585b70; border-radius: 50%; background: transparent; color: #a6adc8;
|
||||
cursor: pointer; transition: transform 0.08s ease, border-color 0.12s ease, color 0.12s ease;
|
||||
}
|
||||
.iwb-color-pop-none span {
|
||||
width: 11px; height: 11px; border-radius: 3px; display: block; background-color: #45475a;
|
||||
background-image: linear-gradient(135deg, transparent calc(50% - 1px), #f38ba8 calc(50% - 1px), #f38ba8 calc(50% + 1px), transparent calc(50% + 1px));
|
||||
.iwb-color-pop-none svg { flex: 0 0 auto; width: 12px; height: 12px; }
|
||||
/* hover 只对可用态生效:disabled 时不该有放大反馈,否则看着像能点 */
|
||||
.iwb-color-pop-none:not(:disabled):hover { border-color: #f38ba8; color: #f38ba8; transform: scale(1.14); }
|
||||
.iwb-color-pop-none.active { border-style: solid; border-color: #f38ba8; color: #f38ba8; background: rgba(243, 139, 168, 0.14); }
|
||||
/* 不可用:整颗压到 42% 不透明度 —— 灰到能看出「这里有个去色,但现在用不上」,
|
||||
但不至于淡到看不见(32% 时在深底上几乎消失,等于又变成了「消失」,只是慢一点)。
|
||||
cursor 保持 default,不给 pointer。 */
|
||||
.iwb-color-pop-none:disabled,
|
||||
.iwb-color-pop-none.is-disabled {
|
||||
opacity: 0.42; cursor: default; color: #8b8fa8; border-color: #4a4a5e;
|
||||
background: transparent; transform: none;
|
||||
}
|
||||
.iwb-color-pop-none:hover { border-color: #f38ba8; color: #f38ba8; }
|
||||
.iwb-color-pop-none.active { border-style: solid; border-color: #f38ba8; color: #f38ba8; background: rgba(243, 139, 168, 0.12); }
|
||||
.iwb-color-pop-none[hidden] { display: none; }
|
||||
.iwb-color-pop-body { display: flex; align-items: center; gap: 10px; }
|
||||
.iwb-color-pop-body { display: flex; align-items: stretch; gap: 10px; }
|
||||
.iwb-color-pop-picker { display: flex; gap: 8px; flex: 0 0 auto; }
|
||||
.iwb-editor-color-pop .iwb-color-sv { width: 180px; height: 104px; flex: 0 0 180px; }
|
||||
.iwb-editor-color-pop .iwb-color-sv { width: 176px; height: 104px; flex: 0 0 176px; }
|
||||
.iwb-editor-color-pop .iwb-color-hue { width: 16px; height: 104px; flex: 0 0 16px; }
|
||||
.iwb-color-pop-sep { width: 1px; align-self: stretch; background: #313244; flex: 0 0 auto; }
|
||||
.iwb-color-pop-fields { display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }
|
||||
|
||||
/* ==== 色块区(v1.19,用户 2026-11-10)====
|
||||
常用色 8×2 在上、最近色 8×2 在下,块间 1px 细线,不写小标题。
|
||||
8 列 20px = 195px;两排色块(45 + 11 + 45 = 101)刚好填满左侧取色器 104 的高度,
|
||||
所以整个弹层只有头部 + 取色器两层,没有多余留白。 */
|
||||
.iwb-color-pop-side {
|
||||
display: flex; flex-direction: column; justify-content: center;
|
||||
width: 195px; flex: 0 0 195px; gap: 0;
|
||||
}
|
||||
/* 细线分隔:只加在「块与块之间」,第一块前面不加,否则顶部多一条悬空的线。
|
||||
色号比背景亮两档(#3b3b4e):没有小标题时,这条线是唯一能看出「常用 / 最近」分界的东西,
|
||||
按 #313244 画在深底上几乎看不见。 */
|
||||
.iwb-color-pop-side > * + * {
|
||||
border-top: 1px solid #3b3b4e; margin-top: 5px; padding-top: 5px;
|
||||
}
|
||||
.iwb-color-group { display: flex; flex-direction: column; gap: 0; min-width: 0; flex: 0 0 auto; }
|
||||
/* 标题不显示:「常用色 / 最近」各占一行是这块面板最浪费的高度,
|
||||
色块自己的 title 已经写明是哪一个、哪一个最近用过 */
|
||||
.iwb-editor-color-pop .iwb-color-group-label { display: none; }
|
||||
/* display:flex 会盖掉 [hidden] 的默认 display:none,必须显式写一条 */
|
||||
.iwb-color-group[hidden] { display: none; }
|
||||
|
||||
/* 色值输入定宽 96(v1.20.1 由 124 再收窄,用户「设置框可以小一些,现在长了」)。
|
||||
#RRGGBB 七个字符在 13px 等宽下约 55px,加左右 padding 10px 仍有 30px 余量;
|
||||
它现在是右组里的一颗「读数」,不该比吸管/图钉重。仍然定宽不可缩。 */
|
||||
.iwb-editor-color-pop .iwb-editor-color-hex-input {
|
||||
width: 86px; height: 28px; padding: 0 6px; text-align: center;
|
||||
flex: 0 0 96px; width: 96px; height: 26px; padding: 0 4px; text-align: center;
|
||||
font: 600 12px monospace; border-radius: 6px; box-sizing: border-box;
|
||||
}
|
||||
.iwb-editor-color-pop .iwb-editor-color-swatches {
|
||||
display: grid; grid-template-columns: repeat(6, 22px); grid-auto-rows: 22px;
|
||||
gap: 7px; flex: 0 0 auto; align-content: center;
|
||||
display: grid; grid-template-columns: repeat(8, 20px); grid-auto-rows: 20px;
|
||||
gap: 5px; flex: 0 0 auto; align-content: center;
|
||||
}
|
||||
.iwb-editor-color-pop .iwb-editor-color-panel-swatch {
|
||||
width: 22px; height: 22px; padding: 0; border: 0; border-radius: 50%; cursor: pointer;
|
||||
width: 20px; height: 20px; padding: 0; border: 0; border-radius: 50%; cursor: pointer;
|
||||
transition: transform 0.08s ease;
|
||||
}
|
||||
.iwb-editor-color-pop .iwb-editor-color-panel-swatch:hover { transform: scale(1.12); }
|
||||
.iwb-editor-color-pop .iwb-editor-color-panel-swatch:hover { transform: scale(1.14); }
|
||||
.iwb-editor-color-pop .iwb-editor-color-panel-swatch.active {
|
||||
outline: 2px solid #fff; outline-offset: 2px;
|
||||
}
|
||||
.iwb-editor-color-pop .iwb-editor-color-eye { width: 28px; height: 28px; border-radius: 6px; }
|
||||
.iwb-editor-color-pop .iwb-editor-color-eye { width: 26px; height: 26px; border-radius: 6px; flex: 0 0 auto; }
|
||||
|
||||
/* ==== 钉住(v1.18 / v1.19 改为流式)====
|
||||
v1.18 是绝对定位贴右上角(躲开「无」按钮显隐带来的位移);
|
||||
v1.19「吸管 + 色值」也进了头部,头部本来就是一排可变宽控件,
|
||||
图钉跟着流走反而更稳 —— 竖线已经把「去色 | 图钉」和左边隔开,位置不会再被误读。 */
|
||||
.iwb-color-pop-pin {
|
||||
flex: 0 0 auto; width: 24px; height: 24px; padding: 0;
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
border: 1px solid transparent; border-radius: 6px; background: transparent;
|
||||
color: #9aa0b4; cursor: pointer;
|
||||
}
|
||||
.iwb-color-pop-pin:hover { background: #313244; color: #cdd6f4; }
|
||||
/* 钉住态:琥珀色描边 + 淡底。用颜色而不是旋转表达「已钉住」,
|
||||
旋转 45° 的图钉在 13px 下看起来像歪掉的问号。 */
|
||||
.iwb-color-pop-pin.active {
|
||||
background: rgba(232, 167, 53, 0.16); border-color: #e8a735; color: #f0b752;
|
||||
}
|
||||
|
||||
/* ================================================================
|
||||
v1.4:侧栏「快速效果」
|
||||
@@ -2072,19 +2143,20 @@
|
||||
/* 选项栏里色块旁边的分组标签,和「描边 / 底色」这类双字按钮区分开 */
|
||||
.iwb-opt-swatch-label { color: #7f849c; font-size: 11px; flex: 0 0 auto; }
|
||||
|
||||
/* 「最近使用」:色板弹层里 4 列 × 2 行,空的时候整块隐藏(不占位) */
|
||||
/* 「最近使用」:与常用色同一套 8 列 20px 网格(v1.19 起最多 16 个 = 铺满两排),
|
||||
空的时候整块隐藏(不占位)。 */
|
||||
.iwb-editor-color-pop .iwb-editor-recent-colors {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 18px);
|
||||
grid-auto-rows: 18px;
|
||||
grid-template-columns: repeat(8, 20px);
|
||||
grid-auto-rows: 20px;
|
||||
gap: 5px;
|
||||
flex: 0 0 auto;
|
||||
align-content: center;
|
||||
}
|
||||
.iwb-editor-recent-colors[hidden] { display: none; }
|
||||
.iwb-editor-color-pop .iwb-editor-recent-colors .iwb-editor-color-panel-swatch {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
@@ -2120,53 +2192,12 @@
|
||||
.iwb-editor-side-resizer:hover::after,
|
||||
.iwb-editor-side-resizer.is-dragging::after { background: #e8a735; }
|
||||
|
||||
/* ---- 2) 右栏调色面板 ---- */
|
||||
.iwb-editor-colors {
|
||||
display: flex; flex-direction: column; gap: 9px;
|
||||
padding: 9px 10px 10px; border-radius: 10px;
|
||||
background: #1e1e2c; border: 1px solid #2f2f42;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
.iwb-editor-colors-head { display: flex; align-items: center; justify-content: space-between; gap: 6px; }
|
||||
.iwb-editor-colors-title { font-size: 13px; font-weight: 600; color: #cdd6f4; }
|
||||
.iwb-editor-colors-hint { font-size: 11.5px; color: #7f87a3; }
|
||||
/* ---- 2) 右栏调色面板:已删(v1.19,用户 2026-11-10) ----
|
||||
颜色只剩工具栏弹层一处。弹层钉住后本来就常开,右栏那份只是重复占位。
|
||||
原来这里的 .iwb-editor-colors / .iwb-editor-colors-head / 以及一批
|
||||
`.iwb-editor-colors .iwb-color-pop-*` 覆盖规则(弹层横排、右栏竖排)全部移除 ——
|
||||
少一层「同一份 DOM 两套布局」的分支,改色板不会再出现「改了一处另一处没跟上」。 */
|
||||
|
||||
/* 弹层是横排一行;右栏窄,改成竖排:调色器全宽 → HEX 一行 → 常用色 → 最近。
|
||||
结构完全一样(同一份 DOM),差异全在这里用容器选择器覆盖。 */
|
||||
.iwb-editor-colors .iwb-color-pop-head { flex-wrap: wrap; gap: 5px; }
|
||||
.iwb-editor-colors .iwb-color-pop-tab { padding: 0 8px; }
|
||||
.iwb-editor-colors .iwb-color-pop-body { flex-direction: column; align-items: stretch; gap: 8px; }
|
||||
.iwb-editor-colors .iwb-color-pop-sep { display: none; }
|
||||
.iwb-editor-colors .iwb-color-pop-picker { width: 100%; gap: 6px; }
|
||||
.iwb-editor-colors .iwb-color-sv { flex: 1 1 auto; width: auto; height: 118px; }
|
||||
.iwb-editor-colors .iwb-color-hue { width: 16px; height: 118px; flex: 0 0 16px; }
|
||||
.iwb-editor-colors .iwb-color-pop-fields { width: 100%; gap: 6px; }
|
||||
.iwb-editor-colors .iwb-editor-color-hex-input { flex: 1 1 auto; width: auto; height: 28px; }
|
||||
.iwb-editor-colors .iwb-editor-color-eye { width: 30px; height: 28px; border-radius: 6px; flex: 0 0 auto; }
|
||||
|
||||
/* 分组:右栏显示「常用色 / 最近」小标题,弹层里隐藏(那里横向排得下,加标题反而占高) */
|
||||
.iwb-color-group { display: flex; flex-direction: column; gap: 6px; min-width: 0; flex: 0 0 auto; }
|
||||
.iwb-color-group-label { font-size: 11.5px; color: #7f87a3; letter-spacing: 0.3px; }
|
||||
.iwb-editor-color-pop .iwb-color-group { gap: 0; }
|
||||
.iwb-editor-color-pop .iwb-color-group-label { display: none; }
|
||||
/* display:flex 会盖掉 [hidden] 的默认 display:none,必须显式写一条 */
|
||||
.iwb-color-group[hidden] { display: none; }
|
||||
|
||||
/* 右栏色块:网格按容器宽度自适应,拖宽后一行能多放几个 */
|
||||
.iwb-editor-colors .iwb-editor-color-swatches {
|
||||
display: grid; grid-template-columns: repeat(auto-fill, minmax(24px, 1fr));
|
||||
gap: 6px; width: 100%;
|
||||
}
|
||||
.iwb-editor-colors .iwb-editor-recent-colors {
|
||||
display: grid; grid-template-columns: repeat(auto-fill, minmax(22px, 1fr));
|
||||
gap: 6px; width: 100%;
|
||||
}
|
||||
.iwb-editor-colors .iwb-editor-color-panel-swatch {
|
||||
width: 100%; aspect-ratio: 1 / 1; min-height: 22px; padding: 0; border: 0;
|
||||
border-radius: 50%; cursor: pointer; transition: transform 0.08s ease;
|
||||
}
|
||||
.iwb-editor-colors .iwb-editor-color-panel-swatch:hover { transform: scale(1.1); }
|
||||
.iwb-editor-colors .iwb-editor-color-panel-swatch.active { outline: 2px solid #fff; outline-offset: 2px; }
|
||||
|
||||
/* ---- 3) 字号 +1 档 ----
|
||||
旧值大量是 10–11.5px(按 1440 宽屏定的),在 2K/4K 与系统缩放 125% 下发虚。
|
||||
@@ -2226,7 +2257,8 @@
|
||||
#iwb-editor-overlay .iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-val,
|
||||
#iwb-editor-overlay .iwb-editor-left .iwb-editor-zoom .iwb-editor-zoom-fit { font-size: 12px; }
|
||||
|
||||
/* 调色面板本体 */
|
||||
#iwb-editor-overlay .iwb-color-pop-tab,
|
||||
#iwb-editor-overlay .iwb-color-pop-none { font-size: 12.5px; height: 26px; }
|
||||
/* 调色面板本体(v1.20:去色已下移到色块网格,这里只剩 tab 需要放大字号;
|
||||
去色是 20px 格子,高度必须跟色块一致,别被这条统一字号的规则顶成 26px) */
|
||||
#iwb-editor-overlay .iwb-color-pop-tab { font-size: 12.5px; height: 26px; }
|
||||
#iwb-editor-overlay .iwb-color-pop-none { width: 20px; height: 20px; }
|
||||
#iwb-editor-overlay .iwb-editor-color-pop .iwb-editor-color-hex-input { font-size: 13px; }
|
||||
@@ -10,29 +10,57 @@ import { S, runtime } from './state.js'
|
||||
import { bindEvents } from './events.js'
|
||||
|
||||
|
||||
// ============ 调色面板(两处共用) ============
|
||||
// ============ 调色面板(工具栏弹层) ============
|
||||
/**
|
||||
* v1.16:调色面板从「只能弹层」变成「右栏常驻 + 弹层保留」,两处用同一份 DOM。
|
||||
*
|
||||
* 为什么抽成函数而不是复制两段 HTML:这套控件有 4 组联动(tab 高亮、SV/色相指示点、
|
||||
* HEX 回填、常用色/最近色的 active 圈),复制两段 = 以后每加一种颜色语义都要改两遍,
|
||||
* 漏一处就是「一边改了另一边不变」。同一份结构 + 按 `[data-color-surface]` 遍历,
|
||||
* 才可能保证一致(events.js#updateColorUI 就是按 surface 逐个刷的)。
|
||||
*
|
||||
* 布局差异全部交给 CSS:弹层是横排一行,右栏窄,改成竖排(picker 全宽、色块自动换行)。
|
||||
* v1.19:右栏常驻面板删掉,只剩工具栏弹层这一份(钉住后它本来就是常开的)。
|
||||
* 仍抽成函数而不是写在模板里:这套控件有 4 组联动(tab 高亮、SV/色相指示点、
|
||||
* HEX 回填、常用色/最近色的 active 圈),events.js#updateColorUI 按
|
||||
* `[data-color-surface]` 逐个刷 —— 留着这层抽象,将来若再加一处面板不用重写联动。
|
||||
*/
|
||||
/* 15 个常用色 + 第一格「去色」= 色板里 8 列 × 2 行(v1.20)。
|
||||
排布刻意成对:第一行是 7 个饱和亮色(红橙黄绿青蓝粉)+ 去色打头,
|
||||
第二行是 4 个中性色(白/浅灰/中灰/黑)+ 4 个同色系「深一档」,
|
||||
深红/深绿/深蓝/深紫 在浅色底图上比亮色稳,做描边不刺眼。
|
||||
亮紫 #aa44ff 让位给第一格的「去色」(v1.20,用户 2026-11-10:去色放常用色第一个)——
|
||||
紫色还留着深一档的 #6b4fbb,色相不缺,8×2 的网格也不用改成 3 行。 */
|
||||
const COMMON_COLORS = [
|
||||
'#ff4444', '#ff8a00', '#ffd400', '#4cd964', '#00bfa5', '#4488ff',
|
||||
'#aa44ff', '#ff66aa', '#ffffff', '#d0d0d0', '#808080', '#000000'
|
||||
'#ff4444', '#ff8a00', '#ffd400', '#4cd964', '#00bfa5', '#4488ff', '#ff66aa',
|
||||
'#ffffff', '#d0d0d0', '#808080', '#000000', '#c0392b', '#0f9d58', '#1677ff', '#6b4fbb'
|
||||
]
|
||||
|
||||
/** 色板面板(v1.19 起只有工具栏弹层一份,右栏常驻面板已删)
|
||||
*
|
||||
* 头部一行:调哪个槽(描边/填充/底色)│ 吸管 + 色值 │ 图钉
|
||||
* 把「吸管 + 色值」提到头部,是为了让下面整块高度都留给色块:
|
||||
* 常用色 2 排 + 最近色 2 排,一屏就能点到,不用滚动、也不用二次点开。
|
||||
*
|
||||
* v1.20(用户 2026-11-10):头部不再随上下文增减控件。
|
||||
* 原因是文字工具会多出「底色」tab,头部一行本来就贴着 440 的极限,
|
||||
* 再去掉/加上「去色」就会把色值框和吸管挤变形(甚至整颗按钮被 flex 抵没)。
|
||||
* 现在「去色」下移到常用色网格的第一格 —— 位置永远固定,不可用时只是变灰 + disabled,
|
||||
* 头部元素因此全是定宽,切工具时头部不再重排。
|
||||
*/
|
||||
function colorSurfaceHtml() {
|
||||
return `
|
||||
<div class="iwb-color-pop-head">
|
||||
<button type="button" class="iwb-color-pop-tab active" data-color-slot="stroke" title="正在调描边色(形状描边 / 画笔 / 文字色)"><i></i><span class="iwb-color-pop-tab-label">描边</span></button>
|
||||
<button type="button" class="iwb-color-pop-tab" data-color-slot="fill" title="正在调填充色(形状内部颜色 / 文字描边色)"><i></i><span class="iwb-color-pop-tab-label">填充</span></button>
|
||||
<button type="button" class="iwb-color-pop-tab" data-color-slot="bg" hidden title="正在调文本框底色(垫在文字下面)"><i></i><span class="iwb-color-pop-tab-label">底色</span></button>
|
||||
<button type="button" class="iwb-color-pop-none" data-color-none="1" title="无填充:形状内部透明,只留描边"><span></span>无</button>
|
||||
<!-- 吸管 + 色值 + 图钉(v1.20.1,用户 2026-11-10):整组右对齐。
|
||||
v1.20 只把图钉推到最右,吸管和色值还紧跟 tab —— tab 数量一变
|
||||
(文字工具多出「底色」),这组就左右浮一次,用户截图里就是这个现象。
|
||||
现在 tab 组独占左侧、剩余空隙由它吸收,右组整体钉在右侧,切工具纹丝不动。
|
||||
右组前面那条竖线删掉了:空隙已经把「选槽」和「取色」分开,
|
||||
右对齐后它只会孤零零悬在空白里。留下的那条竖线是分隔「图钉」这个常驻开关。 -->
|
||||
<span class="iwb-color-pop-tools">
|
||||
<button type="button" class="iwb-editor-color-eye" data-action="palettePick" title="吸色:切到吸管工具,在画布上点一下取色"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3Z"/></svg></button>
|
||||
<input class="iwb-editor-color-hex-input" value="#ff4444" maxlength="7" spellcheck="false" autocomplete="off" title="十六进制颜色,回车生效">
|
||||
<span class="iwb-color-pop-bar"></span>
|
||||
<!-- 钉住(v1.18,用户 2026-11-10):调色常常要连着改好几处,每次点开色板太碎。
|
||||
钉住后点画布 / 点别处都不收起,只有再点一次图钉、按 Esc、或点吸管才收。
|
||||
图标是竖向图钉(头朝上),激活态整颗变琥珀色。 -->
|
||||
<button type="button" class="iwb-color-pop-pin" data-action="pinColorPop" aria-pressed="false" title="钉住色板:一直开着,点画布也不收起(再点一次取消)"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17v5"/><path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z"/></svg></button>
|
||||
</span>
|
||||
</div>
|
||||
<div class="iwb-color-pop-body">
|
||||
<div class="iwb-color-pop-picker">
|
||||
@@ -40,20 +68,25 @@ import { bindEvents } from './events.js'
|
||||
<div class="iwb-color-hue"><span></span></div>
|
||||
</div>
|
||||
<span class="iwb-color-pop-sep"></span>
|
||||
<div class="iwb-color-pop-fields">
|
||||
<button type="button" class="iwb-editor-color-eye" data-action="palettePick" title="吸色:切到吸管工具,在画布上点一下取色"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 22 1-1h3l9-9"/><path d="M3 21v-3l9-9"/><path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3Z"/></svg></button>
|
||||
<input class="iwb-editor-color-hex-input" value="#ff4444" maxlength="7" spellcheck="false" autocomplete="off" title="十六进制颜色,回车生效">
|
||||
</div>
|
||||
<span class="iwb-color-pop-sep"></span>
|
||||
<div class="iwb-color-group">
|
||||
<span class="iwb-color-group-label">常用色</span>
|
||||
<div class="iwb-editor-color-swatches">
|
||||
${COMMON_COLORS.map(c => `<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="${c}" style="background:${c}" title="${c}"></button>`).join('')}
|
||||
<!-- 色块区(v1.19):常用色 8×2 在上、最近色 8×2 在下,中间 1px 细线分隔。
|
||||
不写「常用色 / 最近」小标题 —— 每个色块的 title 已经写明是哪一个,
|
||||
而标题要各占一行,是这块面板最浪费的高度(v1.18 已这么定,v1.19 沿用)。 -->
|
||||
<div class="iwb-color-pop-side">
|
||||
<div class="iwb-color-group">
|
||||
<span class="iwb-color-group-label">常用色</span>
|
||||
<div class="iwb-editor-color-swatches">
|
||||
<!-- 去色(v1.20,用户 2026-11-10):原来是头部一颗带文字的按钮,现在占常用色第一格。
|
||||
好处有二:① 位置永远固定,切到文字/箭头这类「去不掉色」的上下文只是变灰,
|
||||
不会整颗消失;② 头部腾出一颗按钮的宽度,文字工具多出「底色」tab 也挤不坏色值框。
|
||||
含义随当前槽变(无描边 / 无填充 / 无底色),title 在 updateColorUI 里刷。 -->
|
||||
<button type="button" class="iwb-color-pop-none" data-color-none="1" title="去色:当前这一项不上色(描边/填充/底色按上下文透明)"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="m5.6 5.6 12.8 12.8"/></svg></button>
|
||||
${COMMON_COLORS.map(c => `<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="${c}" style="background:${c}" title="${c}"></button>`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
<div class="iwb-color-group">
|
||||
<span class="iwb-color-group-label">最近</span>
|
||||
<div class="iwb-editor-recent-colors" hidden title="最近使用"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="iwb-color-group">
|
||||
<span class="iwb-color-group-label">最近</span>
|
||||
<div class="iwb-editor-recent-colors" hidden title="最近使用"></div>
|
||||
</div>
|
||||
</div>`
|
||||
}
|
||||
@@ -75,11 +108,9 @@ import { bindEvents } from './events.js'
|
||||
<button class="iwb-editor-btn iwb-editor-btn-replace" data-action="replace" title="用当前编辑结果覆盖原图">覆盖</button>
|
||||
<button class="iwb-editor-btn iwb-editor-btn-cancel" data-action="cancel" title="放弃修改并退出">退出</button>
|
||||
</div>
|
||||
<div class="iwb-editor-history">
|
||||
<button class="iwb-editor-action" data-action="undo" title="撤销 (Ctrl+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg></button>
|
||||
<button class="iwb-editor-action" data-action="redo" title="重做 (Ctrl+Shift+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg></button>
|
||||
<button class="iwb-editor-action iwb-editor-action-reset" data-action="reset" title="还原原图:删掉所有标注/图层,回到打开时的样子(Ctrl+Z 可撤销)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/></svg></button>
|
||||
</div>
|
||||
<!-- 撤销/重做/还原(v1.18,用户 2026-11-10):从顶栏搬到画布底部工具栏最右侧。
|
||||
理由:这三个是「画画时会连着按」的操作,手在画布上,不该抬头去顶栏找。
|
||||
顶栏只留会话组(新建/覆盖/退出)与输出。 -->
|
||||
<!-- 顶栏命令带已清空(v1.13):
|
||||
四个「置顶/上移/下移/置底」按钮删除(图层面板可拖动 + Ctrl+]/[ 已覆盖);
|
||||
「适应窗口 / 收起侧栏」搬到画布底部工具栏最右侧,离画布更近。
|
||||
@@ -213,6 +244,15 @@ import { bindEvents } from './events.js'
|
||||
<span class="iwb-editor-divider"></span>
|
||||
<button class="iwb-editor-tool iwb-editor-view-btn" data-action="zoomFit" title="适应窗口 (Ctrl+0):整张图缩放到刚好放得下"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 3 3 3 3 9"/><polyline points="15 3 21 3 21 9"/><polyline points="3 15 3 21 9 21"/><polyline points="21 15 21 21 15 21"/></svg></button>
|
||||
<button class="iwb-editor-tool iwb-editor-view-btn" data-action="togglePanels" title="收起 / 展开侧栏 (Tab)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="2"/><line x1="9" y1="4" x2="9" y2="20"/></svg></button>
|
||||
|
||||
<!-- 撤销 / 重做 / 还原(v1.18):从顶栏移到工具条最右。
|
||||
放在视图快捷之后,是整条工具栏真正的末端 —— 手在画布区时离得最近。 -->
|
||||
<span class="iwb-editor-divider"></span>
|
||||
<div class="iwb-editor-history">
|
||||
<button class="iwb-editor-action" data-action="undo" title="撤销 (Ctrl+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg></button>
|
||||
<button class="iwb-editor-action" data-action="redo" title="重做 (Ctrl+Shift+Z)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"/></svg></button>
|
||||
<button class="iwb-editor-action iwb-editor-action-reset" data-action="reset" title="还原原图:删掉所有标注/图层,回到打开时的样子(Ctrl+Z 可撤销)"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6"/><path d="M3 12a9 9 0 0 1 15-6.7L21 8"/><path d="M3 22v-6h6"/><path d="M21 12a9 9 0 0 1-15 6.7L3 16"/></svg></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="iwb-editor-zoom-hint">滚轮缩放 · 抓手/空格/中键拖拽自由移动画布</div>
|
||||
@@ -221,19 +261,11 @@ import { bindEvents } from './events.js'
|
||||
<!-- v1.16:侧栏宽度拖拽手柄。贴在侧栏左边缘(它在画布右侧),
|
||||
双击复位。宽度写进 CSS 变量 --iwb-side-w,由 --iwb-side-w 统一裁各条 width 规则。 -->
|
||||
<div class="iwb-editor-side-resizer" data-side-resizer="1" title="拖动调整侧栏宽度,双击复位"></div>
|
||||
<!-- 调色面板(v1.16):从弹层搬进来常驻一份,弹层保留。
|
||||
两处是同一份 DOM(dom.js#colorSurfaceHtml),靠 data-color-surface 区分与遍历,
|
||||
不存在「一边改了另一边不变」。顶部色格 = 当前元素可调的颜色项,
|
||||
跟随选中对象变化:形状=描边/填充,文字=文字/描边/底色,箭头=只要描边。 -->
|
||||
<section class="iwb-editor-colors" data-color-surface="side">
|
||||
<div class="iwb-editor-colors-head">
|
||||
<span class="iwb-editor-colors-title">颜色</span>
|
||||
<span class="iwb-editor-colors-hint" title="点上面的色格选择要调哪个颜色">点色格切换</span>
|
||||
</div>
|
||||
${colorSurfaceHtml()}
|
||||
</section>
|
||||
<!-- 调色板已迁到工具栏弹层(v1.3,用户裁定 2026-11-05):
|
||||
侧栏只留快速效果 + 缩放;色板 DOM 在 modal 末尾的 .iwb-editor-color-pop -->
|
||||
<!-- 右栏常驻调色面板已删(v1.19,用户 2026-11-10:「右边栏的调色模块就可以去掉了」)。
|
||||
理由:弹层钉住之后它一直是开着的,右栏那份同样内容只是在跟弹层抢注意力,
|
||||
还白占一块最显眼的位置。颜色只剩弹层一处(modal 末尾 .iwb-editor-color-pop),
|
||||
右栏现在从「图片调节」直接开始。 -->
|
||||
|
||||
<!-- 图片调节(v1.15):连续调色,作用于当前位图图层(默认原图)。
|
||||
行由 adjust.js#mountAdjustPanel() 按 ADJUST_DEFS 生成 —— 参数表只维护一份,
|
||||
不在 DOM 里再抄一遍(这个项目已经因为「同一个概念两处各写一份」栽过几次)。
|
||||
|
||||
+142
-9
@@ -46,12 +46,32 @@ import { toast } from './commands.js'
|
||||
invert: {
|
||||
label: '反白', hint: '反相:明暗翻转,白底变黑底',
|
||||
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
|
||||
render: (canvas, v) => { if (v > 0) filterCanvas(canvas, 'invert(' + (v / 100) + ')') }
|
||||
render: (canvas, v) => {
|
||||
if (v <= 0) return
|
||||
const k = v / 100
|
||||
if (FILTER_SUPPORTED) { filterCanvas(canvas, 'invert(' + k + ')'); return }
|
||||
// 线性插值到反相值:out = c + (255 - 2c) * k
|
||||
const ok = mapPixels(canvas, (r, g, b) => [
|
||||
clamp255(r + (255 - 2 * r) * k),
|
||||
clamp255(g + (255 - 2 * g) * k),
|
||||
clamp255(b + (255 - 2 * b) * k)
|
||||
])
|
||||
if (!ok) blendFallback(canvas, 'invert', k)
|
||||
}
|
||||
},
|
||||
gray: {
|
||||
label: '灰度', hint: '去色,保留明暗层次',
|
||||
param: '强度', unit: '%', min: 0, max: 100, step: 1, def: () => 100,
|
||||
render: (canvas, v) => { if (v > 0) filterCanvas(canvas, 'grayscale(' + (v / 100) + ')') }
|
||||
render: (canvas, v) => {
|
||||
if (v <= 0) return
|
||||
const k = v / 100
|
||||
if (FILTER_SUPPORTED) { filterCanvas(canvas, 'grayscale(' + k + ')'); return }
|
||||
const okGray = mapPixels(canvas, (r, g, b) => {
|
||||
const y = luma(r, g, b)
|
||||
return [clamp255(r + (y - r) * k), clamp255(g + (y - g) * k), clamp255(b + (y - b) * k)]
|
||||
})
|
||||
if (!okGray) blendFallback(canvas, 'gray', k)
|
||||
}
|
||||
},
|
||||
boost: {
|
||||
label: '增强', hint: '提亮并加对比,适合发灰的截图',
|
||||
@@ -59,10 +79,20 @@ import { toast } from './commands.js'
|
||||
render: (canvas, v) => {
|
||||
if (v <= 0) return
|
||||
const k = v / 100
|
||||
// v1.15:旧系数 1+0.12k / 1+0.1k / 1+0.06k 拉满只有 1.12 倍亮度,肉眼看不出变化
|
||||
// (用户反馈「效果现在弱了一些」)。现在拉满 = 1.4 倍亮度 / 1.25 倍对比 / 1.2 倍饱和,
|
||||
// 对应「一眼能看出变亮变通透」,但仍然不过曝 —— 再往上压会先把高光切掉。
|
||||
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: {
|
||||
@@ -71,13 +101,24 @@ import { toast } from './commands.js'
|
||||
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: {
|
||||
label: '柔化', hint: '模糊,弱化背景',
|
||||
param: '半径', unit: 'px', min: 0, max: 16, step: 0.5, def: (canvas) => softRadius(canvas),
|
||||
render: (canvas, v) => { if (v > 0) filterCanvas(canvas, 'blur(' + v + 'px)') }
|
||||
render: (canvas, v) => {
|
||||
if (v <= 0) return
|
||||
if (FILTER_SUPPORTED) filterCanvas(canvas, 'blur(' + v + 'px)')
|
||||
else blurCanvas(canvas, v)
|
||||
}
|
||||
},
|
||||
mosaic: {
|
||||
label: '马赛克', hint: '像素化,用于打码手机号/地址等隐私信息',
|
||||
@@ -115,6 +156,93 @@ import { toast } from './commands.js'
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
// ctx.filter 支持性:Chrome/Edge 支持,macOS WKWebView 长期不支持(赋值会被忽略)。
|
||||
// 不支持时下面全部走像素级兜底,否则「只有马赛克有效」——马赛克本来就不依赖 filter。
|
||||
// ctx.filter 支持性:不能只看「属性是否可赋值」——WKWebView 里属性存在但绘制时被忽略,
|
||||
// 赋值检测会误判为支持。这里做功能性探测:红块过 invert(1) 之后必须变青。
|
||||
const FILTER_SUPPORTED = (function () {
|
||||
try {
|
||||
const src = document.createElement('canvas')
|
||||
src.width = 2; src.height = 2
|
||||
const sctx = src.getContext('2d')
|
||||
sctx.fillStyle = '#ff0000'
|
||||
sctx.fillRect(0, 0, 2, 2)
|
||||
const dst = document.createElement('canvas')
|
||||
dst.width = 2; dst.height = 2
|
||||
const dctx = dst.getContext('2d')
|
||||
dctx.filter = 'invert(1)'
|
||||
dctx.drawImage(src, 0, 0)
|
||||
const d = dctx.getImageData(0, 0, 1, 1).data
|
||||
return d[0] < 60 && d[1] > 180 && d[2] > 180
|
||||
} catch (e) { return false }
|
||||
})()
|
||||
|
||||
/** 逐像素处理(设备像素坐标系直接写回);画布被跨域图污染时 getImageData 会抛错 → 返回 false */
|
||||
function mapPixels(canvas, fn) {
|
||||
const w = canvas.width, h = canvas.height
|
||||
if (!w || !h) return false
|
||||
const ctx = canvas.getContext('2d', { willReadFrequently: true })
|
||||
let img
|
||||
try { img = ctx.getImageData(0, 0, w, h) } catch (e) { return false }
|
||||
const d = img.data
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
if (d[i + 3] === 0) continue
|
||||
const out = fn(d[i], d[i + 1], d[i + 2])
|
||||
d[i] = out[0]; d[i + 1] = out[1]; d[i + 2] = out[2]
|
||||
}
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
ctx.putImageData(img, 0, 0)
|
||||
return true
|
||||
}
|
||||
|
||||
/** 混合模式兜底(读不到像素时):反相用 difference+白,去色用 saturation+灰 */
|
||||
function blendFallback(canvas, mode, strength) {
|
||||
const k = typeof strength === 'number' ? Math.max(0, Math.min(1, strength)) : 1
|
||||
const ctx = canvas.getContext('2d')
|
||||
const copy = document.createElement('canvas')
|
||||
copy.width = canvas.width
|
||||
copy.height = canvas.height
|
||||
copy.getContext('2d').drawImage(canvas, 0, 0)
|
||||
ctx.save()
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
ctx.globalAlpha = 1
|
||||
if (mode === 'invert') { ctx.globalCompositeOperation = 'difference'; ctx.fillStyle = '#ffffff' }
|
||||
else { ctx.globalCompositeOperation = 'saturation'; ctx.fillStyle = '#808080' }
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height)
|
||||
// 按强度混回原图(k=1 全反相,k=0 原样)
|
||||
if (k < 1) {
|
||||
ctx.globalCompositeOperation = 'source-over'
|
||||
ctx.globalAlpha = 1 - k
|
||||
ctx.drawImage(copy, 0, 0)
|
||||
}
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
function luma(r, g, b) { return 0.2126 * r + 0.7152 * g + 0.0722 * b }
|
||||
function clamp255(v) { return v < 0 ? 0 : (v > 255 ? 255 : v) }
|
||||
|
||||
/** 模糊兜底:缩到 1/n 再平滑放大,效果接近 blur 且比卷积快得多 */
|
||||
function blurCanvas(canvas, radius) {
|
||||
const w = canvas.width, h = canvas.height
|
||||
if (!w || !h || radius <= 0) return
|
||||
const n = Math.max(2, Math.min(16, Math.round(radius * 1.6)))
|
||||
const sw = Math.max(1, Math.round(w / n))
|
||||
const sh = Math.max(1, Math.round(h / n))
|
||||
const tmp = document.createElement('canvas')
|
||||
tmp.width = sw; tmp.height = sh
|
||||
const tctx = tmp.getContext('2d')
|
||||
tctx.imageSmoothingEnabled = true
|
||||
tctx.drawImage(canvas, 0, 0, sw, sh)
|
||||
const ctx = canvas.getContext('2d')
|
||||
ctx.save()
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
||||
ctx.globalAlpha = 1
|
||||
ctx.globalCompositeOperation = 'copy'
|
||||
ctx.imageSmoothingEnabled = true
|
||||
ctx.drawImage(tmp, 0, 0, w, h)
|
||||
ctx.restore()
|
||||
}
|
||||
|
||||
/** 马赛克:缩到 1/block 再关掉平滑放大,比逐像素 getImageData 快一个量级 */
|
||||
function pixelateCanvas(canvas, block) {
|
||||
const w = canvas.width, h = canvas.height
|
||||
@@ -205,7 +333,12 @@ import { toast } from './commands.js'
|
||||
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 = undefined
|
||||
|
||||
@@ -357,6 +357,12 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
function onMouseMove(e) {
|
||||
// 记下修饰键:拖动按 Alt 时临时关掉吸附(想停在「差一点点」的位置时用)
|
||||
S._altDown = !!e.altKey
|
||||
// 自愈:拖出窗口/切换应用会丢 mouseup,isDrawing 会永远为 true,后续操作被忽略
|
||||
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
|
||||
@@ -549,6 +555,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
lw: Math.max(1, S.shapeLineWidth),
|
||||
lineWidth: Math.max(1, S.shapeLineWidth),
|
||||
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
|
||||
strokeOn: S.shapeStrokeOn !== false,
|
||||
radius: S.tool === 'rect' ? Math.max(0, S.shapeRadius) : 0,
|
||||
opacity: 1,
|
||||
visible: true
|
||||
@@ -754,6 +761,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
fillColor: S.shapeFillColor, // null = 跟随描边色(改主色时整块跟着变)
|
||||
lw: Math.max(1, S.shapeLineWidth),
|
||||
fill: S.tool === 'rect' || S.tool === 'circle' ? !!S.rectFill : false,
|
||||
strokeOn: S.shapeStrokeOn !== false,
|
||||
radius: S.tool === 'rect' ? Math.max(0, S.shapeRadius) : 0,
|
||||
opacity: 1,
|
||||
visible: true,
|
||||
@@ -899,6 +907,16 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
return sh.type === 'rect' || sh.type === 'circle' || (sh.type === 'pen' && !!sh.closed)
|
||||
}
|
||||
|
||||
/** 「无描边」(v1.17)能不能给:只有「去掉描边后画面还看得见」才给。
|
||||
* 判据就是 fillSlotOn() —— 能填充才谈得上不要描边:
|
||||
* 箭头没有内部、未闭合的钢笔没有面积,去掉描边等于把这个对象删掉,
|
||||
* 这两种情况宁可不给按钮,也别让用户点出一个「看不见的对象」。
|
||||
* 文字不在此列:文字描边是第二格「描边」,早就有「无」了。 */
|
||||
function strokeSlotCanBeNone() {
|
||||
const ctx = colorContext()
|
||||
return ctx.kind === 'shape' && fillSlotOn()
|
||||
}
|
||||
|
||||
/** 文字的三个颜色槽(v1.12)。
|
||||
* 文字对象本来就有三个颜色字段:color(文字本身)/ strokeColor(字的外描边)/
|
||||
* bgColor(文本框底色)。上一版把它们硬塞进「描边 / 填充」两格,第二格其实是
|
||||
@@ -935,9 +953,15 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
const fillOn = sh
|
||||
? (sh.type === 'pen' ? (!!sh.fill && !!sh.closed) : !!sh.fill)
|
||||
: (S.tool === 'pen' ? !!S.penFill : !!S.rectFill)
|
||||
// v1.17:描边也有「有 / 无」两态。老对象没有 strokeOn 字段 ⇒ 视为有描边。
|
||||
// 只有 shape 上下文才谈得上无描边:箭头/画笔那一格是「唯一颜色」,
|
||||
// 显示成斜杠会让人以为画笔也画不出颜色。
|
||||
const strokeOn = ctx.kind !== 'shape'
|
||||
? true
|
||||
: (sh ? (sh.strokeOn !== false) : (S.shapeStrokeOn !== false))
|
||||
return {
|
||||
mode: ctx.kind === 'shape' ? 'shape' : 'single',
|
||||
stroke, fill: rawFill || stroke, fillOn, follow: !rawFill,
|
||||
stroke, strokeOn, fill: rawFill || stroke, fillOn, follow: !rawFill,
|
||||
bg: null, bgOn: false, bgAlpha: 1,
|
||||
strokeName: '描边', fillName: '填充', bgName: '底色'
|
||||
}
|
||||
@@ -972,11 +996,15 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
const dot = strokeBtn.querySelector('i')
|
||||
if (dot) dot.style.backgroundColor = sl.stroke
|
||||
strokeBtn.classList.toggle('active', S.colorTarget === 'stroke')
|
||||
// v1.17:无描边时色块画红斜杠,和「无填充」同一套视觉语言
|
||||
strokeBtn.classList.toggle('is-none', !isText && sl.strokeOn === false)
|
||||
strokeBtn.title = isText
|
||||
? `文字色 ${String(sl.stroke).toUpperCase()}:改文字本身的颜色(右边「描边」是字的外描边)`
|
||||
: (second
|
||||
? `描边色 ${String(sl.stroke).toUpperCase()}:形状描边也用这个值。点开色板调色`
|
||||
: `${strokeName}色 ${String(sl.stroke).toUpperCase()}:点开色板调色`)
|
||||
: (sl.strokeOn === false
|
||||
? '描边:无(只有填充)。点开选色会自动恢复描边'
|
||||
: (second
|
||||
? `描边色 ${String(sl.stroke).toUpperCase()}:形状描边也用这个值。点开色板调色,「无」= 去掉描边`
|
||||
: `${strokeName}色 ${String(sl.stroke).toUpperCase()}:点开色板调色`))
|
||||
const popEl = runtime.el.querySelector('.iwb-editor-color-pop')
|
||||
strokeBtn.setAttribute('aria-expanded', String(!!(popEl && !popEl.hidden && S.colorTarget === 'stroke')))
|
||||
}
|
||||
@@ -1030,19 +1058,31 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
: (isText ? '正在调文字色(文字本身的颜色)' : '正在调描边色'))
|
||||
if (isFill) { tab.classList.toggle('is-none', !sl.fillOn); tab.hidden = !second }
|
||||
if (isBg) { tab.classList.toggle('is-none', !sl.bgOn); tab.hidden = !isText }
|
||||
// 描边格:文字的「描边」是第二格(上面已处理),文字色/单槽上下文不允许「无」
|
||||
if (!isFill && !isBg) tab.classList.toggle('is-none', !isText && sl.strokeOn === false)
|
||||
})
|
||||
// 「无」:形状 = 无填充;文字描边 = 描边宽度 0;文字底色 = 关掉底色块
|
||||
// (文字色没有「无」—— 字没有颜色就等于把字删了,不该给这个按钮)
|
||||
// v1.16:右栏与弹层各有一个「无」,必须按集合刷,否则只有先出现的那个对
|
||||
// 「去色」:形状/钢笔 = 无描边或无填充;文字描边 = 描边宽度 0;文字底色 = 关掉底色块
|
||||
// v1.20(用户 2026-11-10):它现在是常用色网格的第一格,**永远显示**。
|
||||
// 文字色 / 箭头这类「去掉就等于删掉对象」的上下文,改成置灰 + disabled,而不是整颗消失 ——
|
||||
// 消失会让色板每切一次工具就重排一次,位置记不住。
|
||||
const onBg = S.colorTarget === 'bg' && isText
|
||||
const onFill = S.colorTarget === 'fill' && second
|
||||
const showNone = onBg || onFill
|
||||
const onStroke = S.colorTarget === 'stroke' && !isText && strokeSlotCanBeNone()
|
||||
const noneUsable = onBg || onFill || onStroke
|
||||
runtime.el.querySelectorAll('[data-color-none]').forEach(noneBtn => {
|
||||
noneBtn.hidden = !showNone
|
||||
noneBtn.classList.toggle('active', showNone && (onBg ? !sl.bgOn : !sl.fillOn))
|
||||
noneBtn.title = onBg
|
||||
? '无底色:文字后面完全透明'
|
||||
: (isText ? '无描边:把描边宽度置 0,只留文字本身' : '无填充:形状内部透明,只留描边')
|
||||
noneBtn.hidden = false
|
||||
noneBtn.disabled = !noneUsable
|
||||
noneBtn.classList.toggle('is-disabled', !noneUsable)
|
||||
noneBtn.classList.toggle('active', noneUsable && (onBg ? !sl.bgOn : (onFill ? !sl.fillOn : !sl.strokeOn)))
|
||||
noneBtn.title = noneUsable
|
||||
? (onBg
|
||||
? '去色:文字后面完全透明(无底色)'
|
||||
: (onStroke
|
||||
? (sl.strokeOn === false ? '当前已是无描边;点选颜色可恢复描边' : '去色:去掉形状外框,只留内部填充')
|
||||
: (isText ? '去色:把描边宽度置 0,只留文字本身' : '去色:形状内部透明,只留描边')))
|
||||
: (isText && S.colorTarget === 'stroke'
|
||||
? '去色不可用:文字色去掉就等于把文字删了,要隐藏文字请用「清空标注」'
|
||||
: '去色不可用:这一格只有一种颜色,去掉就没有了')
|
||||
})
|
||||
|
||||
const cur = activeColor()
|
||||
@@ -1052,7 +1092,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
if (on) matchPreset = true
|
||||
s.classList.toggle('active', on)
|
||||
})
|
||||
// v1.16:hex / 调色器在两处面板各有一份 → 一律按集合刷
|
||||
// hex / 调色器按集合刷(现在只有弹层一处,写法保持不变以免将来加面板时漏刷)
|
||||
runtime.el.querySelectorAll('.iwb-editor-color-hex').forEach(el => { el.textContent = cur.toUpperCase() })
|
||||
runtime.el.querySelectorAll('.iwb-editor-color-hex-input').forEach(inp => {
|
||||
if (document.activeElement !== inp) inp.value = cur.toUpperCase()
|
||||
@@ -1162,7 +1202,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
// 取值与工具栏两个色块完全同一份(colorSlots),不再各自算一遍
|
||||
const sl = colorSlots()
|
||||
let html = '<span class="iwb-opt-label">描边</span>'
|
||||
+ `<input type="color" class="iwb-opt-color" data-shape-color="stroke" value="${sl.stroke}" title="描边色:与工具栏左上的描边色块是同一份,改哪边都一样">`
|
||||
+ `<input type="color" class="iwb-opt-color${sl.strokeOn === false ? ' is-off' : ''}" data-shape-color="stroke" value="${sl.stroke}" title="描边色:与工具栏左上的描边色块是同一份,改哪边都一样${sl.strokeOn === false ? ';当前无描边,选色会自动恢复' : ''}">`
|
||||
if (owner) {
|
||||
html += '<span class="iwb-opt-label">填充</span>'
|
||||
+ `<input type="color" class="iwb-opt-color${sl.fillOn ? '' : ' is-off'}" data-shape-color="fill" data-fill-owner="${owner}" value="${sl.fill}" title="填充色:与工具栏右下的填充色块是同一份${sl.fillOn ? '' : ';当前无填充,选色会自动切成实心'}">`
|
||||
@@ -1441,7 +1481,12 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
? '填充色:与工具栏右下的填充色块是同一份'
|
||||
: '当前无填充(形状内部透明)。选色会自动切成实心,也可点工具栏填充色块选「无」'
|
||||
} else {
|
||||
inp.title = '描边色:与工具栏左上的描边色块是同一份'
|
||||
// v1.17:无描边时描边色块也要置灰(和「无填充」同一套提示)
|
||||
const off = sl.strokeOn === false
|
||||
inp.classList.toggle('is-off', off)
|
||||
inp.title = off
|
||||
? '当前无描边(只有填充)。选色会自动恢复描边,也可点工具栏描边色块选「无」'
|
||||
: '描边色:与工具栏左上的描边色块是同一份'
|
||||
}
|
||||
})
|
||||
// 选项栏与工具栏是同一份颜色数据:这里一刷新,工具栏两个色槽必须跟着刷。
|
||||
@@ -1580,9 +1625,9 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
syncOptionBar()
|
||||
}
|
||||
|
||||
/** 「无」按钮(v1.11 起只管填充;v1.12 起按格子分派):
|
||||
* 形状填充 → 内部透明;文字描边 → 描边宽度 0;文字底色 → 关掉底色块。
|
||||
* 三种情况都只改开关,颜色留着不动 —— 下次点颜色还是它。 */
|
||||
/** 「无」按钮(v1.11 起只管填充;v1.12 起按格子分派;v1.17 起描边也支持):
|
||||
* 形状填充 → 内部透明;形状描边 → 不画外框;文字描边 → 描边宽度 0;文字底色 → 关掉底色块。
|
||||
* 四种情况都只改开关,颜色留着不动 —— 下次点颜色还是它。 */
|
||||
function applyColorNone() {
|
||||
const sl = colorSlots()
|
||||
if (sl.mode === 'text') {
|
||||
@@ -1592,9 +1637,33 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
syncOptionBar()
|
||||
return
|
||||
}
|
||||
if (S.colorTarget === 'stroke') { applyStrokeNone(); return }
|
||||
applyShapeColor('none')
|
||||
}
|
||||
|
||||
/** 无描边(v1.17):只关外框,描边色留着,下次选色直接恢复。
|
||||
* 「只描边」的形状去掉描边会整体消失 —— 顺手切实心,
|
||||
* 让结果是「一个没有框的色块」而不是「对象凭空没了」。 */
|
||||
function applyStrokeNone() {
|
||||
if (!strokeSlotCanBeNone()) return
|
||||
S.colorTarget = 'stroke'
|
||||
S.shapeStrokeOn = false
|
||||
const sh = getSelectedShape()
|
||||
if (sh && !sh.locked && sh.strokeOn !== false) {
|
||||
saveSnapshot('无描边')
|
||||
sh.strokeOn = false
|
||||
if (!sh.fill && (sh.type === 'rect' || sh.type === 'circle' || (sh.type === 'pen' && sh.closed))) {
|
||||
sh.fill = true
|
||||
if (sh.type === 'pen') S.penFill = true
|
||||
else S.rectFill = true
|
||||
}
|
||||
renderObjects()
|
||||
}
|
||||
updateFillUI()
|
||||
updateColorUI()
|
||||
syncOptionBar()
|
||||
}
|
||||
|
||||
/** 形状描边色 / 填充色(v1.10;v1.11 起同时承接「无填充」)。
|
||||
* 描边色不另存一份 —— 直接走 applyColorChange 写主色,左侧色板、吸管、
|
||||
* 文字色、形状描边色四处因此永远同一个值(上一版的教训:同一个概念存两处必分叉)。
|
||||
@@ -1612,6 +1681,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
if (sh && !sh.locked && sh.fill) {
|
||||
if (!skipHistory) saveSnapshot('无填充')
|
||||
sh.fill = false
|
||||
// 与「无描边」对称:描边也是无的话对象就彻底看不见了,恢复描边兜底
|
||||
if (sh.strokeOn === false) { sh.strokeOn = true; S.shapeStrokeOn = true }
|
||||
renderObjects()
|
||||
}
|
||||
updateColorUI()
|
||||
@@ -1622,6 +1693,9 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
if (!/^#[0-9a-f]{6}$/.test(hex)) return
|
||||
if (kind === 'stroke') {
|
||||
S.colorTarget = 'stroke'
|
||||
// 新建默认值也恢复描边:否则「无描边」状态下改一次描边色,
|
||||
// 下一个新形状仍然是没框的,用户会以为设置没生效
|
||||
S.shapeStrokeOn = true
|
||||
applyColorChange(hex, opts)
|
||||
if (skipHistory) syncOptionBarSoon()
|
||||
else syncOptionBar()
|
||||
@@ -1702,30 +1776,52 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
saveSnapshot('填充')
|
||||
// 未闭合的钢笔路径没有可填区域:保持描边,不动视觉结果
|
||||
sh.fill = isPen ? (!!S.penFill && !!sh.closed) : !!S.rectFill
|
||||
// 用户明确点了「描边」= 要看见框:无描边的对象顺手恢复,否则点完毫无变化
|
||||
if (!sh.fill && sh.strokeOn === false) { sh.strokeOn = true; S.shapeStrokeOn = true }
|
||||
renderObjects()
|
||||
// 对象的 fill 更新在 sync 之后,选择工具下按钮的激活态要再刷一次
|
||||
syncOptionBar()
|
||||
}
|
||||
}
|
||||
|
||||
/** PS 的 X 语义(v1.13.1):把选中形状的「填充色」与「描边色」对调。
|
||||
* 以前 Shift+X 绑的是「实心 ↔ 只描边」开关 —— 按下去填充被关掉、描边纹丝不动,
|
||||
* 用户的主观体验就是「填充色丢了」,再按一次才回来。用户要的是**交换两个颜色**:
|
||||
* 填充色换到描边的位置、描边色换到填充的位置,填充的开关状态不变(交换的是颜色,不是有无)。
|
||||
* 填充色仍「跟随描边色」(fillColor=null)时只有一个颜色,没有可交换的对象,只提示不动数据。 */
|
||||
/** PS 的 X 语义:把选中形状的「描边」与「填充」对调。
|
||||
* v1.13.1:以前 Shift+X 绑的是「实心 ↔ 只描边」开关,按下去填充被关掉、
|
||||
* 描边纹丝不动,用户的主观体验就是「填充色丢了」。改为**交换两个颜色**。
|
||||
* v1.17:交换的是整份状态(颜色 + 有/无),不只是颜色 ——
|
||||
* 「无填充 + 有色描边」按一下 → 「有色填充 + 无描边」,反之亦然。
|
||||
* 这样「有一边是无色」时也能用(用户反馈的第二个问题);
|
||||
* 两边都有色且填充还在跟随描边时只有一个颜色,才提示不动。
|
||||
* 「未闭合钢笔 / 箭头」没有可填内部:交换后整条路径会消失,直接提示不执行。 */
|
||||
function swapShapeColors() {
|
||||
const sh = getSelectedShape()
|
||||
if (!sh || sh.locked) return false
|
||||
if (sh.type === 'arrow') { toast('箭头只有描边色,没有可交换的填充色', 'info'); return true }
|
||||
const stroke = sh.color || S.color
|
||||
const fill = sh.fillColor || null
|
||||
if (!fill) { toast('填充色正跟随描边色(两者同一个颜色),无需交换', 'info'); return true }
|
||||
const canFill = sh.type === 'rect' || sh.type === 'circle' || (sh.type === 'pen' && !!sh.closed)
|
||||
const strokeOn = sh.strokeOn !== false
|
||||
const fillOn = !!sh.fill
|
||||
const strokeColor = sh.color || S.color
|
||||
const fillColor = sh.fillColor || null // null = 跟随描边色
|
||||
if (!canFill && !fillOn) { toast('这条路径没有可填内部,交换后什么都看不见', 'info'); return true }
|
||||
if (!strokeOn && !fillOn) { toast('描边与填充都是无色,没有可交换的颜色', 'info'); return true }
|
||||
if (strokeOn && fillOn && !fillColor) { toast('填充色正跟随描边色(两者同一个颜色),无需交换', 'info'); return true }
|
||||
|
||||
saveSnapshot('交换填充与描边色')
|
||||
sh.color = fill
|
||||
S.color = fill // 描边色与主色永远同一份(v1.10 的约定)
|
||||
sh.fillColor = stroke
|
||||
S.shapeFillColor = stroke // 交换后就是独立填充色了,不再跟随描边
|
||||
// 1) 交换「有 / 无」:哪边有色,交换后就跑到另一边去
|
||||
sh.strokeOn = fillOn
|
||||
sh.fill = strokeOn && canFill
|
||||
S.shapeStrokeOn = fillOn
|
||||
if (sh.type === 'pen') S.penFill = !!(sh.fill && sh.closed)
|
||||
else if (sh.type === 'rect' || sh.type === 'circle') S.rectFill = !!sh.fill
|
||||
// 2) 交换颜色。填充原来「跟随描边色」(fillColor=null)就继续跟随 ——
|
||||
// 跟随值恰好就是原描边色,换过去还是同一个颜色,不必把它拆成独立色。
|
||||
if (fillColor) {
|
||||
sh.color = fillColor
|
||||
S.color = fillColor
|
||||
sh.fillColor = strokeColor
|
||||
S.shapeFillColor = strokeColor
|
||||
}
|
||||
renderObjects()
|
||||
updateFillUI()
|
||||
updateColorUI()
|
||||
syncOptionBar()
|
||||
return true
|
||||
@@ -2157,6 +2253,37 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
})
|
||||
}
|
||||
|
||||
/** v1.18 钉住(用户 2026-11-10):色板弹层常开,点画布 / 点别处都不收起。
|
||||
* 状态存宿主 KV —— 钉住是一种「这段时间我要连着调色」的使用习惯,
|
||||
* 不该每次开编辑器都重新钉一遍。 */
|
||||
export function loadColorPopPinned() {
|
||||
const st = S.callbacks && S.callbacks.settings
|
||||
let on = false
|
||||
if (st && typeof st.get === 'function') { try { on = !!st.get('colorPopPinned') } catch (e) { /* 宿主 KV 不可用就当没钉 */ } }
|
||||
S.colorPopPinned = on
|
||||
syncPinUI()
|
||||
}
|
||||
|
||||
function setColorPopPinned(on) {
|
||||
S.colorPopPinned = !!on
|
||||
const st = S.callbacks && S.callbacks.settings
|
||||
if (st && typeof st.set === 'function') {
|
||||
try { st.set('colorPopPinned', S.colorPopPinned) } catch (e) { /* 存不下就只管本次会话 */ }
|
||||
}
|
||||
syncPinUI()
|
||||
}
|
||||
|
||||
function syncPinUI() {
|
||||
if (!runtime.el) return
|
||||
runtime.el.querySelectorAll('[data-action="pinColorPop"]').forEach(btn => {
|
||||
btn.classList.toggle('active', !!S.colorPopPinned)
|
||||
btn.setAttribute('aria-pressed', String(!!S.colorPopPinned))
|
||||
btn.title = S.colorPopPinned
|
||||
? '已钉住:点画布不会收起色板(再点一次取消钉住)'
|
||||
: '钉住色板:一直开着,点画布也不收起(再点一次取消)'
|
||||
})
|
||||
}
|
||||
|
||||
/** 关闭色板弹层;返回「关之前是开着的」,供 Esc 决定要不要吞掉这次按键 */
|
||||
export function closeColorPop() {
|
||||
const pop = runtime.el && runtime.el.querySelector('.iwb-editor-color-pop')
|
||||
@@ -2206,10 +2333,9 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
}
|
||||
}
|
||||
|
||||
/** 调色面板(v1.3 弹层 → v1.16 弹层 + 右栏常驻):
|
||||
* 两处是同一份 DOM(dom.js#colorSurfaceHtml),按 [data-color-surface] 逐个绑定。
|
||||
* 每个 surface 各自持有一份 HSV 拖拽状态,但取值一律从 activeColor() 现算,
|
||||
* 所以「在右栏取色、再去弹层拖 SV」不会跳色。 */
|
||||
/** 调色面板(v1.3 弹层 → v1.16 弹层 + 右栏常驻 → v1.19 只剩弹层):
|
||||
* 结构来自 dom.js#colorSurfaceHtml,按 [data-color-surface] 逐个绑定。
|
||||
* 每个 surface 各自持有一份 HSV 拖拽状态,但取值一律从 activeColor() 现算。 */
|
||||
function bindColorPanel() {
|
||||
const pop = runtime.el.querySelector('.iwb-editor-color-pop')
|
||||
const colorBtns = [...runtime.el.querySelectorAll('[data-action="toggleColorPop"]')]
|
||||
@@ -2219,8 +2345,10 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
})
|
||||
if (pop) {
|
||||
// 点外面关闭:必须用捕获阶段 —— 画布的 mousedown 会 preventDefault,
|
||||
// 冒泡阶段拿不到「点了外面」这件事。右栏面板常驻,不参与关闭。
|
||||
// 冒泡阶段拿不到「点了外面」这件事。
|
||||
// 钉住时一律不关:这就是「钉住」的全部意义(要收就再点一次图钉,或按 Esc)。
|
||||
document.addEventListener('mousedown', (e) => {
|
||||
if (S.colorPopPinned) return
|
||||
const onBtn = colorBtns.some(b => b.contains(e.target))
|
||||
if (!pop.hidden && !pop.contains(e.target) && !onBtn) closeColorPop()
|
||||
}, true)
|
||||
@@ -2236,6 +2364,8 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
// tab 切换目标槽 / 「无」 / 常用色与最近色,统一委托:
|
||||
// 静态 12 色 + 动态插入的「最近使用」都要能点,一次性 querySelectorAll 会漏掉后者
|
||||
surface.addEventListener('click', (e) => {
|
||||
const pin = e.target.closest('[data-action="pinColorPop"]')
|
||||
if (pin) { e.stopPropagation(); setColorPopPinned(!S.colorPopPinned); return }
|
||||
const tab = e.target.closest('.iwb-color-pop-tab[data-color-slot]')
|
||||
if (tab) {
|
||||
e.stopPropagation()
|
||||
@@ -2258,7 +2388,7 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
const palettePick = surface.querySelector('[data-action="palettePick"]')
|
||||
if (palettePick) {
|
||||
palettePick.addEventListener('mousedown', (e) => e.stopPropagation())
|
||||
// 取色要回画布点,弹层必须先收起,否则它会挡住取样点(右栏面板在画布外,不挡)
|
||||
// 取色要回画布点,弹层必须先收起,否则它会挡住取样点
|
||||
palettePick.addEventListener('click', () => { closeColorPop(); setTool('picker') })
|
||||
}
|
||||
|
||||
@@ -2509,13 +2639,32 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
function commitPenPath() {
|
||||
if (!S.penPath || S.penPath.pts.length < 2) { S.penPath = null; renderObjects(); return }
|
||||
saveSnapshot()
|
||||
const shape = { id: 's' + Date.now() + Math.floor(Math.random() * 1000), type: 'pen', pts: S.penPath.pts.slice(), closed: !!S.penPath.closed, color: S.color, fillColor: S.shapeFillColor, lw: Math.max(1, S.shapeLineWidth), fill: !!S.penFill && !!S.penPath.closed, opacity: 1, visible: true, locked: false, z: ++S.zCounter }
|
||||
const shape = { id: 's' + Date.now() + Math.floor(Math.random() * 1000), type: 'pen', pts: S.penPath.pts.slice(), closed: !!S.penPath.closed, color: S.color, fillColor: S.shapeFillColor, lw: Math.max(1, S.shapeLineWidth), fill: !!S.penFill && !!S.penPath.closed, strokeOn: S.shapeStrokeOn !== false, opacity: 1, visible: true, locked: false, z: ++S.zCounter }
|
||||
// 路径落成即回 V 并选中(v1.5):连续画多条就再按一次 P;节点编辑仍走 V 下双击
|
||||
S.shapeLayers.push(shape); S.penPath = null; renderObjects(); renderLayerPanel()
|
||||
finishCreateTool('shape', shape.id)
|
||||
}
|
||||
|
||||
/** 将 canvas 鼠标事件绑定到活跃图层 canvas(在 setupCanvas 后调用,仅绑定一次) */
|
||||
// 交互状态复位:窗口失焦 / 指针取消 / 切标签页时兜底
|
||||
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) { /* ignore */ }
|
||||
}
|
||||
|
||||
export function bindCanvasEvents() {
|
||||
if (S._canvasEventsBound) return
|
||||
S._canvasEventsBound = true
|
||||
@@ -2525,6 +2674,9 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
|
||||
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)
|
||||
|
||||
@@ -33,7 +33,7 @@ import { createEl, loadImage } from './dom.js'
|
||||
import { renderObjects, hideTextInput, textBounds } from './objects.js'
|
||||
import { setupCanvas } from './viewport.js'
|
||||
import { resetOverlayTransform } from './scale.js'
|
||||
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar, loadSideWidth } from './events.js'
|
||||
import { updateAllUI, bindLiteUI, renderOptionBar, updateStatusbar, loadSideWidth, loadColorPopPinned } from './events.js'
|
||||
import { disposeSelection, renderSelection, selectionInfo, syncAnts, registerSelectionCommands } from './selection.js'
|
||||
import { bindFloating, positionFloating, hideSelectionContext } from './floating.js'
|
||||
import { renderFxPanel } from './effects.js'
|
||||
@@ -69,6 +69,8 @@ import { toast } from './commands.js'
|
||||
registerSelectionCommands()
|
||||
loadExportOptions()
|
||||
loadRecentColors()
|
||||
// v1.18:色板「钉住」状态也来自宿主 KV,和常用色/最近色一起恢复
|
||||
loadColorPopPinned()
|
||||
bindLiteUI()
|
||||
bindFloating()
|
||||
bindExportUI()
|
||||
@@ -338,7 +340,7 @@ import { toast } from './commands.js'
|
||||
opacity: l.opacity == null ? 1 : l.opacity,
|
||||
cssOpacity: l.canvas ? parseFloat(l.canvas.style.opacity || '1') : null
|
||||
})),
|
||||
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, z: s.z, color: s.color, fillColor: s.fillColor || null, radius: s.radius || 0, x1: Math.round(s.x1 || 0), y1: Math.round(s.y1 || 0), x2: Math.round(s.x2 || 0), y2: Math.round(s.y2 || 0) })),
|
||||
shapes: S.shapeLayers.map(s => ({ id: s.id, type: s.type, lw: s.lw, fill: !!s.fill, closed: !!s.closed, strokeOn: s.strokeOn !== false, z: s.z, color: s.color, fillColor: s.fillColor || null, radius: s.radius || 0, x1: Math.round(s.x1 || 0), y1: Math.round(s.y1 || 0), x2: Math.round(s.x2 || 0), y2: Math.round(s.y2 || 0) })),
|
||||
texts: S.textLayers.map(t => ({
|
||||
id: t.id, text: t.text, x: t.x, y: t.y, fontSize: t.fontSize, color: t.color,
|
||||
fontWeight: t.fontWeight, fontFamily: t.fontFamily, align: t.align, lineHeight: t.lineHeight,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* recent-colors.js - 最近使用颜色(v1.9)
|
||||
*
|
||||
* 只依赖 state.js(叶子模块):tools.js 在改色时调用 rememberColor(),
|
||||
* color pop 打开时 renderRecentColors() 把最近 8 个色块铺出来。
|
||||
* color pop 打开时 renderRecentColors() 把最近的色块铺出来。
|
||||
* 持久化走宿主 ctx.settings(小 KV,不放像素,符合宿主存储约定)。
|
||||
*/
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
|
||||
import { S, runtime } from './state.js'
|
||||
|
||||
const MAX = 8
|
||||
// v1.19:上限 6 → 16。色板弹层改成 8 列网格,16 个正好铺满两排
|
||||
// (v1.18 为「更紧凑」收到 6,是因为当时只有一排的空间;吸管+色值移到头部后省出这一排)。
|
||||
const MAX = 16
|
||||
const KEY = 'recentColors'
|
||||
|
||||
function valid(hex) {
|
||||
@@ -29,7 +31,7 @@ import { S, runtime } from './state.js'
|
||||
renderRecentColors()
|
||||
}
|
||||
|
||||
/** 记一个颜色:去重后置顶,最多 8 个 */
|
||||
/** 记一个颜色:去重后置顶,最多 MAX 个 */
|
||||
export function rememberColor(hex) {
|
||||
if (!valid(hex)) return
|
||||
const c = String(hex).toLowerCase()
|
||||
@@ -45,7 +47,6 @@ import { S, runtime } from './state.js'
|
||||
|
||||
export function renderRecentColors() {
|
||||
if (!runtime.el) return
|
||||
// v1.16:右栏常驻面板与工具栏弹层各有一份,按集合刷
|
||||
const wraps = runtime.el.querySelectorAll('.iwb-editor-recent-colors')
|
||||
if (!wraps.length) return
|
||||
const list = S.recentColors || []
|
||||
@@ -55,8 +56,7 @@ export function renderRecentColors() {
|
||||
wraps.forEach(wrap => {
|
||||
wrap.innerHTML = html
|
||||
wrap.hidden = !list.length
|
||||
// v1.16:右栏给了一组加了「最近」小标题,没有最近色时整组一起藏,
|
||||
// 否则标题下面留一块空白,看起来像没加载出来。
|
||||
// 没有最近色时整组一起藏,否则下面留一块空白,看起来像没加载出来
|
||||
const group = wrap.closest('.iwb-color-group')
|
||||
if (group) group.hidden = !list.length
|
||||
})
|
||||
|
||||
@@ -45,6 +45,9 @@
|
||||
// v1.2 工具参数解耦:形状线宽与文字字号不再借用画笔粗细,
|
||||
// 否则「调细画笔」会顺手把所有形状的描边一起改掉。
|
||||
shapeLineWidth: 3, // 矩形/圆形/箭头/钢笔的描边粗细
|
||||
// v1.17:默认是否画描边。关掉后形状只剩填充(「无描边」),
|
||||
// 对象上另存 strokeOn,老对象没有这个字段一律视为有描边。
|
||||
shapeStrokeOn: true,
|
||||
shapeRadius: 0, // 矩形圆角半径 px(v1.9,仅 rect 有意义)
|
||||
// v1.10:矢量图形的填充色。null = 跟随描边色(新画的就是「同色实心」,
|
||||
// 换主色时整体跟着变),一旦单独选过填充色就固定下来(每形状自己存 fillColor)。
|
||||
@@ -53,6 +56,9 @@
|
||||
// 色板(调色器 / 吸管 / 推荐色 / hex)按这个值决定写 S.color 还是 shapeFillColor,
|
||||
// 否则「三个地方各调各的颜色」会一直存在。
|
||||
colorTarget: 'stroke', // stroke | fill
|
||||
// v1.18:色板弹层是否「钉住」。钉住后点画布/点别处都不收起,方便连着调几处颜色。
|
||||
// 存宿主 KV(跨会话记住):钉过一次就一直钉着,下次打开仍生效。
|
||||
colorPopPinned: false,
|
||||
// v1.16:右侧栏宽度(px)。0 = 按默认值走,打开编辑器时从宿主 KV 恢复。
|
||||
// 宽度统一落在 CSS 变量 --iwb-side-w 上,不再各条规则各写一个魔数。
|
||||
sideWidth: 0,
|
||||
@@ -67,7 +73,7 @@
|
||||
textBgFill: TEXT_DEFAULTS.bgFill, // 底色块
|
||||
textBgColor: TEXT_DEFAULTS.bgColor, // 中性近黑,不再是纯黑 #000000
|
||||
textBgAlpha: TEXT_DEFAULTS.bgAlpha, // 底色透明度(色块按这个不透明度显示,所见即所得)
|
||||
// 最近使用颜色(最多 8 个,存 ctx.settings,跨会话保留)
|
||||
// 最近使用颜色(最多 6 个,存 ctx.settings,跨会话保留)
|
||||
recentColors: [],
|
||||
// 图层系统
|
||||
layers: [], // 位图图层数组 [{ id, name, canvas, ctx, opacity, visible, z }]
|
||||
|
||||
@@ -201,9 +201,18 @@ import { rememberColor } from './recent-colors.js'
|
||||
ctx.lineWidth = s.lw
|
||||
ctx.lineCap = 'round'
|
||||
ctx.lineJoin = 'round'
|
||||
// v1.17:无描边(strokeOn === false)。老对象没有这个字段,一律当有描边。
|
||||
// 注意不能靠 lineWidth = 0 实现:canvas 会忽略 0 从而保持上一次的值。
|
||||
const strokeOn = s.strokeOn !== false
|
||||
if (s.type === 'pen') {
|
||||
const pts = Array.isArray(s.pts) ? s.pts : []
|
||||
if (pts.length > 1) { ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y); for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y); if (s.closed) ctx.closePath(); if (s.closed && s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() } ctx.stroke() }
|
||||
if (pts.length > 1) {
|
||||
ctx.beginPath(); ctx.moveTo(pts[0].x, pts[0].y)
|
||||
for (let i = 1; i < pts.length; i++) ctx.lineTo(pts[i].x, pts[i].y)
|
||||
if (s.closed) ctx.closePath()
|
||||
if (s.closed && s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() }
|
||||
if (strokeOn) ctx.stroke()
|
||||
}
|
||||
} else if (s.type === 'rect') {
|
||||
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2), rw = Math.abs(s.x2 - s.x1), rh = Math.abs(s.y2 - s.y1)
|
||||
const radius = roundedRadius(s, rw, rh)
|
||||
@@ -211,10 +220,10 @@ import { rememberColor } from './recent-colors.js'
|
||||
ctx.beginPath()
|
||||
roundRectPath(ctx, rx, ry, rw, rh, radius)
|
||||
if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() }
|
||||
ctx.stroke()
|
||||
if (strokeOn) ctx.stroke()
|
||||
} else {
|
||||
if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fillRect(rx, ry, rw, rh) }
|
||||
ctx.strokeRect(rx, ry, rw, rh)
|
||||
if (strokeOn) ctx.strokeRect(rx, ry, rw, rh)
|
||||
}
|
||||
} else if (s.type === 'circle') {
|
||||
const rx = Math.min(s.x1, s.x2), ry = Math.min(s.y1, s.y2)
|
||||
@@ -222,8 +231,9 @@ import { rememberColor } from './recent-colors.js'
|
||||
ctx.beginPath()
|
||||
ctx.ellipse(rx + rw / 2, ry + rh / 2, Math.max(1, rw / 2), Math.max(1, rh / 2), 0, 0, Math.PI * 2)
|
||||
if (s.fill) { ctx.fillStyle = fillOf(s); ctx.fill() }
|
||||
ctx.stroke()
|
||||
} else {
|
||||
if (strokeOn) ctx.stroke()
|
||||
} else if (strokeOn) {
|
||||
// 箭头:没有可填内部,去掉描边等于不画(UI 也不提供这个入口)
|
||||
ctx.fillStyle = strokeOf(s)
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(s.x1, s.y1)
|
||||
@@ -424,9 +434,13 @@ import { rememberColor } from './recent-colors.js'
|
||||
renderObjects()
|
||||
}
|
||||
const sh = getSelectedShape()
|
||||
if (sh && !sh.locked && S.tool !== 'text' && sh.color !== S.color) {
|
||||
if (sh && !sh.locked && S.tool !== 'text' && (sh.color !== S.color || sh.strokeOn === false)) {
|
||||
// v1.17:给「无描边」的形状选颜色 = 想再看见描边,顺手打开。
|
||||
// 与改色共用同一张快照,撤销一步就能回到「无描边 + 旧色」。
|
||||
const revive = sh.strokeOn === false
|
||||
if (!skipHistory) saveSnapshot()
|
||||
sh.color = S.color
|
||||
if (revive) { sh.strokeOn = true; S.shapeStrokeOn = true }
|
||||
renderObjects()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,3 +15,5 @@ import { createGlue } from './glue.js'
|
||||
;(typeof window !== 'undefined' ? window : globalThis).__IWB_ANNOTATE_FACTORY__ = function (ctx) {
|
||||
return createGlue(ctx, editorCss)
|
||||
}
|
||||
|
||||
// build-rev: 2026-11-17 (cache-bust)
|
||||
@@ -6,11 +6,14 @@
|
||||
// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。
|
||||
//
|
||||
// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。
|
||||
// skin: 'private' = 本插件自带整套调色板(Catppuccin 深色工具 UI),不跟随宿主主题。
|
||||
// 代价由宿主契约测试钉死:声明 private 的插件不得引用宿主颜色 var(--iwb-*),只能自洽。
|
||||
var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
id: 'image-annotate',
|
||||
name: '标注 / 修图',
|
||||
version: '__PLUGIN_VERSION__',
|
||||
apiVersion: 1,
|
||||
skin: 'private',
|
||||
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
|
||||
settings: {
|
||||
exportPreset: { type: 'string', default: 'original' },
|
||||
|
||||
@@ -7,3 +7,5 @@
|
||||
return global.__IWB_ANNOTATE_FACTORY__(ctx)
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
|
||||
// build-rev: 2026-11-17T17 (pointer-self-heal)
|
||||
+387
-2298
File diff suppressed because it is too large.
Load diff
@@ -183,10 +183,24 @@ if (!SKIP_PASTE) {
|
||||
(await page.locator('.iwb-editor-header .iwb-editor-commands').count()) === 0,
|
||||
'layerBtn=' + await page.locator('.iwb-editor-layer-btn').count())
|
||||
|
||||
const toolsTail = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-editor-tools > *'))
|
||||
.slice(-2).map((n) => n.dataset.action || n.className))
|
||||
check('工具栏最右两个按钮是「适应窗口 / 收起侧栏」',
|
||||
JSON.stringify(toolsTail) === JSON.stringify(['zoomFit', 'togglePanels']), JSON.stringify(toolsTail))
|
||||
// v1.18(用户 2026-11-10):撤销 / 重做 / 还原 从顶栏搬到工具条最右,
|
||||
// 「适应窗口 / 收起侧栏」退到它前面两位。这里断言「末尾是撤销组、视图按钮在其前」
|
||||
// —— 光看版本号挡不住产物没重建。
|
||||
const toolsOrder = await page.evaluate(() => {
|
||||
const kids = Array.from(document.querySelectorAll('.iwb-editor-tools > *'))
|
||||
const acts = kids.filter((n) => n.dataset && n.dataset.action).map((n) => n.dataset.action)
|
||||
const hist = kids[kids.length - 1]
|
||||
return {
|
||||
tail: acts.slice(-2),
|
||||
lastIsHistory: Boolean(hist && hist.classList.contains('iwb-editor-history')),
|
||||
histActs: [...(hist ? hist.querySelectorAll('[data-action]') : [])].map((b) => b.dataset.action),
|
||||
headerHasHistory: Boolean(document.querySelector('.iwb-editor-header .iwb-editor-history')),
|
||||
}
|
||||
})
|
||||
check('工具栏最右是「撤销/重做/还原」组(视图按钮在其前)',
|
||||
JSON.stringify(toolsOrder.tail) === JSON.stringify(['zoomFit', 'togglePanels']) &&
|
||||
toolsOrder.lastIsHistory && toolsOrder.histActs.join(',') === 'undo,redo,reset' &&
|
||||
!toolsOrder.headerHasHistory, JSON.stringify(toolsOrder))
|
||||
|
||||
const before = await panelSeq()
|
||||
const activeName = await page.evaluate(() => document.querySelector('.iwb-editor-layer-list .iwb-layer-item.active .iwb-layer-name')?.textContent)
|
||||
@@ -217,20 +231,50 @@ if (!SKIP_PASTE) {
|
||||
(await page.locator('.iwb-editor-adj-target').textContent()) !== '无图层',
|
||||
await page.locator('.iwb-editor-adj-target').textContent())
|
||||
|
||||
// v1.16:右栏常驻调色面板 + 可拖宽度。真站里 DOM 与 CSS 是分别打包的,
|
||||
// 只验面板在不在、拖宽后宽度有没有真的变 —— 样式漏打包时这里会直接露出来。
|
||||
const sideColor = await page.evaluate(() => {
|
||||
const side = document.querySelector('.iwb-editor-left [data-color-surface="side"]')
|
||||
if (!side) return null
|
||||
// v1.19:右栏常驻调色面板已删(用户 2026-11-10),颜色只剩工具栏弹层一处。
|
||||
// 真站里 DOM 与 CSS 分别打包,这里同时验「右栏干净」和「弹层头部一行 / 16 色 8 列」——
|
||||
// 样式漏打包时,头部会退回竖排或色块掉成 6 列,这条会直接露出来。
|
||||
const sideColor = await page.evaluate(() => ({
|
||||
hasSide: Boolean(document.querySelector('.iwb-editor-left [data-color-surface]')),
|
||||
firstSection: (document.querySelector('.iwb-editor-left > section') || {}).className || '',
|
||||
}))
|
||||
check('右栏调色模块已删(第一个模块是图片调节)',
|
||||
sideColor.hasSide === false && /iwb-editor-adj/.test(sideColor.firstSection),
|
||||
JSON.stringify(sideColor))
|
||||
|
||||
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(240)
|
||||
const popShape = await page.evaluate(() => {
|
||||
const pop = document.querySelector('.iwb-editor-color-pop')
|
||||
if (!pop) return null
|
||||
const r = (el) => el.getBoundingClientRect()
|
||||
const head = r(pop.querySelector('.iwb-color-pop-head'))
|
||||
const items = [pop.querySelector('[data-action="palettePick"]'),
|
||||
pop.querySelector('.iwb-editor-color-hex-input'),
|
||||
pop.querySelector('[data-action="pinColorPop"]')].map((el) => {
|
||||
const b = r(el)
|
||||
return { c: b.top + b.height / 2, l: b.left, r: b.right }
|
||||
})
|
||||
const sw = [...pop.querySelectorAll('.iwb-editor-color-swatches [data-panel-color]')]
|
||||
const grid = pop.querySelector('.iwb-editor-color-swatches')
|
||||
return {
|
||||
tabs: side.querySelectorAll('.iwb-color-pop-tab').length,
|
||||
swatches: side.querySelectorAll('.iwb-editor-color-swatches [data-panel-color]').length,
|
||||
sv: !!side.querySelector('.iwb-color-sv')
|
||||
w: Math.round(r(pop).width),
|
||||
sameRow: items.every((it) =>
|
||||
Math.abs(it.c - (head.top + head.height / 2)) < 3 && it.l >= head.left - 1 && it.r <= head.right + 1),
|
||||
common: sw.length,
|
||||
cols: new Set(sw.map((b) => Math.round(r(b).left))).size,
|
||||
swatch: sw.length ? Math.round(r(sw[0]).width) : 0,
|
||||
// v1.20:去色占常用色第一格(20px 同尺寸、第一排最左)
|
||||
noneFirst: grid.children[0] === pop.querySelector('[data-color-none]'),
|
||||
cells: grid.children.length,
|
||||
}
|
||||
})
|
||||
check('右栏常驻调色面板(色格切换 + 调色器 + 12 个常用色)',
|
||||
Boolean(sideColor) && sideColor.tabs === 3 && sideColor.swatches === 12 && sideColor.sv,
|
||||
JSON.stringify(sideColor))
|
||||
check('色板弹层:头部一行(吸管 / 色值 / 图钉同排)+ 去色占常用色第一格 + 15 色 8 列',
|
||||
Boolean(popShape) && popShape.sameRow && popShape.noneFirst && popShape.cells === 16 &&
|
||||
popShape.common === 15 && popShape.cols === 8 && popShape.swatch === 20 && popShape.w === 440,
|
||||
JSON.stringify(popShape))
|
||||
await page.keyboard.press('Escape')
|
||||
await page.waitForTimeout(140)
|
||||
|
||||
const sideBefore = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width))
|
||||
const sideGrip = await page.locator('.iwb-editor-side-resizer').boundingBox()
|
||||
@@ -246,6 +290,37 @@ if (!SKIP_PASTE) {
|
||||
await page.locator('.iwb-editor-side-resizer').dblclick()
|
||||
await page.waitForTimeout(150)
|
||||
|
||||
// v1.17:描边可以是「无色」。真站要验的是按钮真的出现在描边槽、点完对象上真的关了,
|
||||
// 而不只是 CSS 里多了个类 —— 形状消失与否只有跑起来才知道。
|
||||
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
|
||||
await page.mouse.move(imgBox.x + imgBox.width * 0.12, imgBox.y + imgBox.height * 0.12)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(imgBox.x + imgBox.width * 0.30, imgBox.y + imgBox.height * 0.30, { steps: 6 })
|
||||
await page.mouse.up()
|
||||
await page.waitForTimeout(250)
|
||||
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
|
||||
await page.mouse.click(imgBox.x + imgBox.width * 0.21, imgBox.y + imgBox.height * 0.21)
|
||||
await page.waitForTimeout(200)
|
||||
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(250)
|
||||
const noneOnStroke = await page.evaluate(() => {
|
||||
const n = document.querySelector('.iwb-editor-color-pop [data-color-none]')
|
||||
// v1.20:去色不再 hidden,改用 disabled 表达「这个上下文不能去色」
|
||||
return Boolean(n) && Boolean(n.offsetParent) && !n.disabled
|
||||
})
|
||||
await page.evaluate(() => document.querySelector('.iwb-editor-color-pop [data-color-none]').click())
|
||||
await page.waitForTimeout(300)
|
||||
const noStrokeState = await page.evaluate(() => {
|
||||
const d = window.__iwbEditor.__debug()
|
||||
const s = d.shapes.find((x) => x.id === d.selectedShapeId)
|
||||
return s ? { strokeOn: s.strokeOn, fill: s.fill } : null
|
||||
})
|
||||
check('真站:描边能置「无」(去掉描边顺手切实心,对象不会消失)',
|
||||
noneOnStroke && Boolean(noStrokeState) && noStrokeState.strokeOn === false && noStrokeState.fill === true,
|
||||
JSON.stringify({ noneOnStroke, noStrokeState }))
|
||||
await page.keyboard.press('Escape')
|
||||
await page.waitForTimeout(120)
|
||||
|
||||
// v1.14 字体选择:真站是带 CSP 的环境,这里确认下拉可用、字体切换真的落到了对象上。
|
||||
// 系统字体不受 CSP 约束(CSP 管的是网络字体),所以只要 canvas 能画就没问题。
|
||||
const famDbg = () => page.evaluate(() => window.__iwbEditor.__debug())
|
||||
|
||||
@@ -139,13 +139,16 @@ check('打开编辑器默认只有「原图」1 层,且状态栏不再写「
|
||||
JSON.stringify((await dbg()).layers.map(l => l.name)))
|
||||
|
||||
// v1.3(用户裁定 2026-11-05):调色板从侧栏搬进工具栏弹层,侧栏只剩缩放
|
||||
check('调色板已搬进工具栏:侧栏只剩缩放,SV/色相/推荐色都在弹层里',
|
||||
// v1.19(用户 2026-11-10):右栏那份常驻调色面板删掉,颜色只剩弹层一处
|
||||
check('调色板只在工具栏弹层:右栏没有调色模块,SV/色相/去色 + 15 个常用色都在弹层里',
|
||||
await page.evaluate(() => {
|
||||
const q = (s) => Boolean(document.querySelector(s))
|
||||
return !q('.iwb-editor-left .iwb-editor-color-panel') &&
|
||||
return !q('.iwb-editor-left [data-color-surface]') && !q('.iwb-editor-left .iwb-editor-colors') &&
|
||||
q('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]') &&
|
||||
q('.iwb-editor-color-pop .iwb-color-sv') && q('.iwb-editor-color-pop .iwb-color-hue') &&
|
||||
document.querySelectorAll('.iwb-editor-color-pop .iwb-editor-color-panel-swatch').length === 12 &&
|
||||
// v1.20:去色进网格占第一格,所以 data-panel-color 只剩 15 个(+ 去色 = 16 格)
|
||||
document.querySelectorAll('.iwb-editor-color-pop .iwb-editor-color-swatches [data-panel-color]').length === 15 &&
|
||||
q('.iwb-editor-color-pop .iwb-editor-color-swatches [data-color-none]') &&
|
||||
q('.iwb-editor-zoom') &&
|
||||
!q('.iwb-editor-brush-size') && !q('.iwb-editor-brush-num') &&
|
||||
document.querySelectorAll('.iwb-editor-brush-preset').length === 0
|
||||
@@ -193,6 +196,150 @@ check('色板弹层默认收起;点工具栏色点弹出、且整块在视口
|
||||
return inView && !(await pop.isVisible()) ? true : 'box=' + JSON.stringify(box)
|
||||
})())
|
||||
|
||||
// ---------- v1.18 / v1.19 / v1.20 色板弹层布局(用户 2026-11-10) ----------
|
||||
// v1.18:「加钉住」「三项不写标题、用细横线分割」
|
||||
// v1.19:「去色放钉住左边、竖线分割」「吸色与色值放在钉住那一排」「宽度再多一点,
|
||||
// 颜色一排 8 个,常用色多加 4 个」「最近色放两排」
|
||||
// v1.20:文字工具多出「底色」tab 时头部挤爆,把「去色」整颗抵没了 ——
|
||||
// 改成去色占常用色第一格(永远在,不可用只置灰),头部元素全部定宽。
|
||||
await page.locator('.iwb-editor-tool[data-tool="marquee"]').click() // 用选择工具点画布,不落像素
|
||||
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(140)
|
||||
const popLayout = await page.evaluate(() => {
|
||||
const pop = document.querySelector('.iwb-editor-color-pop')
|
||||
const r = (el) => el.getBoundingClientRect()
|
||||
const none = pop.querySelector('[data-color-none]')
|
||||
const grid = pop.querySelector('.iwb-editor-color-swatches')
|
||||
const picker = r(pop.querySelector('.iwb-color-pop-picker'))
|
||||
const side = r(pop.querySelector('.iwb-color-pop-side'))
|
||||
const headEl = pop.querySelector('.iwb-color-pop-head')
|
||||
const head = r(headEl)
|
||||
const eye = pop.querySelector('[data-action="palettePick"]')
|
||||
const hex = pop.querySelector('.iwb-editor-color-hex-input')
|
||||
const pin = pop.querySelector('[data-action="pinColorPop"]')
|
||||
const sw = [...pop.querySelectorAll('.iwb-editor-color-swatches [data-panel-color]')]
|
||||
// 去色现在是常用色网格的第一格:位置固定、尺寸和其它色块一致
|
||||
const noneFirstCell = grid.children[0] === none
|
||||
const noneSameSize = Math.abs(r(none).width - r(sw[0]).width) < 1 &&
|
||||
Math.abs(r(none).height - r(sw[0]).height) < 1
|
||||
const noneRow1 = Math.round(r(none).top) === Math.round(r(sw[0]).top) &&
|
||||
Math.round(r(none).left) < Math.round(r(sw[0]).left)
|
||||
// 头部一行:吸管 / 色值 / 图钉 的竖直中心都必须落在头部这条线上
|
||||
const cy = (el) => r(el).top + r(el).height / 2
|
||||
const headOneRow = [eye, hex, pin].every((el) =>
|
||||
Math.abs(cy(el) - (head.top + head.height / 2)) < 3 &&
|
||||
r(el).left >= head.left - 1 && r(el).right <= head.right + 1)
|
||||
// 定宽/不浮动验收(v1.20.1):文字工具会多出「底色」tab,
|
||||
// 吸管 + 色值 + 图钉这一组**不能跟着 tab 左右浮** —— 用户明确要求「他不浮动」。
|
||||
// 所以量「两 tab / 三 tab」两种上下文下的左边界签名,必须逐像素一致;
|
||||
// 同时图钉右边缘要贴住头部右边界(整组右对齐的证据)。
|
||||
const sig = () => [Math.round(r(eye).left), Math.round(r(hex).left),
|
||||
Math.round(r(pin).left), Math.round(r(pin).right)].join(',')
|
||||
const sig2 = sig()
|
||||
const bgTab = pop.querySelector('.iwb-color-pop-tab[data-color-slot="bg"]')
|
||||
const bgWasHidden = bgTab.hidden
|
||||
if (bgWasHidden) bgTab.hidden = false
|
||||
const sig3 = sig()
|
||||
const rightPinned = Math.abs(r(pin).right - head.right) < 1.5
|
||||
// 注意用元素本身读 scrollWidth/clientWidth —— DOMRect 上没有这两个属性,写 head.scrollWidth
|
||||
// 会拿到 undefined,比较恒为 false(本次就是这样白跑了两轮)
|
||||
const headFitsThreeTabs = headEl.scrollWidth <= headEl.clientWidth + 1 && r(pin).right <= head.right + 1
|
||||
const headDbg = {
|
||||
client: headEl.clientWidth, scroll: headEl.scrollWidth,
|
||||
tabs: [...pop.querySelectorAll('.iwb-color-pop-tab')].map((t) => Math.round(r(t).width)),
|
||||
hex: Math.round(r(hex).width), hexLeft: Math.round(r(hex).left),
|
||||
popW: Math.round(r(pop).width), headRight: Math.round(head.right),
|
||||
sig2, sig3,
|
||||
}
|
||||
if (bgWasHidden) bgTab.hidden = true
|
||||
const row1 = sw.slice(0, 7).map((b) => Math.round(r(b).top))
|
||||
const row2 = sw.slice(7).map((b) => Math.round(r(b).top))
|
||||
// 「最近」没有历史色时整组(含外层 group)都是 hidden,量不出网格;
|
||||
// 这里临时铺满 16 个量完再还原 —— 只解 wrap 的 hidden 不够,外层还压着一层
|
||||
const rec = pop.querySelector('.iwb-editor-recent-colors')
|
||||
const recGroup = rec.closest('.iwb-color-group')
|
||||
const recWasHidden = rec.hidden
|
||||
const grpWasHidden = Boolean(recGroup && recGroup.hidden)
|
||||
if (recWasHidden) {
|
||||
rec.hidden = false
|
||||
if (recGroup) recGroup.hidden = false
|
||||
rec.innerHTML = '<button class="iwb-editor-color-panel-swatch"></button>'.repeat(16)
|
||||
}
|
||||
const recRows = new Set([...rec.querySelectorAll('.iwb-editor-color-panel-swatch')]
|
||||
.map((b) => Math.round(r(b).top))).size
|
||||
const recCols = new Set([...rec.querySelectorAll('.iwb-editor-color-panel-swatch')]
|
||||
.map((b) => Math.round(r(b).left))).size
|
||||
if (recWasHidden) {
|
||||
rec.innerHTML = ''
|
||||
rec.hidden = true
|
||||
if (grpWasHidden && recGroup) recGroup.hidden = true
|
||||
}
|
||||
const out = {
|
||||
w: Math.round(r(pop).width),
|
||||
h: Math.round(r(pop).height),
|
||||
headOneRow,
|
||||
headRows: [head.top, head.bottom, head.left, head.right].map(Math.round),
|
||||
items: [eye, hex, pin].map((el) => [r(el).top, r(el).bottom, r(el).left, r(el).right].map(Math.round)),
|
||||
sideInRight: Math.round(side.left) >= Math.round(picker.right),
|
||||
noneFirstCell, noneSameSize, noneRow1,
|
||||
headFitsThreeTabs, headFixed: sig2 === sig3, rightPinned,
|
||||
hexW: Math.round(r(hex).width), headDbg,
|
||||
common: sw.length,
|
||||
// 8 列 × 2 行:13 个常用色 + 第一格去色 = 16 格,两排各 8
|
||||
twoRows: row1.length === 7 && row2.length === 8 &&
|
||||
new Set(row1).size === 1 && new Set(row2).size === 1 && row1[0] < row2[0] &&
|
||||
grid.children.length === 16,
|
||||
cols: new Set(sw.map((b) => Math.round(r(b).left))).size,
|
||||
recRows, recCols,
|
||||
dividers: [...pop.querySelectorAll('.iwb-color-pop-side > * + *')].map((g) => getComputedStyle(g).borderTopWidth),
|
||||
labelsVisible: [...pop.querySelectorAll('.iwb-color-group-label')].filter((l) => l.offsetParent !== null).length,
|
||||
swatch: Math.round(r(sw[0]).width),
|
||||
}
|
||||
return out
|
||||
})
|
||||
check('色板头部:吸管 + 色值 + 图钉整组右对齐,加「底色」tab 后逐像素不浮动',
|
||||
popLayout.headOneRow && popLayout.headFitsThreeTabs && popLayout.headFixed && popLayout.rightPinned,
|
||||
JSON.stringify(popLayout.headDbg) + ' rightPinned=' + popLayout.rightPinned)
|
||||
check('「去色」是常用色的第一格(20px 同尺寸、第一排最左),不再挂在头部',
|
||||
popLayout.noneFirstCell && popLayout.noneSameSize && popLayout.noneRow1,
|
||||
JSON.stringify({ first: popLayout.noneFirstCell, size: popLayout.noneSameSize, row: popLayout.noneRow1, sw: popLayout.swatch }))
|
||||
check('常用色 8 列 × 2 行(去色 + 15 色 = 16 格),最近色也是 8 列两排,块间 1px 细线且无小标题',
|
||||
popLayout.common === 15 && popLayout.twoRows && popLayout.cols === 8 &&
|
||||
popLayout.recCols === 8 && popLayout.recRows === 2 &&
|
||||
popLayout.labelsVisible === 0 && popLayout.dividers.every((d) => d === '1px'),
|
||||
JSON.stringify(popLayout))
|
||||
check('色块区在取色器右侧,弹层宽高在预期区间(比 v1.18 的 380×153 宽一档)',
|
||||
popLayout.sideInRight && popLayout.w >= 410 && popLayout.w <= 470 && popLayout.h <= 178 &&
|
||||
popLayout.swatch === 20,
|
||||
'w=' + popLayout.w + ' h=' + popLayout.h + ' swatch=' + popLayout.swatch)
|
||||
// 开发用:ANNOT_SHOT=/tmp/pop.png 出一张色板弹层截图(验证布局)
|
||||
if (process.env.ANNOT_SHOT) await page.locator('.iwb-editor-color-pop').screenshot({ path: process.env.ANNOT_SHOT })
|
||||
|
||||
const pinBtn = page.locator('.iwb-editor-color-pop [data-action="pinColorPop"]')
|
||||
await pinBtn.click()
|
||||
await page.waitForTimeout(90)
|
||||
await page.mouse.click(imgBox.x + imgBox.width * 0.5, imgBox.y + imgBox.height * 0.5)
|
||||
await page.waitForTimeout(140)
|
||||
const pinned = await page.evaluate(() => ({
|
||||
open: !document.querySelector('.iwb-editor-color-pop').hidden,
|
||||
active: document.querySelector('.iwb-editor-color-pop [data-action="pinColorPop"]').classList.contains('active'),
|
||||
saved: window.__settings.colorPopPinned === true,
|
||||
}))
|
||||
check('钉住后点画布不收起,状态写进宿主 settings(下次打开仍钉着)',
|
||||
pinned.open && pinned.active && pinned.saved, JSON.stringify(pinned))
|
||||
|
||||
await pinBtn.click()
|
||||
await page.waitForTimeout(70)
|
||||
await page.mouse.click(imgBox.x + imgBox.width * 0.35, imgBox.y + imgBox.height * 0.4)
|
||||
await page.waitForTimeout(140)
|
||||
const unpinned = await page.evaluate(() => ({
|
||||
open: !document.querySelector('.iwb-editor-color-pop').hidden,
|
||||
saved: window.__settings.colorPopPinned,
|
||||
active: document.querySelector('.iwb-editor-color-pop [data-action="pinColorPop"]').classList.contains('active'),
|
||||
}))
|
||||
check('取消钉住后点画布立即收起(状态回到 false)',
|
||||
!unpinned.open && unpinned.saved === false && !unpinned.active, JSON.stringify(unpinned))
|
||||
|
||||
const drag = async (x1, y1, x2, y2) => {
|
||||
await page.mouse.move(x1, y1)
|
||||
await page.mouse.down()
|
||||
@@ -672,10 +819,9 @@ check('适应窗口后图片底边不被工具条遮挡', await page.evaluate(()
|
||||
check('顶栏输出/导出按钮组贴最右侧(用户裁定 2026-11-04)', await page.evaluate(() => {
|
||||
const hdr = document.querySelector('.iwb-editor-header')
|
||||
const ex = document.querySelector('.iwb-editor-header > .iwb-editor-export-actions')
|
||||
const hist = document.querySelector('.iwb-editor-header > .iwb-editor-history')
|
||||
if (!hdr || !ex || !hist) return false
|
||||
if (!hdr || !ex) return false
|
||||
const h = hdr.getBoundingClientRect(), e = ex.getBoundingClientRect()
|
||||
return h.right - e.right <= 14 && e.left > hist.getBoundingClientRect().right
|
||||
return h.right - e.right <= 14
|
||||
}))
|
||||
|
||||
// 橡皮:1.2.2 回归 —— events.js 少 import getActiveLayer,一按下就 ReferenceError,表现为「橡皮不能擦」
|
||||
@@ -743,11 +889,15 @@ check('顶栏不再有图层层级按钮;视图快捷搬到画布工具栏最
|
||||
const hdrAdd = document.querySelector('.iwb-editor-header [data-action="addBlankLayer"], .iwb-editor-header [data-action="addBitmapLayer"]')
|
||||
const tools = document.querySelector('.iwb-editor-canvas-wrap > .iwb-editor-tools')
|
||||
const kids = tools ? [...tools.children] : []
|
||||
const lastTwo = kids.slice(-2).map(el => el.dataset && el.dataset.action)
|
||||
// v1.18:撤销组搬进来后是 tools 的最后一个子元素,视图快捷退到它前面两位
|
||||
// (中间还夹了一条分隔线 span,没有 data-action,过滤掉)
|
||||
const histEl = kids.find(el => el.classList && el.classList.contains('iwb-editor-history')) || null
|
||||
const lastTwo = kids.filter(el => el !== histEl && el.dataset && el.dataset.action)
|
||||
.slice(-2).map(el => el.dataset.action)
|
||||
return !q('.iwb-editor-more-wrap') && !q('[data-action="toggleMore"]') &&
|
||||
hdrLayerBtns === 0 && !hdrAdd && addBtns === 4 &&
|
||||
!q('.iwb-editor-header [data-action="zoomFit"]') && !q('.iwb-editor-header [data-action="togglePanels"]') &&
|
||||
lastTwo.join(',') === 'zoomFit,togglePanels' &&
|
||||
lastTwo.join(',') === 'zoomFit,togglePanels' && kids[kids.length - 1] === histEl &&
|
||||
q('.iwb-editor-layer-panel-header [data-action="addBlankLayer"]') &&
|
||||
q('.iwb-editor-layer-panel-header [data-action="addBitmapLayer"]') &&
|
||||
q('.iwb-editor-layer-panel-header [data-action="mergeLayers"]') &&
|
||||
@@ -755,7 +905,7 @@ check('顶栏不再有图层层级按钮;视图快捷搬到画布工具栏最
|
||||
}))
|
||||
|
||||
check('「还原原图」图标是循环重置(refresh)而不是垃圾桶', await page.evaluate(() => {
|
||||
const svg = document.querySelector('.iwb-editor-header [data-action="reset"] svg')
|
||||
const svg = document.querySelector('.iwb-editor-tools [data-action="reset"] svg')
|
||||
if (!svg) return false
|
||||
const paths = svg.querySelectorAll('path').length
|
||||
const polys = Array.from(svg.querySelectorAll('polyline')).map(p => p.getAttribute('points')).join('|')
|
||||
@@ -1018,24 +1168,45 @@ await page.keyboard.press('Control+z') // 撤销上一步新建的矩形,恢
|
||||
|
||||
// ---- v1.2.9:会话组(新建/覆盖/退出)移到顶栏最左 + 图层 PS 快捷键 ----
|
||||
|
||||
check('顶栏:标题最前 → 新建/覆盖/退出(统一中性色)→ 竖分隔 → 撤销组,右侧只剩 输出+导出', await page.evaluate(() => {
|
||||
check('顶栏:标题 → 新建/覆盖/退出(统一中性色),撤销组已搬去工具条,右侧只剩 输出+导出', await page.evaluate(() => {
|
||||
const q = (s) => document.querySelector(s)
|
||||
const session = q('.iwb-editor-header > .iwb-editor-session')
|
||||
const title = q('.iwb-editor-header > .iwb-editor-title')
|
||||
const hist = q('.iwb-editor-header > .iwb-editor-history')
|
||||
const dl = q('.iwb-editor-header [data-action="download"]')
|
||||
if (!session || !title || !hist || !dl) return false
|
||||
const t = title.getBoundingClientRect(), s = session.getBoundingClientRect(), h = hist.getBoundingClientRect()
|
||||
if (!session || !title || !dl) return false
|
||||
const t = title.getBoundingClientRect(), s = session.getBoundingClientRect()
|
||||
const btns = Array.from(session.querySelectorAll('.iwb-editor-btn')).map(b => b.dataset.action).join(',')
|
||||
const bg = (sel) => getComputedStyle(q(sel)).backgroundColor
|
||||
const unified = bg('.iwb-editor-header .iwb-editor-btn-new') === bg('.iwb-editor-header .iwb-editor-btn-replace') &&
|
||||
bg('.iwb-editor-header .iwb-editor-btn-replace') === bg('.iwb-editor-header .iwb-editor-btn-cancel')
|
||||
return btns === 'newNode,replace,cancel' &&
|
||||
t.left < s.left && s.right < h.left &&
|
||||
t.left < s.left &&
|
||||
!q('.iwb-editor-header > .iwb-editor-history') && // v1.18 搬去工具条最右
|
||||
!q('.iwb-editor-header > .iwb-editor-commands') &&
|
||||
unified && dl.textContent.trim() === '导出' &&
|
||||
!q('.iwb-editor-export-actions [data-action="newNode"]')
|
||||
}))
|
||||
|
||||
// v1.18(用户 2026-11-10):撤销 / 重做 / 还原从顶栏搬到画布底部工具栏最右 —— 手在画布上时够得到
|
||||
check('撤销 / 重做 / 还原 在工具条最右(视图快捷之后,是 tools 的最后一个子元素)', await page.evaluate(() => {
|
||||
const tools = document.querySelector('.iwb-editor-tools')
|
||||
const hist = tools && tools.querySelector('.iwb-editor-history')
|
||||
const fit = tools && tools.querySelector('[data-action="zoomFit"]')
|
||||
const panels = tools && tools.querySelector('[data-action="togglePanels"]')
|
||||
const crop = tools && tools.querySelector('[data-tool="crop"]')
|
||||
if (!hist || !fit || !panels || !crop) return false
|
||||
const acts = [...hist.querySelectorAll('[data-action]')].map((b) => b.dataset.action).join(',')
|
||||
const c = crop.getBoundingClientRect()
|
||||
const f = fit.getBoundingClientRect()
|
||||
const p = panels.getBoundingClientRect()
|
||||
const h = hist.getBoundingClientRect()
|
||||
return acts === 'undo,redo,reset' &&
|
||||
tools.lastElementChild === hist &&
|
||||
c.right <= f.left && f.right <= p.left && p.right <= h.left &&
|
||||
Math.abs(h.top - c.top) < 2 // 与工具按钮同一条水平线,没有掉到第二行
|
||||
}))
|
||||
// 开发用:ANNOT_SHOT_BAR=/tmp/bar.png 出一张工具条截图(验证撤销组落在最右、没有换行)
|
||||
if (process.env.ANNOT_SHOT_BAR) await page.locator('.iwb-editor-tools').screenshot({ path: process.env.ANNOT_SHOT_BAR })
|
||||
check('画笔选项栏:推荐大小只留 4 个快捷点,硬度补 5 个快捷点且滑杆加宽', await (async () => {
|
||||
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
|
||||
const ok = await page.evaluate(() => {
|
||||
@@ -1975,12 +2146,35 @@ const popTextTarget = await page.evaluate(() => {
|
||||
fillActive: tab.classList.contains('active'),
|
||||
fillLabel: tab.querySelector('.iwb-color-pop-tab-label').textContent,
|
||||
bgVisible: !bgTab.hidden,
|
||||
noneVisible: !pop.querySelector('[data-color-none]').hidden
|
||||
// v1.20:去色不再 hidden,改成「在不在 + 能不能用」
|
||||
noneVisible: !!pop.querySelector('[data-color-none]').offsetParent,
|
||||
noneUsable: !pop.querySelector('[data-color-none]').disabled
|
||||
}
|
||||
})
|
||||
check('点文字的「描边」格:色板目标是描边(tab 写「描边」),底色 tab 同时可选',
|
||||
check('点文字的「描边」格:色板目标是描边(tab 写「描边」),底色 tab 同时可选,去色可用',
|
||||
popTextTarget.open && popTextTarget.fillActive && popTextTarget.fillLabel === '描边' &&
|
||||
popTextTarget.bgVisible && popTextTarget.noneVisible, JSON.stringify(popTextTarget))
|
||||
popTextTarget.bgVisible && popTextTarget.noneVisible && popTextTarget.noneUsable,
|
||||
JSON.stringify(popTextTarget))
|
||||
|
||||
// v1.20(用户 2026-11-10 截图):文字色这一格去不掉色,但按钮必须**留在原位变灰**,
|
||||
// 不能整颗消失 —— 消失会让色板每切一次工具就重排,位置记不住。
|
||||
await page.locator('.iwb-editor-color-btn[data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(200)
|
||||
const noneDisabledOnTextColor = await page.evaluate(() => {
|
||||
const n = document.querySelector('.iwb-editor-color-pop [data-color-none]')
|
||||
return {
|
||||
visible: !!n.offsetParent, disabled: n.disabled, dim: Number(getComputedStyle(n).opacity),
|
||||
title: n.title, bgTabStillHidden: document.querySelector('.iwb-color-pop-tab[data-color-slot="bg"]').hidden
|
||||
}
|
||||
})
|
||||
check('文字色上下文:去色仍在第一格、只是置灰 disabled(说明原因),不整颗消失',
|
||||
noneDisabledOnTextColor.visible && noneDisabledOnTextColor.disabled &&
|
||||
noneDisabledOnTextColor.dim < 0.6 && /去色不可用/.test(noneDisabledOnTextColor.title),
|
||||
JSON.stringify(noneDisabledOnTextColor))
|
||||
// 开发用:ANNOT_SHOT3=/tmp/pop-text.png 出「文字工具三 tab + 去色置灰」的效果图(用户截图那个场景)
|
||||
if (process.env.ANNOT_SHOT3) await page.locator('.iwb-editor-color-pop').screenshot({ path: process.env.ANNOT_SHOT3 })
|
||||
await page.locator('.iwb-editor-color-btn[data-color-slot="fill"]').click()
|
||||
await page.waitForTimeout(200)
|
||||
|
||||
await page.evaluate(() => {
|
||||
const el = document.querySelector('.iwb-editor-color-pop .iwb-editor-color-hex-input')
|
||||
@@ -2265,6 +2459,23 @@ await page.locator('.iwb-editor-color-pop [data-panel-color="#ffd400"]').first()
|
||||
await page.waitForTimeout(200)
|
||||
const recents = (await dbg()).recentColors
|
||||
const recentsInPop = await page.locator('.iwb-editor-color-pop .iwb-editor-recent-colors [data-panel-color]').count()
|
||||
// 开发用:ANNOT_SHOT2=/tmp/pop-full.png 出一张「去色可见 + 最近色铺满两排」的完整效果图。
|
||||
// 最近色要长期用才攒得满,这里临时补到 16 个纯为出图,不改 S.recentColors / settings。
|
||||
if (process.env.ANNOT_SHOT2) {
|
||||
await page.evaluate(() => {
|
||||
const rec = document.querySelector('.iwb-editor-color-pop .iwb-editor-recent-colors')
|
||||
const group = rec.closest('.iwb-color-group')
|
||||
const list = ['#ffd400', '#e34d59', '#1677ff', '#0f9d58', '#6b4fbb', '#c0392b',
|
||||
'#ff8a00', '#4cd964', '#00bfa5', '#4488ff', '#aa44ff', '#ff66aa',
|
||||
'#d0d0d0', '#808080', '#ffffff', '#000000']
|
||||
rec.innerHTML = list.map((c) =>
|
||||
`<button type="button" class="iwb-editor-color-panel-swatch" data-panel-color="${c}" style="background:${c}" title="最近使用 ${c}"></button>`).join('')
|
||||
rec.hidden = false
|
||||
if (group) group.hidden = false
|
||||
})
|
||||
await page.waitForTimeout(120)
|
||||
await page.locator('.iwb-editor-color-pop').screenshot({ path: process.env.ANNOT_SHOT2 })
|
||||
}
|
||||
await page.keyboard.press('Escape')
|
||||
await page.waitForTimeout(120)
|
||||
check('选过的颜色进入「最近使用」并出现在色板弹层',
|
||||
@@ -2405,11 +2616,13 @@ const popTarget = await page.evaluate(() => {
|
||||
return {
|
||||
open: !pop.hidden,
|
||||
fillActive: pop.querySelector('.iwb-color-pop-tab[data-color-slot="fill"]').classList.contains('active'),
|
||||
noneVisible: !pop.querySelector('[data-color-none]').hidden
|
||||
noneVisible: !!pop.querySelector('[data-color-none]').offsetParent,
|
||||
noneUsable: !pop.querySelector('[data-color-none]').disabled
|
||||
}
|
||||
})
|
||||
check('点填充槽打开色板:目标是填充,并出现「无」按钮',
|
||||
popTarget.open && popTarget.fillActive && popTarget.noneVisible, JSON.stringify(popTarget))
|
||||
check('点填充槽打开色板:目标是填充,去色在第一格且可用',
|
||||
popTarget.open && popTarget.fillActive && popTarget.noneVisible && popTarget.noneUsable,
|
||||
JSON.stringify(popTarget))
|
||||
|
||||
// 用一个画布上不会出现的怪色(#a014b2)验收:12 个推荐色在前面用例里都用过,
|
||||
// 拿黄色/绿色统计会数到别的图形,永远清不到 0。
|
||||
@@ -2532,6 +2745,177 @@ const shiftXSwap = await (async () => {
|
||||
})()
|
||||
check('Shift+X 交换填充色与描边色(填充不会被关掉、再按回到原样)', shiftXSwap.ok, shiftXSwap.detail)
|
||||
|
||||
// ================================================================
|
||||
// v1.17:描边也能是「无色」;只要有一边无色,Shift+X 照样能交换
|
||||
// ================================================================
|
||||
// 用户原话:「让矢量图形与钢笔的描边色也可以去掉」
|
||||
// 「让描边与填充,有一个是无色的时候,可以交换,现在是不可以的」
|
||||
const setOptColor = (slot, hex) => page.evaluate(({ slot, hex }) => {
|
||||
const el = document.querySelector(`.iwb-editor-optionbar-body [data-shape-color="${slot}"]`)
|
||||
el.value = hex
|
||||
el.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
}, { slot, hex })
|
||||
|
||||
async function drawRectAt(x1, y1, x2, y2) {
|
||||
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
|
||||
const a = { x: imgBox.x + imgBox.width * x1, y: imgBox.y + imgBox.height * y1 }
|
||||
const b = { x: imgBox.x + imgBox.width * x2, y: imgBox.y + imgBox.height * y2 }
|
||||
await page.mouse.move(a.x, a.y); await page.mouse.down()
|
||||
await page.mouse.move(b.x, b.y, { steps: 6 }); await page.mouse.up()
|
||||
await page.waitForTimeout(180)
|
||||
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
|
||||
await page.mouse.click((a.x + b.x) / 2, (a.y + b.y) / 2)
|
||||
await page.waitForTimeout(160)
|
||||
return { a, b }
|
||||
}
|
||||
|
||||
// 取选中形状 + 三处 UI 的「无」状态,后面几条都用它
|
||||
const selectedShapeState = () => page.evaluate(() => {
|
||||
const d = window.__iwbEditor.__debug()
|
||||
const s = d.shapes.find(x => x.id === d.selectedShapeId)
|
||||
const btn = document.querySelector('.iwb-editor-color-pair [data-color-slot="stroke"]')
|
||||
const opt = document.querySelector('.iwb-editor-optionbar-body [data-shape-color="stroke"]')
|
||||
const none = document.querySelector('.iwb-editor-color-pop [data-color-none]')
|
||||
return {
|
||||
type: s && s.type, closed: s && s.closed,
|
||||
strokeOn: s && s.strokeOn, fill: s && s.fill,
|
||||
color: s && s.color, fillColor: s && s.fillColor,
|
||||
strokeBtnNone: !!btn && btn.classList.contains('is-none'),
|
||||
optOff: !!opt && opt.classList.contains('is-off'),
|
||||
// v1.20:去色永远在,只是不可用时 disabled(灰色),所以断言的是「能不能用」不是「在不在」
|
||||
noneDisabled: !none || none.disabled,
|
||||
noneActive: !!none && none.classList.contains('active')
|
||||
}
|
||||
})
|
||||
|
||||
// ---- 形状:去掉描边 ----
|
||||
// 描边给一个画布上没出现过的洋红,靠像素数证明「框真的没了」而不是只改了数据
|
||||
await drawRectAt(0.55, 0.52, 0.82, 0.74)
|
||||
await setOptColor('fill', '#0aa6c8')
|
||||
await page.waitForTimeout(160)
|
||||
await setOptColor('stroke', '#ff00aa')
|
||||
await page.waitForTimeout(220)
|
||||
// 按画布分别数:画布上还躺着别的早期用例留下的同色对象(文字就用了 #ff00aa),
|
||||
// 全局求和会把它们算进来 —— 只认「某一个画布从有变没有」才说得清这条描边真的没了
|
||||
const magentaPerCanvas = () => page.evaluate(() => [...document.querySelectorAll('.iwb-editor-vec-canvas')].map(cv => {
|
||||
const d = cv.getContext('2d').getImageData(0, 0, cv.width, cv.height).data
|
||||
let n = 0
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
if (d[i + 3] > 200 && Math.abs(d[i] - 255) < 8 && d[i + 1] < 8 && Math.abs(d[i + 2] - 170) < 8) n++
|
||||
}
|
||||
return n
|
||||
}))
|
||||
const magentaBefore = await magentaPerCanvas()
|
||||
await page.locator('.iwb-editor-color-btn[data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(220)
|
||||
const noneShownOnStroke = await page.evaluate(() =>
|
||||
!document.querySelector('.iwb-editor-color-pop [data-color-none]').disabled)
|
||||
// 开发用:ANNOT_SHOT4=/tmp/pop-none.png 出「去色可用态」的效果图(形状描边上下文)
|
||||
if (process.env.ANNOT_SHOT4) await page.locator('.iwb-editor-color-pop').screenshot({ path: process.env.ANNOT_SHOT4 })
|
||||
await page.evaluate(() => document.querySelector('.iwb-editor-color-pop [data-color-none]').click())
|
||||
await page.waitForTimeout(320)
|
||||
const noStroke = await selectedShapeState()
|
||||
const magentaAfter = await magentaPerCanvas()
|
||||
const cyanStill = await countColorInVec([10, 166, 200], 8)
|
||||
const strokeGone = magentaBefore.some((n, i) => n > 300 && magentaAfter[i] === 0)
|
||||
const noNewMagenta = magentaAfter.every((n, i) => n <= magentaBefore[i])
|
||||
check('形状可以去掉描边:描边像素清零,填充色与描边色都留着',
|
||||
noneShownOnStroke && strokeGone && noNewMagenta &&
|
||||
noStroke.strokeOn === false && noStroke.fill === true &&
|
||||
noStroke.color === '#ff00aa' && cyanStill > 300,
|
||||
JSON.stringify({ noneShownOnStroke, magentaBefore, magentaAfter, cyanStill, ...noStroke }))
|
||||
check('无描边时工具栏描边格画斜杠、选项栏描边色块置灰、色板「无」高亮',
|
||||
noStroke.strokeBtnNone === true && noStroke.optOff === true && noStroke.noneActive === true,
|
||||
JSON.stringify({ btn: noStroke.strokeBtnNone, opt: noStroke.optOff, none: noStroke.noneActive }))
|
||||
|
||||
// 对称保护:已经无描边、再把填充也点掉 → 对象会彻底隐形,应当自动把描边还回来
|
||||
await page.locator('.iwb-editor-color-btn[data-color-slot="fill"]').click()
|
||||
await page.waitForTimeout(200)
|
||||
await page.evaluate(() => document.querySelector('.iwb-editor-color-pop [data-color-none]').click())
|
||||
await page.waitForTimeout(300)
|
||||
const bothNone = await selectedShapeState()
|
||||
check('「无描边」后再点「无填充」:自动恢复描边,不会留下一个看不见的对象',
|
||||
bothNone.fill === false && bothNone.strokeOn === true,
|
||||
JSON.stringify({ fill: bothNone.fill, strokeOn: bothNone.strokeOn }))
|
||||
// 回到「无描边」状态给下一条用例用(色板此时停在填充槽,先切回描边)
|
||||
await page.locator('.iwb-editor-color-btn[data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(200)
|
||||
await page.evaluate(() => document.querySelector('.iwb-editor-color-pop [data-color-none]').click())
|
||||
await page.waitForTimeout(280)
|
||||
|
||||
// 选色即恢复描边:与「文字描边宽度 0 时选色自动给 6px」同一条逻辑,
|
||||
// 否则用户选了颜色画面没变化,会以为颜色设置坏了
|
||||
await page.evaluate(() => {
|
||||
const el = document.querySelector('.iwb-editor-color-pop .iwb-editor-color-hex-input')
|
||||
el.value = '#ff00aa'
|
||||
el.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
})
|
||||
await page.waitForTimeout(320)
|
||||
const revivedStroke = await selectedShapeState()
|
||||
const magentaRevived = await magentaPerCanvas()
|
||||
const strokeBack = magentaRevived.some((n, i) => n > 300 && magentaAfter[i] === 0)
|
||||
check('无描边时再选一次颜色 → 自动恢复描边(选了色一定有变化)',
|
||||
revivedStroke.strokeOn === true && revivedStroke.color === '#ff00aa' && strokeBack,
|
||||
JSON.stringify({ ...revivedStroke, strokeBack, magentaAfter, magentaRevived }))
|
||||
|
||||
// ---- 钢笔闭合路径:同样能去掉描边 ----
|
||||
await page.locator('.iwb-editor-tool[data-tool="pen"]').click()
|
||||
const t1 = { x: imgBox.x + imgBox.width * 0.34, y: imgBox.y + imgBox.height * 0.16 }
|
||||
const t2 = { x: imgBox.x + imgBox.width * 0.46, y: imgBox.y + imgBox.height * 0.16 }
|
||||
const t3 = { x: imgBox.x + imgBox.width * 0.40, y: imgBox.y + imgBox.height * 0.34 }
|
||||
await page.mouse.click(t1.x, t1.y); await page.waitForTimeout(90)
|
||||
await page.mouse.click(t2.x, t2.y); await page.waitForTimeout(90)
|
||||
await page.mouse.click(t3.x, t3.y); await page.waitForTimeout(90)
|
||||
await page.mouse.click(t1.x, t1.y); await page.waitForTimeout(280) // 回到起点 = 闭合
|
||||
await page.locator('.iwb-editor-color-btn[data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(220)
|
||||
await page.evaluate(() => document.querySelector('.iwb-editor-color-pop [data-color-none]').click())
|
||||
await page.waitForTimeout(320)
|
||||
const penNoStroke = await selectedShapeState()
|
||||
check('钢笔闭合路径也能去掉描边(去掉后只剩填充面,不会整个消失)',
|
||||
penNoStroke.type === 'pen' && penNoStroke.closed === true &&
|
||||
penNoStroke.strokeOn === false && penNoStroke.fill === true,
|
||||
JSON.stringify(penNoStroke))
|
||||
|
||||
// 未闭合路径没有可填内部:去掉描边 = 这条线没了,索性不给「无」
|
||||
await page.locator('.iwb-editor-tool[data-tool="pen"]').click()
|
||||
await page.mouse.click(imgBox.x + imgBox.width * 0.62, imgBox.y + imgBox.height * 0.36)
|
||||
await page.waitForTimeout(90)
|
||||
await page.mouse.click(imgBox.x + imgBox.width * 0.76, imgBox.y + imgBox.height * 0.42)
|
||||
await page.waitForTimeout(90)
|
||||
await page.keyboard.press('Enter') // 回车结束开放路径
|
||||
await page.waitForTimeout(280)
|
||||
await page.locator('.iwb-editor-color-btn[data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(220)
|
||||
const openPen = await selectedShapeState()
|
||||
check('未闭合钢笔不给「无描边」(去掉等于把这条线删了):去色留在原位但置灰',
|
||||
openPen.type === 'pen' && openPen.closed === false && openPen.noneDisabled === true,
|
||||
JSON.stringify(openPen))
|
||||
|
||||
// ---- 一边无色也能交换(用户反馈的第二个问题)----
|
||||
await page.keyboard.press('Escape')
|
||||
await drawRectAt(0.08, 0.10, 0.30, 0.30)
|
||||
// 先做成「只有描边」:fill 关掉,描边给独立色
|
||||
await page.evaluate(() => {
|
||||
const btn = document.querySelector('.iwb-editor-optionbar-body [data-opt-toggle="stroke"]')
|
||||
if (btn) btn.click()
|
||||
})
|
||||
await page.waitForTimeout(200)
|
||||
await setOptColor('stroke', '#ff00aa')
|
||||
await page.waitForTimeout(220)
|
||||
const onlyStroke = await selectedShapeState()
|
||||
await page.keyboard.press('Shift+x')
|
||||
await page.waitForTimeout(260)
|
||||
const afterSwap1 = await selectedShapeState()
|
||||
await page.keyboard.press('Shift+x')
|
||||
await page.waitForTimeout(260)
|
||||
const afterSwap2 = await selectedShapeState()
|
||||
check('一边无色也能交换:只描边 → 只填充(描边关、填充开),再按回到原样',
|
||||
onlyStroke.strokeOn === true && onlyStroke.fill === false &&
|
||||
afterSwap1.strokeOn === false && afterSwap1.fill === true &&
|
||||
afterSwap2.strokeOn === true && afterSwap2.fill === false,
|
||||
JSON.stringify({ 原: onlyStroke, 按一次: afterSwap1, 再按: afterSwap2 }))
|
||||
|
||||
// ================================================================
|
||||
// v1.15 图片调节(放最后:会改像素,放中间会污染依赖像素的用例)
|
||||
// ================================================================
|
||||
@@ -2553,40 +2937,40 @@ check('右侧栏出现「图片调节」,11 项齐全且顺序固定',
|
||||
adjRowCount === 11 && adjNames.join('/') === '曝光/明度/对比度/阴影/高光/色相/饱和度/温度/色调/锐度/清晰度',
|
||||
'rows=' + adjRowCount + ' ' + adjNames.join('/'))
|
||||
|
||||
// ---------- v1.16:右栏常驻调色面板 / 两处同步 / 可拖宽度 / 字号 ----------
|
||||
const sideSurface = await page.evaluate(() => {
|
||||
const side = document.querySelector('.iwb-editor-left [data-color-surface="side"]')
|
||||
if (!side) return null
|
||||
const tabs = [...side.querySelectorAll('.iwb-color-pop-tab')]
|
||||
// ---------- v1.19:右栏调色模块删除(用户 2026-11-10)/ 可拖宽度 / 字号 ----------
|
||||
const sideFirst = await page.evaluate(() => {
|
||||
const aside = document.querySelector('.iwb-editor-left')
|
||||
const firstSection = aside && aside.querySelector(':scope > section')
|
||||
return {
|
||||
tabs: tabs.length,
|
||||
visibleTabs: tabs.filter(t => !t.hidden).length,
|
||||
swatches: side.querySelectorAll('.iwb-editor-color-swatches [data-panel-color]').length,
|
||||
sv: !!side.querySelector('.iwb-color-sv'),
|
||||
hue: !!side.querySelector('.iwb-color-hue'),
|
||||
hex: !!side.querySelector('.iwb-editor-color-hex-input')
|
||||
hasColor: Boolean(aside && aside.querySelector('[data-color-surface]')),
|
||||
first: firstSection ? firstSection.className : '',
|
||||
popCount: document.querySelectorAll('.iwb-editor-color-pop').length,
|
||||
}
|
||||
})
|
||||
check('右栏有常驻调色面板:可调颜色项 + 调色器 + 12 个常用色',
|
||||
Boolean(sideSurface) && sideSurface.tabs === 3 && sideSurface.visibleTabs >= 1 &&
|
||||
sideSurface.swatches === 12 && sideSurface.sv && sideSurface.hue && sideSurface.hex,
|
||||
JSON.stringify(sideSurface))
|
||||
check('右栏调色模块已删:侧栏第一个模块是「图片调节」,颜色只剩弹层一处',
|
||||
sideFirst.hasColor === false && /iwb-editor-adj/.test(sideFirst.first) && sideFirst.popCount === 1,
|
||||
JSON.stringify(sideFirst))
|
||||
|
||||
// 在右栏点常用色 → 弹层里同一色块也必须高亮(两处共用一份颜色状态)
|
||||
await page.locator('.iwb-editor-left [data-color-surface="side"] [data-panel-color="#00bfa5"]').click()
|
||||
await page.waitForTimeout(220)
|
||||
// 弹层里选常用色:色块 active 圈 / HEX 输入 / 工具栏色点三处必须同时变
|
||||
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(120)
|
||||
await page.locator('.iwb-editor-color-pop .iwb-editor-color-swatches [data-panel-color="#00bfa5"]').click()
|
||||
await page.waitForTimeout(200)
|
||||
const colorSync = await page.evaluate(() => {
|
||||
// 只看「常用色」网格:最近使用里同色也会高亮,那是正常的两处提示,不该算进断言
|
||||
const activeIn = (root) => [...root.querySelectorAll('.iwb-editor-color-swatches [data-panel-color]')]
|
||||
const active = [...document.querySelectorAll('.iwb-editor-color-pop .iwb-editor-color-swatches [data-panel-color]')]
|
||||
.filter(b => b.classList.contains('active')).map(b => b.dataset.panelColor)
|
||||
const side = document.querySelector('.iwb-editor-left [data-color-surface="side"]')
|
||||
const pop = document.querySelector('.iwb-editor-color-pop')
|
||||
return { side: activeIn(side), pop: activeIn(pop), color: window.__iwbEditor.__debug().color }
|
||||
return {
|
||||
active,
|
||||
hex: document.querySelector('.iwb-editor-color-pop .iwb-editor-color-hex-input').value,
|
||||
color: window.__iwbEditor.__debug().color,
|
||||
}
|
||||
})
|
||||
check('右栏选色后弹层同一色块同步高亮(不是两套各管各的)',
|
||||
colorSync.side.length === 1 && colorSync.side[0] === '#00bfa5' &&
|
||||
colorSync.pop.length === 1 && colorSync.pop[0] === '#00bfa5' && colorSync.color === '#00bfa5',
|
||||
check('弹层选色:常用色高亮 + HEX 回填 + 主色统一(三处不是各说各话)',
|
||||
colorSync.active.length === 1 && colorSync.active[0] === '#00bfa5' &&
|
||||
colorSync.hex.toLowerCase() === '#00bfa5' && colorSync.color === '#00bfa5',
|
||||
JSON.stringify(colorSync))
|
||||
await page.keyboard.press('Escape')
|
||||
await page.waitForTimeout(90)
|
||||
|
||||
// 拖右栏宽度:侧栏在画布右侧,指针左移 80px ⇒ 宽 80px
|
||||
const sideW0 = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width))
|
||||
|
||||
@@ -28,9 +28,12 @@ v0.2 换 potrace,并且按用户要求**只做单色 / 灰度**(不做彩色
|
||||
背景默认白)+「带底」勾选(决定背景色是否写进导出)
|
||||
- **按孤岛拆分**(默认开):每个连通块输出为一个独立 `<path>` 元素,粘到 Figma 就是多个
|
||||
可单独选中的图层;关掉则整图合并成一个 path(便于整体缩放/移动)
|
||||
- 预览:按住空格对比原图;面板显示元素数 / 层数 / 体积 / 耗时
|
||||
- 输出:**复制 SVG**(写 `image/svg+xml` + `text/html` + `text/plain` 三种剪贴板口味,
|
||||
Figma / Illustrator 粘进去就是真矢量)· **下载 SVG** · **保存为节点**(PNG,按输出倍率 1–4× 从矢量重绘)
|
||||
- 预览:按住空格对比原图;**滚轮/捏合缩放、左键拖动平移、双击复位**(0.2×–8×);面板显示元素数 / 层数 / 体积 / 耗时
|
||||
- 顶栏按钮(左 → 右):**保存为节点** · **复制 SVG** · **下载 SVG** · 取消(四颗统一描边配色,不用绿色主按钮)
|
||||
- **保存为节点**:PNG,按输出倍率 1–4× 从矢量重绘后写回画布
|
||||
- **复制 SVG**:写 `image/svg+xml` + `text/html` + `text/plain` 三种剪贴板口味,
|
||||
Figma / Illustrator 粘进去就是真矢量
|
||||
- **下载 SVG**:存成文件
|
||||
|
||||
## 按孤岛拆分(v0.3)
|
||||
|
||||
@@ -84,6 +87,34 @@ potrace 出厂把**整张图所有轮廓**塞进同一个 `<path>` 的 d 里(8
|
||||
白底 + 白底稿(菜单、白底商品图)会看不出画面边界,所以预览图本身留了一圈 1px 极淡描边 +
|
||||
细阴影;这是唯一一处「为了看清边界」而加的装饰。
|
||||
|
||||
## 预览缩放 / 平移(v0.4)
|
||||
|
||||
描摹结果要放大看细节(笔画接缝、圆角有没有被拟合成直线),所以预览区是一块可缩放画布:
|
||||
|
||||
| 操作 | 行为 |
|
||||
|---|---|
|
||||
| 鼠标滚轮 / 触控板捏合 | 以**光标位置为锚点**缩放(0.2×–8×) |
|
||||
| 按住左键拖动 / 按住中键拖动 | 平移画布(100% 时也能拖) |
|
||||
| 水平滚动(`Shift` + 滚轮也是这种) | 只平移,不改倍率 |
|
||||
| 双击 / 点右下角「172% 复位」/ 按 `0` | 回到 100% 等比铺满 |
|
||||
| `+` / `-` | 以画面中心缩放 |
|
||||
|
||||
三个实现上的取舍:
|
||||
|
||||
- **视图状态写进 `.vz-preview` 的 CSS 变量**(`--vz-zoom` / `--vz-pan-x` / `--vz-pan-y`),
|
||||
由两张 `<img>`(矢量 + 原图)各自 `transform: var(...)` 引用。按住空格切原图时视图**纹丝不动** ——
|
||||
要是每张图各存一份状态,切过去那一刻画面就会跳。harness 有断言锁这个行为。
|
||||
- **锚点缩放**才有「指哪放大哪」的感觉。推导:图片中心恒在「预览区中心 + pan」,屏幕点 P 的图上偏移
|
||||
`d = (P − C − pan) / zoom`,要让 P 不动需 `pan′ = pan + d·(zoom − zoom′)`。
|
||||
- **滚轮一律缩放,不猜设备**。第一版想区分「鼠标滚轮 vs 触控板双指滑动」,判定条件写成
|
||||
「`deltaY` 是 ±100 这类整数且 ≥48」—— 结果鼠标开着平滑滚动、或高精度滚轮给小数步长时,
|
||||
滚轮被当成双指滑动,表现成**拖图不放大**(用户实测踩到)。现在只按主导轴分:
|
||||
垂直 → 缩放,水平 → 平移。步长按幅度分两档(≥40 用 0.0018,细碎小数用 0.012),
|
||||
让鼠标一格约 1.2×、触控板小步也跟手。
|
||||
|
||||
布局上 `.vz-stage` 从 flex 居中改成 `position: absolute` + `translate(-50%, -50%)`:
|
||||
缩放锚点要求元素的变换中心稳稳落在预览区正中,flex 居中下图片尺寸一变中心就会漂。
|
||||
|
||||
## 复制到剪贴板为什么写三种口味
|
||||
|
||||
剪贴板不像文件,只有一个「格式」——它同时可以装多份不同 MIME 的数据,读的一方自己挑。
|
||||
@@ -105,8 +136,8 @@ potrace 与其 JS 移植都是 **GPL-2.0**(见 `plugin/vendor/potrace/LICENSE`
|
||||
```bash
|
||||
npm run build -- image-vectorize # plugin/ → src/index.js(esbuild IIFE)
|
||||
npm run validate # 契约校验
|
||||
node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,47 项)
|
||||
node image-vectorize/tools/e2e-site.mjs # 真站(KV / SRI / CSP / 真实画布桥)
|
||||
node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,64 项)
|
||||
node image-vectorize/tools/e2e-site.mjs # 桌面客户端端到端(市场安装 / SRI / CSP / 真实画布桥)
|
||||
|
||||
# 拿真实素材调参数(不进 CI,最快看到效果):
|
||||
node image-vectorize/tools/trace-cli.mjs ~/Desktop/menu.png --mode gray --levels 3
|
||||
@@ -115,14 +146,16 @@ node image-vectorize/tools/trace-cli.mjs ~/Desktop/logo.png --mode mono --no-spl
|
||||
# → 产物 SVG + 一张「原图 / 结果」对比图(~-/tmp/vz-cli/)
|
||||
```
|
||||
|
||||
发布:
|
||||
发布:本仓只产出 `src/index.js`(构建产物),发布走桌面仓的市场链路,见根 README「发布到市场」:
|
||||
|
||||
```bash
|
||||
cp image-vectorize/src/index.js /tmp/plugin-image-vectorize.js
|
||||
cd ../image-workbench-web && node scripts/plugins-publish.mjs /tmp/plugin-image-vectorize.js \
|
||||
--version image-vectorize=0.3.0 --upload
|
||||
npm run build -- image-vectorize && npm run validate
|
||||
# 桌面仓:node scripts/sync-plugins-from-repo.js && node scripts/gen-market.js
|
||||
# 再把 market/ 上传到 NAS(market.maqiart.eu.org)
|
||||
```
|
||||
|
||||
改版本时同步 `package.json` 的 `version`(构建时注入 manifest)与桌面仓同步脚本读取的版本。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- **照片不适合**:potrace 只懂明暗,照片会被压成几块灰阶(这不是 bug,是算法定位)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/image-vectorize",
|
||||
"private": true,
|
||||
"version": "0.3.1",
|
||||
"version": "0.6.1",
|
||||
"description": "位图转矢量:potrace(纯 JS)单色/灰度描摹,输出 SVG 与 PNG 节点;对文字、logo、线稿保形好,不需要 wasm",
|
||||
"ibwPlugin": {
|
||||
"id": "image-vectorize",
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。
|
||||
//
|
||||
// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。
|
||||
// skin: 'private' = 自绘深色工具 UI(#1b1b22 系列),不跟随宿主主题。
|
||||
// 代价由宿主契约测试钉死:声明 private 的插件不得引用宿主颜色 var(--iwb-*),只能自洽。
|
||||
var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
id: 'image-vectorize',
|
||||
name: '位图转矢量',
|
||||
version: '__PLUGIN_VERSION__',
|
||||
apiVersion: 1,
|
||||
skin: 'private',
|
||||
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
|
||||
settings: {
|
||||
preset: { type: 'string', default: 'text' },
|
||||
|
||||
@@ -16,15 +16,15 @@
|
||||
.vz-modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 92vw;
|
||||
height: 88vh;
|
||||
min-width: 760px;
|
||||
min-height: 520px;
|
||||
max-width: 1680px;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
max-width: none;
|
||||
background: #1b1b22;
|
||||
border: 1px solid #33333f;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55);
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@@ -75,14 +75,16 @@
|
||||
.vz-btn:hover { background: #34343f; border-color: #4a4a5c; }
|
||||
.vz-btn:active { background: #2f2f3a; }
|
||||
.vz-btn:disabled { opacity: 0.45; cursor: default; }
|
||||
|
||||
.vz-btn-primary {
|
||||
background: #1f7a52;
|
||||
border-color: #27875c;
|
||||
color: #eafff5;
|
||||
/* 顶栏「保存为节点 / 复制 SVG / 下载 SVG」三颗走上面这套灰色描边配色。
|
||||
「关闭」单独用编辑器主色调(.vz-seg 选中态同款 #33566f)填充,与产出操作区分、防误点。
|
||||
2026-11-19:原「取消」改名「关闭」并按主色调取色(行为不变,仍是 data-act="cancel" 退出编辑器)。 */
|
||||
.vz-btn-close {
|
||||
background: #33566f;
|
||||
border-color: #33566f;
|
||||
color: #eaf6ff;
|
||||
}
|
||||
.vz-btn-primary:hover { background: #248a5d; border-color: #2f9c69; }
|
||||
.vz-btn-primary:disabled { background: #24503e; border-color: #2a5c47; }
|
||||
.vz-btn-close:hover { background: #3d6480; border-color: #4a7394; }
|
||||
.vz-btn-close:active { background: #2c4a60; }
|
||||
|
||||
/* ---------- 主体 ---------- */
|
||||
.vz-body {
|
||||
@@ -104,15 +106,41 @@
|
||||
棋盘格既干扰判断形状,也让深色细笔画看起来发虚(实测用户第一反应是「糊」)。
|
||||
矢量 SVG 本身仍不含背景矩形,导出/复制到 Figma 依旧是透明底。 */
|
||||
background-color: #ffffff;
|
||||
/* 缩放 / 平移的**唯一真源**:矢量图与原图两张 img 共用这套变量,
|
||||
所以按住空格对比时,视图完全不动(各自存一份状态迟早会对不上)。
|
||||
量纲:zoom 无单位;pan 是**屏幕像素**(先 scale 后 translate,平移量不被缩放放大)。 */
|
||||
--vz-zoom: 1;
|
||||
--vz-pan-x: 0px;
|
||||
--vz-pan-y: 0px;
|
||||
cursor: grab;
|
||||
/* 触屏 / 触控板手势全部自己处理,别让浏览器抢去做页面滚动 */
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.vz-preview.is-panning { cursor: grabbing; }
|
||||
|
||||
/* 白底之上用一圈极淡的描边 + 细阴影标出画面边界:
|
||||
白底稿(如菜单/白底商品图)与预览区同色时,否则看不出图到哪里 */
|
||||
白底稿(如菜单/白底商品图)与预览区同色时,否则看不出图到哪里。
|
||||
绝对定位 + 50%/50% 是为了让 transform 的中心锚点稳定落在预览区正中(缩放锚点计算依赖这一点);
|
||||
max-* 用 calc(100% - 40px) 抵掉 .vz-preview 的 20px padding(百分比相对 padding box 算)。 */
|
||||
.vz-stage {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
max-width: calc(100% - 40px);
|
||||
max-height: calc(100% - 40px);
|
||||
display: block;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.07);
|
||||
transform:
|
||||
translate(-50%, -50%)
|
||||
translate(var(--vz-pan-x), var(--vz-pan-y))
|
||||
scale(var(--vz-zoom));
|
||||
transform-origin: 50% 50%;
|
||||
/* 拖动时每帧改 transform,提前提层,避免整块重绘掉帧(最多两张图,内存代价可忽略) */
|
||||
will-change: transform;
|
||||
/* 拖动时别触发 img 的原生拖拽(会拽出一个半透明缩略图,手势直接断掉) */
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
|
||||
.vz-stage[hidden] { display: none; }
|
||||
@@ -148,6 +176,32 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 缩放倍率:只有真的缩放过才出现(100% 时挂 hidden,不占视线)。
|
||||
它同时是「现在没在 1:1」的唯一视觉信号 —— 用户放大看细节后容易忘记自己还缩着。 */
|
||||
.vz-zoom {
|
||||
position: absolute;
|
||||
right: 14px;
|
||||
bottom: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 9px;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 255, 255, 0.94);
|
||||
border: 1px solid rgba(0, 0, 0, 0.12);
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
|
||||
color: #45454f;
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.vz-zoom[hidden] { display: none; }
|
||||
.vz-zoom b { font-weight: 600; }
|
||||
.vz-zoom span { color: #9a9aa8; }
|
||||
.vz-zoom:hover { border-color: rgba(0, 0, 0, 0.22); }
|
||||
.vz-zoom:hover span { color: #45454f; }
|
||||
|
||||
/* 描摹中/出错的浮层 */
|
||||
.vz-status {
|
||||
position: absolute;
|
||||
@@ -466,7 +520,7 @@
|
||||
|
||||
/* 窄屏:面板转到底部 */
|
||||
@media (max-width: 900px) {
|
||||
.vz-modal { width: 96vw; height: 92vh; min-width: 0; }
|
||||
.vz-modal { width: 100vw; height: 100vh; min-width: 0; }
|
||||
.vz-body { flex-direction: column; }
|
||||
.vz-panel { width: auto; max-height: 46%; border-left: 0; border-top: 1px solid #2e2e3a; }
|
||||
}
|
||||
@@ -128,18 +128,21 @@ function viewHTML(name) {
|
||||
'<header class="vz-header">' +
|
||||
'<span class="vz-title">位图转矢量<em data-meta>' + esc(name) + '</em></span>' +
|
||||
'<div class="vz-spacer"></div>' +
|
||||
'<button type="button" class="vz-btn" data-act="cancel">取消</button>' +
|
||||
// 顺序:主操作在左,取消在最右(用户 2026-11-09 要求与原先互换)。
|
||||
// 四颗按钮同一套描边配色,不再给主操作上绿色填充 —— 用户口径「颜色都用取消按钮的配色」。
|
||||
'<button type="button" class="vz-btn" data-act="save">保存为节点</button>' +
|
||||
'<button type="button" class="vz-btn" data-act="copy">复制 SVG</button>' +
|
||||
'<button type="button" class="vz-btn" data-act="svg">下载 SVG</button>' +
|
||||
'<button type="button" class="vz-btn vz-btn-primary" data-act="save">保存为节点</button>' +
|
||||
'<button type="button" class="vz-btn vz-btn-close" data-act="cancel">关闭</button>' +
|
||||
'</header>' +
|
||||
'<div class="vz-body">' +
|
||||
'<div class="vz-preview">' +
|
||||
'<img class="vz-stage" data-stage="vector" alt="矢量预览">' +
|
||||
'<img class="vz-stage" data-stage="original" alt="原图" hidden>' +
|
||||
'<div class="vz-preview" data-preview>' +
|
||||
'<img class="vz-stage" data-stage="vector" alt="矢量预览" draggable="false">' +
|
||||
'<img class="vz-stage" data-stage="original" alt="原图" draggable="false" hidden>' +
|
||||
'<div class="vz-badge" data-badge>矢量预览</div>' +
|
||||
'<div class="vz-status" data-status hidden><i class="vz-dot"></i><span data-status-text></span></div>' +
|
||||
'<div class="vz-hint">空格 对比原图 · 「复制 SVG」可直接粘到 Figma</div>' +
|
||||
'<div class="vz-hint">空格 对比原图 · 滚轮缩放 · 拖动平移 · 双击复位</div>' +
|
||||
'<div class="vz-zoom" data-zoom-chip hidden title="点击回到 100%"><b data-zoom-val>100%</b><span>复位</span></div>' +
|
||||
'</div>' +
|
||||
'<aside class="vz-panel" data-panel></aside>' +
|
||||
'</div></div></div>'
|
||||
@@ -171,6 +174,11 @@ export function createVectorizer(options) {
|
||||
let seq = 0
|
||||
let debounceTimer = 0
|
||||
let spaceDown = false
|
||||
// 预览视图(缩放 + 平移):zoom=1 / pan=0 就是原始「等比铺满」,双击或点倍率胶囊复位
|
||||
let zoom = 1
|
||||
let panX = 0
|
||||
let panY = 0
|
||||
let drag = null
|
||||
|
||||
// ---------- 设置读写 ----------
|
||||
|
||||
@@ -323,6 +331,112 @@ export function createVectorizer(options) {
|
||||
els.badge.textContent = spaceDown ? '原图' : '矢量预览'
|
||||
}
|
||||
|
||||
// ---------- 预览视图:缩放 / 平移 ----------
|
||||
//
|
||||
// 为什么把状态写进 CSS 变量而不是直接改每张图的 style.transform:
|
||||
// 预览里有「矢量」和「原图」两张 img 靠显隐切换做对比,各存一份视图状态迟早对不上
|
||||
// (按住空格那一瞬间画面会跳)。变量挂在 .vz-preview 上,两张图共用,天然同步。
|
||||
|
||||
const ZOOM_MIN = 0.2
|
||||
const ZOOM_MAX = 8
|
||||
|
||||
function applyView() {
|
||||
if (!els || !els.preview) return
|
||||
els.preview.style.setProperty('--vz-zoom', String(zoom))
|
||||
els.preview.style.setProperty('--vz-pan-x', panX + 'px')
|
||||
els.preview.style.setProperty('--vz-pan-y', panY + 'px')
|
||||
const changed = zoom !== 1 || panX !== 0 || panY !== 0
|
||||
if (els.zoomVal) els.zoomVal.textContent = Math.round(zoom * 100) + '%'
|
||||
// 倍率胶囊只在真的缩放过时出现:100% 状态挂个「100% 复位」纯属噪音
|
||||
if (els.zoomChip) els.zoomChip.hidden = !changed
|
||||
}
|
||||
|
||||
function resetView() {
|
||||
zoom = 1
|
||||
panX = 0
|
||||
panY = 0
|
||||
drag = null
|
||||
if (els && els.preview) els.preview.classList.remove('is-panning')
|
||||
applyView()
|
||||
}
|
||||
|
||||
/**
|
||||
* 以屏幕点 (clientX, clientY) 为锚点缩放 —— 鼠标下的像素在缩放前后停在原处,
|
||||
* 否则「想放大看这个字」会变成「放大完还得把它找回来」。
|
||||
*
|
||||
* 推导:图片中心恒在「预览区中心 + pan」,屏幕点 P 对应的图上偏移 d = (P - C - pan) / zoom,
|
||||
* 要让 P 不动即 C + pan + d·zoom = C + pan' + d·zoom′ ⇒ pan′ = pan + d·(zoom − zoom′)。
|
||||
*/
|
||||
function zoomAt(clientX, clientY, factor) {
|
||||
if (!els || !els.preview) return
|
||||
const next = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, zoom * factor))
|
||||
if (Math.abs(next - zoom) < 1e-4) return
|
||||
const rect = els.preview.getBoundingClientRect()
|
||||
const dx = (clientX - (rect.left + rect.width / 2) - panX) / zoom
|
||||
const dy = (clientY - (rect.top + rect.height / 2) - panY) / zoom
|
||||
panX -= dx * (next - zoom)
|
||||
panY -= dy * (next - zoom)
|
||||
zoom = next
|
||||
applyView()
|
||||
}
|
||||
|
||||
function zoomAtCenter(factor) {
|
||||
if (!els || !els.preview) return
|
||||
const rect = els.preview.getBoundingClientRect()
|
||||
zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, factor)
|
||||
}
|
||||
|
||||
function onPreviewWheel(event) {
|
||||
event.preventDefault()
|
||||
// 滚轮 = 缩放,无条件(用户口径:中键滚轮就是放大缩小)。
|
||||
// 早先靠「deltaY 是 ±100 整数」猜设备来区分鼠标滚轮与触控板双指滑动,结果鼠标驱动
|
||||
// 一旦给小数步长(平滑滚动 / 高精度滚轮)就落进平移分支,表现成「滚轮拖图不放大」。
|
||||
// 现在只按主导轴分:水平滚动(含 Shift+滚轮,Chrome 会转成 deltaX)才平移。
|
||||
if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
|
||||
panX += event.deltaX
|
||||
applyView()
|
||||
return
|
||||
}
|
||||
if (!event.deltaY) return
|
||||
// 步长分两档:鼠标滚轮一格 ±100,触控板是细碎小数步 —— 后者要给更大增益才跟得上手
|
||||
const step = event.ctrlKey ? 0.01 : Math.abs(event.deltaY) >= 40 ? 0.0018 : 0.012
|
||||
zoomAt(event.clientX, event.clientY, Math.exp(-event.deltaY * step))
|
||||
}
|
||||
|
||||
function onPreviewPointerDown(event) {
|
||||
if (!els || !els.preview) return
|
||||
// 左键拖动 = 平移;中键拖动也平移(设计软件的肌肉记忆,顺手)
|
||||
if (event.button !== 0 && event.button !== 1) return
|
||||
if (event.target.closest('.vz-zoom')) return
|
||||
// 挡掉 img 原生拖拽与中键自动滚动(Windows 上会弹四向圆盘,手势直接断掉)
|
||||
event.preventDefault()
|
||||
drag = { x: event.clientX, y: event.clientY, panX: panX, panY: panY, id: event.pointerId }
|
||||
els.preview.classList.add('is-panning')
|
||||
try { els.preview.setPointerCapture(event.pointerId) } catch (e) { /* 没有 capture 也能拖,只是移出元素会断 */ }
|
||||
}
|
||||
|
||||
function onPreviewPointerMove(event) {
|
||||
if (!drag || !els || !els.preview || event.pointerId !== drag.id) return
|
||||
panX = drag.panX + (event.clientX - drag.x)
|
||||
panY = drag.panY + (event.clientY - drag.y)
|
||||
applyView()
|
||||
}
|
||||
|
||||
function onPreviewPointerUp(event) {
|
||||
if (!drag) return
|
||||
if (event && event.pointerId !== undefined && event.pointerId !== drag.id) return
|
||||
if (els && els.preview) {
|
||||
els.preview.classList.remove('is-panning')
|
||||
try { els.preview.releasePointerCapture(drag.id) } catch (e) { /* 已经释放过 */ }
|
||||
}
|
||||
drag = null
|
||||
}
|
||||
|
||||
function onPreviewDblClick(event) {
|
||||
if (event.target.closest('.vz-zoom')) return
|
||||
resetView()
|
||||
}
|
||||
|
||||
// ---------- 描摹 ----------
|
||||
|
||||
function retrace() {
|
||||
@@ -602,6 +716,13 @@ export function createVectorizer(options) {
|
||||
close()
|
||||
return
|
||||
}
|
||||
// 视图快捷键:0 复位、+/- 以中心缩放。在滑杆 / 数字框里打字时不抢键
|
||||
const keyTag = (event.target && event.target.tagName) || ''
|
||||
if (keyTag !== 'INPUT' && keyTag !== 'TEXTAREA' && keyTag !== 'SELECT') {
|
||||
if (event.key === '0') { event.preventDefault(); resetView(); return }
|
||||
if (event.key === '+' || event.key === '=') { event.preventDefault(); zoomAtCenter(1.25); return }
|
||||
if (event.key === '-' || event.key === '_') { event.preventDefault(); zoomAtCenter(0.8); return }
|
||||
}
|
||||
if (event.code === 'Space' && !spaceDown && !event.repeat) {
|
||||
const tag = (event.target && event.target.tagName) || ''
|
||||
if (tag === 'INPUT' || tag === 'TEXTAREA') return
|
||||
@@ -633,6 +754,11 @@ export function createVectorizer(options) {
|
||||
const node = root
|
||||
root = null
|
||||
els = null
|
||||
// 视图状态跟着会话走:下次打开从「等比铺满」开始
|
||||
zoom = 1
|
||||
panX = 0
|
||||
panY = 0
|
||||
drag = null
|
||||
node.remove()
|
||||
if (typeof onClose === 'function') onClose()
|
||||
}
|
||||
@@ -663,6 +789,8 @@ export function createVectorizer(options) {
|
||||
vector: root.querySelector('[data-stage="vector"]'),
|
||||
original: root.querySelector('[data-stage="original"]'),
|
||||
badge: root.querySelector('[data-badge]'),
|
||||
zoomChip: root.querySelector('[data-zoom-chip]'),
|
||||
zoomVal: root.querySelector('[data-zoom-val]'),
|
||||
status: root.querySelector('[data-status]'),
|
||||
statusText: root.querySelector('[data-status-text]'),
|
||||
meta: root.querySelector('[data-meta]'),
|
||||
@@ -672,6 +800,18 @@ export function createVectorizer(options) {
|
||||
els.panel.innerHTML = panelHTML(params, preset, outScale, advOpen)
|
||||
|
||||
root.addEventListener('click', onRootClick)
|
||||
// 预览视图手势:滚轮/捏合缩放、拖动平移、双击复位、点倍率胶囊复位
|
||||
els.preview.addEventListener('wheel', onPreviewWheel, { passive: false })
|
||||
els.preview.addEventListener('pointerdown', onPreviewPointerDown)
|
||||
els.preview.addEventListener('pointermove', onPreviewPointerMove)
|
||||
els.preview.addEventListener('pointerup', onPreviewPointerUp)
|
||||
els.preview.addEventListener('pointercancel', onPreviewPointerUp)
|
||||
// capture 被系统抢走(切窗口、拖出屏幕)时也要收尾,否则光标会一直卡在 grabbing
|
||||
els.preview.addEventListener('lostpointercapture', onPreviewPointerUp)
|
||||
els.preview.addEventListener('dblclick', onPreviewDblClick)
|
||||
els.preview.addEventListener('click', function (event) {
|
||||
if (event.target.closest('.vz-zoom')) resetView()
|
||||
})
|
||||
els.panel.addEventListener('input', onPanelInput)
|
||||
els.panel.addEventListener('click', onPanelClick)
|
||||
document.addEventListener('keydown', onKeyDown, true)
|
||||
@@ -680,6 +820,7 @@ export function createVectorizer(options) {
|
||||
|
||||
syncControls()
|
||||
setStats(null)
|
||||
resetView()
|
||||
retrace()
|
||||
return { close }
|
||||
}
|
||||
|
||||
+198
-21
@@ -6,11 +6,14 @@
|
||||
// ⚠️ 因此本文件的注释里不要写出那种字面量形态(会抢先匹配),要描述就直接说「id 字面量」。
|
||||
//
|
||||
// 版本占位符由构建脚本用 package.json 的 version 替换,保证两处永不漂移。
|
||||
// skin: 'private' = 自绘深色工具 UI(#1b1b22 系列),不跟随宿主主题。
|
||||
// 代价由宿主契约测试钉死:声明 private 的插件不得引用宿主颜色 var(--iwb-*),只能自洽。
|
||||
var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
id: 'image-vectorize',
|
||||
name: '位图转矢量',
|
||||
version: '0.3.1',
|
||||
version: '0.6.1',
|
||||
apiVersion: 1,
|
||||
skin: 'private',
|
||||
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
|
||||
settings: {
|
||||
preset: { type: 'string', default: 'text' },
|
||||
@@ -2023,15 +2026,15 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
.vz-modal {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 92vw;
|
||||
height: 88vh;
|
||||
min-width: 760px;
|
||||
min-height: 520px;
|
||||
max-width: 1680px;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
max-width: none;
|
||||
background: #1b1b22;
|
||||
border: 1px solid #33333f;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55);
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
@@ -2082,14 +2085,16 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
.vz-btn:hover { background: #34343f; border-color: #4a4a5c; }
|
||||
.vz-btn:active { background: #2f2f3a; }
|
||||
.vz-btn:disabled { opacity: 0.45; cursor: default; }
|
||||
|
||||
.vz-btn-primary {
|
||||
background: #1f7a52;
|
||||
border-color: #27875c;
|
||||
color: #eafff5;
|
||||
/* 顶栏「保存为节点 / 复制 SVG / 下载 SVG」三颗走上面这套灰色描边配色。
|
||||
「关闭」单独用编辑器主色调(.vz-seg 选中态同款 #33566f)填充,与产出操作区分、防误点。
|
||||
2026-11-19:原「取消」改名「关闭」并按主色调取色(行为不变,仍是 data-act="cancel" 退出编辑器)。 */
|
||||
.vz-btn-close {
|
||||
background: #33566f;
|
||||
border-color: #33566f;
|
||||
color: #eaf6ff;
|
||||
}
|
||||
.vz-btn-primary:hover { background: #248a5d; border-color: #2f9c69; }
|
||||
.vz-btn-primary:disabled { background: #24503e; border-color: #2a5c47; }
|
||||
.vz-btn-close:hover { background: #3d6480; border-color: #4a7394; }
|
||||
.vz-btn-close:active { background: #2c4a60; }
|
||||
|
||||
/* ---------- 主体 ---------- */
|
||||
.vz-body {
|
||||
@@ -2111,15 +2116,41 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
棋盘格既干扰判断形状,也让深色细笔画看起来发虚(实测用户第一反应是「糊」)。
|
||||
矢量 SVG 本身仍不含背景矩形,导出/复制到 Figma 依旧是透明底。 */
|
||||
background-color: #ffffff;
|
||||
/* 缩放 / 平移的**唯一真源**:矢量图与原图两张 img 共用这套变量,
|
||||
所以按住空格对比时,视图完全不动(各自存一份状态迟早会对不上)。
|
||||
量纲:zoom 无单位;pan 是**屏幕像素**(先 scale 后 translate,平移量不被缩放放大)。 */
|
||||
--vz-zoom: 1;
|
||||
--vz-pan-x: 0px;
|
||||
--vz-pan-y: 0px;
|
||||
cursor: grab;
|
||||
/* 触屏 / 触控板手势全部自己处理,别让浏览器抢去做页面滚动 */
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.vz-preview.is-panning { cursor: grabbing; }
|
||||
|
||||
/* 白底之上用一圈极淡的描边 + 细阴影标出画面边界:
|
||||
白底稿(如菜单/白底商品图)与预览区同色时,否则看不出图到哪里 */
|
||||
白底稿(如菜单/白底商品图)与预览区同色时,否则看不出图到哪里。
|
||||
绝对定位 + 50%/50% 是为了让 transform 的中心锚点稳定落在预览区正中(缩放锚点计算依赖这一点);
|
||||
max-* 用 calc(100% - 40px) 抵掉 .vz-preview 的 20px padding(百分比相对 padding box 算)。 */
|
||||
.vz-stage {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
max-width: calc(100% - 40px);
|
||||
max-height: calc(100% - 40px);
|
||||
display: block;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.16), 0 0 0 1px rgba(0, 0, 0, 0.07);
|
||||
transform:
|
||||
translate(-50%, -50%)
|
||||
translate(var(--vz-pan-x), var(--vz-pan-y))
|
||||
scale(var(--vz-zoom));
|
||||
transform-origin: 50% 50%;
|
||||
/* 拖动时每帧改 transform,提前提层,避免整块重绘掉帧(最多两张图,内存代价可忽略) */
|
||||
will-change: transform;
|
||||
/* 拖动时别触发 img 的原生拖拽(会拽出一个半透明缩略图,手势直接断掉) */
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
|
||||
.vz-stage[hidden] { display: none; }
|
||||
@@ -2155,6 +2186,32 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 缩放倍率:只有真的缩放过才出现(100% 时挂 hidden,不占视线)。
|
||||
它同时是「现在没在 1:1」的唯一视觉信号 —— 用户放大看细节后容易忘记自己还缩着。 */
|
||||
.vz-zoom {
|
||||
position: absolute;
|
||||
right: 14px;
|
||||
bottom: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 9px;
|
||||
border-radius: 6px;
|
||||
background: rgba(255, 255, 255, 0.94);
|
||||
border: 1px solid rgba(0, 0, 0, 0.12);
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
|
||||
color: #45454f;
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.vz-zoom[hidden] { display: none; }
|
||||
.vz-zoom b { font-weight: 600; }
|
||||
.vz-zoom span { color: #9a9aa8; }
|
||||
.vz-zoom:hover { border-color: rgba(0, 0, 0, 0.22); }
|
||||
.vz-zoom:hover span { color: #45454f; }
|
||||
|
||||
/* 描摹中/出错的浮层 */
|
||||
.vz-status {
|
||||
position: absolute;
|
||||
@@ -2473,7 +2530,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
|
||||
/* 窄屏:面板转到底部 */
|
||||
@media (max-width: 900px) {
|
||||
.vz-modal { width: 96vw; height: 92vh; min-width: 0; }
|
||||
.vz-modal { width: 100vw; height: 100vh; min-width: 0; }
|
||||
.vz-body { flex-direction: column; }
|
||||
.vz-panel { width: auto; max-height: 46%; border-left: 0; border-top: 1px solid #2e2e3a; }
|
||||
}
|
||||
@@ -2970,7 +3027,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
}).join("") + '</div></div><div class="vz-row vz-row-switch"><div class="vz-row-text">按孤岛拆分<span>每个连通块一个图层,粘到 Figma 可单独选中;笔画不连的汉字会分成几块</span></div><label class="vz-switch"><input type="checkbox" data-check="splitIslands"' + (params.splitIslands ? " checked" : "") + '><i></i></label></div></div><div class="vz-group"><div class="vz-stats"><span><b data-stat="elements">–</b> 元素</span><span><b data-stat="levels">–</b> 层</span><span><b data-stat="bytes">–</b></span><span><b data-stat="ms">–</b></span></div></div><div class="vz-group"><button type="button" class="vz-adv-toggle" data-act="adv" aria-expanded="' + (advOpen ? "true" : "false") + '">高级参数<span data-adv-caret>' + (advOpen ? "▴" : "▾") + '</span></button><div class="vz-adv" data-adv' + (advOpen ? "" : " hidden") + '><div class="vz-row"><div class="vz-row-label">阈值<span>自动按直方图取,手动可救极端图</span></div><div class="vz-seg" data-seg-group="thrMode"><button type="button" data-seg="thrMode" data-value="auto">自动</button><button type="button" data-seg="thrMode" data-value="manual">手动</button></div></div><div data-thr-row hidden>' + rangeHTML("threshold", "阈值取值", 0, 255, 1, params.threshold >= 0 ? params.threshold : 128, "") + '</div><div class="vz-row"><div class="vz-row-label">反相<span>黑底白字时打开</span></div><div class="vz-seg" data-seg-group="invert">' + segHTML("invert", [["0", "正片"], ["1", "负片"]], params.invert ? 1 : 0) + '</div></div><div class="vz-row"><div class="vz-row-label">填充 / 背景<span>填充仅「纯单色」生效 · 背景作预览底</span></div><div class="vz-swatches"><input type="color" class="vz-color" data-color="color" value="' + esc(params.color) + '" title="填充色(纯单色生效)"><input type="color" class="vz-color" data-color="bg" value="' + esc(params.bg) + '" title="背景色(预览底;勾「带底」写入导出)"><label class="vz-mini" title="导出 / 复制时把背景色一起写进 SVG(默认不带,粘到 Figma 是透明底)"><input type="checkbox" data-check="bgExport"' + (params.bgExport ? " checked" : "") + "><span>带底</span></label></div></div></div></div>";
|
||||
}
|
||||
function viewHTML(name) {
|
||||
return '<div class="vz-root"><div class="vz-modal" role="dialog" aria-modal="true" aria-label="位图转矢量"><header class="vz-header"><span class="vz-title">位图转矢量<em data-meta>' + esc(name) + '</em></span><div class="vz-spacer"></div><button type="button" class="vz-btn" data-act="cancel">取消</button><button type="button" class="vz-btn" data-act="copy">复制 SVG</button><button type="button" class="vz-btn" data-act="svg">下载 SVG</button><button type="button" class="vz-btn vz-btn-primary" data-act="save">保存为节点</button></header><div class="vz-body"><div class="vz-preview"><img class="vz-stage" data-stage="vector" alt="矢量预览"><img class="vz-stage" data-stage="original" alt="原图" hidden><div class="vz-badge" data-badge>矢量预览</div><div class="vz-status" data-status hidden><i class="vz-dot"></i><span data-status-text></span></div><div class="vz-hint">空格 对比原图 · 「复制 SVG」可直接粘到 Figma</div></div><aside class="vz-panel" data-panel></aside></div></div></div>';
|
||||
return '<div class="vz-root"><div class="vz-modal" role="dialog" aria-modal="true" aria-label="位图转矢量"><header class="vz-header"><span class="vz-title">位图转矢量<em data-meta>' + esc(name) + '</em></span><div class="vz-spacer"></div><button type="button" class="vz-btn" data-act="save">保存为节点</button><button type="button" class="vz-btn" data-act="copy">复制 SVG</button><button type="button" class="vz-btn" data-act="svg">下载 SVG</button><button type="button" class="vz-btn vz-btn-close" data-act="cancel">关闭</button></header><div class="vz-body"><div class="vz-preview" data-preview><img class="vz-stage" data-stage="vector" alt="矢量预览" draggable="false"><img class="vz-stage" data-stage="original" alt="原图" draggable="false" hidden><div class="vz-badge" data-badge>矢量预览</div><div class="vz-status" data-status hidden><i class="vz-dot"></i><span data-status-text></span></div><div class="vz-hint">空格 对比原图 · 滚轮缩放 · 拖动平移 · 双击复位</div><div class="vz-zoom" data-zoom-chip hidden title="点击回到 100%"><b data-zoom-val>100%</b><span>复位</span></div></div><aside class="vz-panel" data-panel></aside></div></div></div>';
|
||||
}
|
||||
var ALPHA_TONE = { hard: 0.4, normal: 1, round: 1.2 };
|
||||
var toneOf = (alphaMax) => alphaMax <= 0.6 ? "hard" : alphaMax >= 1.1 ? "round" : "normal";
|
||||
@@ -2994,6 +3051,10 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
let seq = 0;
|
||||
let debounceTimer = 0;
|
||||
let spaceDown = false;
|
||||
let zoom = 1;
|
||||
let panX = 0;
|
||||
let panY = 0;
|
||||
let drag = null;
|
||||
function readSettings() {
|
||||
const out = {};
|
||||
if (!settings || typeof settings.get !== "function") return out;
|
||||
@@ -3138,6 +3199,87 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
els.original.hidden = !spaceDown;
|
||||
els.badge.textContent = spaceDown ? "原图" : "矢量预览";
|
||||
}
|
||||
const ZOOM_MIN = 0.2;
|
||||
const ZOOM_MAX = 8;
|
||||
function applyView() {
|
||||
if (!els || !els.preview) return;
|
||||
els.preview.style.setProperty("--vz-zoom", String(zoom));
|
||||
els.preview.style.setProperty("--vz-pan-x", panX + "px");
|
||||
els.preview.style.setProperty("--vz-pan-y", panY + "px");
|
||||
const changed = zoom !== 1 || panX !== 0 || panY !== 0;
|
||||
if (els.zoomVal) els.zoomVal.textContent = Math.round(zoom * 100) + "%";
|
||||
if (els.zoomChip) els.zoomChip.hidden = !changed;
|
||||
}
|
||||
function resetView() {
|
||||
zoom = 1;
|
||||
panX = 0;
|
||||
panY = 0;
|
||||
drag = null;
|
||||
if (els && els.preview) els.preview.classList.remove("is-panning");
|
||||
applyView();
|
||||
}
|
||||
function zoomAt(clientX, clientY, factor) {
|
||||
if (!els || !els.preview) return;
|
||||
const next = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, zoom * factor));
|
||||
if (Math.abs(next - zoom) < 1e-4) return;
|
||||
const rect = els.preview.getBoundingClientRect();
|
||||
const dx = (clientX - (rect.left + rect.width / 2) - panX) / zoom;
|
||||
const dy = (clientY - (rect.top + rect.height / 2) - panY) / zoom;
|
||||
panX -= dx * (next - zoom);
|
||||
panY -= dy * (next - zoom);
|
||||
zoom = next;
|
||||
applyView();
|
||||
}
|
||||
function zoomAtCenter(factor) {
|
||||
if (!els || !els.preview) return;
|
||||
const rect = els.preview.getBoundingClientRect();
|
||||
zoomAt(rect.left + rect.width / 2, rect.top + rect.height / 2, factor);
|
||||
}
|
||||
function onPreviewWheel(event) {
|
||||
event.preventDefault();
|
||||
if (Math.abs(event.deltaX) > Math.abs(event.deltaY)) {
|
||||
panX += event.deltaX;
|
||||
applyView();
|
||||
return;
|
||||
}
|
||||
if (!event.deltaY) return;
|
||||
const step = event.ctrlKey ? 0.01 : Math.abs(event.deltaY) >= 40 ? 18e-4 : 0.012;
|
||||
zoomAt(event.clientX, event.clientY, Math.exp(-event.deltaY * step));
|
||||
}
|
||||
function onPreviewPointerDown(event) {
|
||||
if (!els || !els.preview) return;
|
||||
if (event.button !== 0 && event.button !== 1) return;
|
||||
if (event.target.closest(".vz-zoom")) return;
|
||||
event.preventDefault();
|
||||
drag = { x: event.clientX, y: event.clientY, panX, panY, id: event.pointerId };
|
||||
els.preview.classList.add("is-panning");
|
||||
try {
|
||||
els.preview.setPointerCapture(event.pointerId);
|
||||
} catch (e) {
|
||||
}
|
||||
}
|
||||
function onPreviewPointerMove(event) {
|
||||
if (!drag || !els || !els.preview || event.pointerId !== drag.id) return;
|
||||
panX = drag.panX + (event.clientX - drag.x);
|
||||
panY = drag.panY + (event.clientY - drag.y);
|
||||
applyView();
|
||||
}
|
||||
function onPreviewPointerUp(event) {
|
||||
if (!drag) return;
|
||||
if (event && event.pointerId !== void 0 && event.pointerId !== drag.id) return;
|
||||
if (els && els.preview) {
|
||||
els.preview.classList.remove("is-panning");
|
||||
try {
|
||||
els.preview.releasePointerCapture(drag.id);
|
||||
} catch (e) {
|
||||
}
|
||||
}
|
||||
drag = null;
|
||||
}
|
||||
function onPreviewDblClick(event) {
|
||||
if (event.target.closest(".vz-zoom")) return;
|
||||
resetView();
|
||||
}
|
||||
function retrace() {
|
||||
if (!source) return;
|
||||
const ticket = ++seq;
|
||||
@@ -3409,6 +3551,24 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
const keyTag = event.target && event.target.tagName || "";
|
||||
if (keyTag !== "INPUT" && keyTag !== "TEXTAREA" && keyTag !== "SELECT") {
|
||||
if (event.key === "0") {
|
||||
event.preventDefault();
|
||||
resetView();
|
||||
return;
|
||||
}
|
||||
if (event.key === "+" || event.key === "=") {
|
||||
event.preventDefault();
|
||||
zoomAtCenter(1.25);
|
||||
return;
|
||||
}
|
||||
if (event.key === "-" || event.key === "_") {
|
||||
event.preventDefault();
|
||||
zoomAtCenter(0.8);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (event.code === "Space" && !spaceDown && !event.repeat) {
|
||||
const tag = event.target && event.target.tagName || "";
|
||||
if (tag === "INPUT" || tag === "TEXTAREA") return;
|
||||
@@ -3440,6 +3600,10 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
const node = root;
|
||||
root = null;
|
||||
els = null;
|
||||
zoom = 1;
|
||||
panX = 0;
|
||||
panY = 0;
|
||||
drag = null;
|
||||
node.remove();
|
||||
if (typeof onClose === "function") onClose();
|
||||
}
|
||||
@@ -3465,6 +3629,8 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
vector: root.querySelector('[data-stage="vector"]'),
|
||||
original: root.querySelector('[data-stage="original"]'),
|
||||
badge: root.querySelector("[data-badge]"),
|
||||
zoomChip: root.querySelector("[data-zoom-chip]"),
|
||||
zoomVal: root.querySelector("[data-zoom-val]"),
|
||||
status: root.querySelector("[data-status]"),
|
||||
statusText: root.querySelector("[data-status-text]"),
|
||||
meta: root.querySelector("[data-meta]")
|
||||
@@ -3473,6 +3639,16 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
els.meta.textContent = name + " · " + source.srcW + "×" + source.srcH;
|
||||
els.panel.innerHTML = panelHTML(params, preset, outScale, advOpen);
|
||||
root.addEventListener("click", onRootClick);
|
||||
els.preview.addEventListener("wheel", onPreviewWheel, { passive: false });
|
||||
els.preview.addEventListener("pointerdown", onPreviewPointerDown);
|
||||
els.preview.addEventListener("pointermove", onPreviewPointerMove);
|
||||
els.preview.addEventListener("pointerup", onPreviewPointerUp);
|
||||
els.preview.addEventListener("pointercancel", onPreviewPointerUp);
|
||||
els.preview.addEventListener("lostpointercapture", onPreviewPointerUp);
|
||||
els.preview.addEventListener("dblclick", onPreviewDblClick);
|
||||
els.preview.addEventListener("click", function(event) {
|
||||
if (event.target.closest(".vz-zoom")) resetView();
|
||||
});
|
||||
els.panel.addEventListener("input", onPanelInput);
|
||||
els.panel.addEventListener("click", onPanelClick);
|
||||
document.addEventListener("keydown", onKeyDown, true);
|
||||
@@ -3480,6 +3656,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
window.addEventListener("blur", onBlur);
|
||||
syncControls();
|
||||
setStats(null);
|
||||
resetView();
|
||||
retrace();
|
||||
return { close };
|
||||
}
|
||||
|
||||
@@ -139,6 +139,15 @@ check('样式注入生效(CSP unsafe-inline)', await page.evaluate(() => {
|
||||
return Boolean(s && s.textContent.indexOf('.vz-') >= 0)
|
||||
}))
|
||||
|
||||
// 用户 2026-11-09:取消与保存为节点互换,四颗按钮同一套描边配色(绿色主按钮已去掉)。
|
||||
// 这条同时是「线上真的是新版」的活体证据 —— 光看版本号挡不住产物没重建。
|
||||
check('顶栏顺序 保存为节点→复制→下载→取消,四颗同色', await page.evaluate(() => {
|
||||
const btns = [...document.querySelectorAll('.vz-header .vz-btn')]
|
||||
if (btns.map((b) => b.dataset.act).join(',') !== 'save,copy,svg,cancel') return false
|
||||
const colors = new Set(btns.map((b) => getComputedStyle(b).backgroundColor + '|' + getComputedStyle(b).color))
|
||||
return colors.size === 1
|
||||
}))
|
||||
|
||||
// ---------- 5) 真站 CSP 下引擎能跑 ----------
|
||||
const paths = await poll(async () => {
|
||||
// 统计项是「元素」,合并模式下会带后缀「(N 孤岛合并)」,只取前面的数字
|
||||
@@ -184,6 +193,45 @@ check('「填充 / 背景」两个色块并排在同一行', await page.evaluate
|
||||
return Math.abs(ra.top - rb.top) < 2 && rb.left > ra.right - 1
|
||||
}))
|
||||
|
||||
// v0.4.0:预览缩放 / 平移(真站上鼠标手势得真能走通,不能只信本地合成宿主)
|
||||
const pvBox = await page.locator('.vz-preview').boundingBox()
|
||||
await page.mouse.move(pvBox.x + pvBox.width / 2 + 40, pvBox.y + pvBox.height / 2 - 20)
|
||||
await page.mouse.wheel(0, -300)
|
||||
await sleep(220)
|
||||
// 断言「换算比例」而不是「比容器大」:正方形图 fit 进宽屏预览后本来就比容器窄,
|
||||
// 拿 rect.width > clientWidth 会比较,放大了也可能不成立(实测真站 549 vs 1011)
|
||||
check('滚轮放大预览、倍率胶囊出现', await page.evaluate(() => {
|
||||
const p = document.querySelector('.vz-preview')
|
||||
const v = document.querySelector('[data-stage="vector"]')
|
||||
const z = Number(p.style.getPropertyValue('--vz-zoom') || 1)
|
||||
const chip = document.querySelector('[data-zoom-chip]')
|
||||
const ratio = v.getBoundingClientRect().width / v.clientWidth
|
||||
return z > 1.1 && Boolean(chip) && !chip.hidden && Math.abs(ratio - z) < 0.02
|
||||
}))
|
||||
await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2)
|
||||
await sleep(220)
|
||||
check('双击复位回 100%', await page.evaluate(() => {
|
||||
const p = document.querySelector('.vz-preview')
|
||||
return Number(p.style.getPropertyValue('--vz-zoom') || 1) === 1
|
||||
}))
|
||||
|
||||
// 回归:平滑滚轮(小数 deltaY)在真站也必须缩放。旧逻辑靠整数步长识别鼠标,会把这类滚轮当平移。
|
||||
await page.evaluate(() => {
|
||||
const p = document.querySelector('.vz-preview')
|
||||
const r = p.getBoundingClientRect()
|
||||
p.dispatchEvent(new WheelEvent('wheel', {
|
||||
deltaY: -12.5, deltaMode: 0, bubbles: true, cancelable: true,
|
||||
clientX: r.left + r.width / 2, clientY: r.top + r.height / 2,
|
||||
}))
|
||||
})
|
||||
await sleep(160)
|
||||
check('真站:小数步长滚轮照样放大', await page.evaluate(() => {
|
||||
const p = document.querySelector('.vz-preview')
|
||||
return Number(p.style.getPropertyValue('--vz-zoom') || 1) > 1.001
|
||||
}))
|
||||
await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2)
|
||||
await sleep(160)
|
||||
|
||||
// ---------- 5.6) 复制到剪贴板(真写,读回校验口味) ----------
|
||||
await page.locator('[data-act="copy"]').click()
|
||||
await sleep(400)
|
||||
|
||||
@@ -153,6 +153,15 @@ check('模态打开:预览区 + 参数面板 + 四个动作按钮齐全', awai
|
||||
document.querySelector('[data-act="save"]') && document.querySelector('[data-act="svg"]') &&
|
||||
document.querySelector('[data-act="copy"]') && document.querySelector('[data-act="cancel"]'))))
|
||||
|
||||
// 用户 2026-11-09:顶栏「取消」与「保存为节点」互换(主操作在左、取消在最右),
|
||||
// 且不再给主操作上绿色 —— 四颗按钮用同一套描边配色。
|
||||
check('顶栏顺序:保存为节点 → 复制 → 下载 → 取消,且四颗同色', await page.evaluate(() => {
|
||||
const btns = [...document.querySelectorAll('.vz-header .vz-btn')]
|
||||
if (btns.map((b) => b.dataset.act).join(',') !== 'save,copy,svg,cancel') return false
|
||||
const colors = new Set(btns.map((b) => getComputedStyle(b).backgroundColor + '|' + getComputedStyle(b).color))
|
||||
return colors.size === 1
|
||||
}))
|
||||
|
||||
// 高级参数默认展开:用户 2026-11-05 明确要求「不用隐藏」(低频项也一眼能看到)
|
||||
check('高级参数默认展开', await page.evaluate(() => {
|
||||
const box = document.querySelector('[data-adv]')
|
||||
@@ -186,6 +195,87 @@ check('预览区白底、无棋盘格', await page.evaluate(() => {
|
||||
return lum > 240 && cs.backgroundImage === 'none'
|
||||
}))
|
||||
|
||||
// ---------- 预览视图:缩放 / 平移(2026-11-09 用户需求) ----------
|
||||
const viewState = () => page.evaluate(() => {
|
||||
const p = document.querySelector('[data-preview]')
|
||||
return {
|
||||
zoom: Number(p.style.getPropertyValue('--vz-zoom') || 1),
|
||||
panX: parseFloat(p.style.getPropertyValue('--vz-pan-x') || '0'),
|
||||
panY: parseFloat(p.style.getPropertyValue('--vz-pan-y') || '0'),
|
||||
chip: !document.querySelector('[data-zoom-chip]').hidden,
|
||||
label: document.querySelector('[data-zoom-val]').textContent,
|
||||
}
|
||||
})
|
||||
const fit = await viewState()
|
||||
check('默认等比铺满(100%),倍率胶囊不出现', fit.zoom === 1 && fit.panX === 0 && fit.panY === 0 && !fit.chip)
|
||||
|
||||
const pv = await page.locator('[data-preview]').boundingBox()
|
||||
const cx = pv.x + pv.width / 2
|
||||
const cy = pv.y + pv.height / 2
|
||||
// 鼠标刻意偏离中心,用来验证「以光标为锚点」而不是「以中心缩放」
|
||||
await page.mouse.move(cx + 60, cy - 40)
|
||||
await page.mouse.wheel(0, -300)
|
||||
await sleep(140)
|
||||
const zoomed = await viewState()
|
||||
check('滚轮向上放大', zoomed.zoom > 1.1 && zoomed.chip, 'zoom=' + zoomed.zoom)
|
||||
check('缩放锚在光标处(偏离中心缩放会带动平移)',
|
||||
Math.abs(zoomed.panX) > 1 || Math.abs(zoomed.panY) > 1,
|
||||
'pan=' + zoomed.panX.toFixed(1) + ',' + zoomed.panY.toFixed(1))
|
||||
check('倍率胶囊显示当前百分比', /^\d+%$/.test(zoomed.label) && zoomed.label !== '100%', zoomed.label)
|
||||
|
||||
await page.mouse.move(cx, cy)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(cx + 50, cy + 30, { steps: 6 })
|
||||
await page.mouse.up()
|
||||
await sleep(140)
|
||||
const panned = await viewState()
|
||||
check('拖动平移(位移跟手,1:1 不缩放)',
|
||||
Math.abs(panned.panX - zoomed.panX - 50) < 3 && Math.abs(panned.panY - zoomed.panY - 30) < 3,
|
||||
'pan=' + panned.panX.toFixed(1) + ',' + panned.panY.toFixed(1))
|
||||
// 开发用:VZ_SHOT=/tmp/vz-zoom.png 出一张「放大 + 平移」状态的截图
|
||||
if (process.env.VZ_SHOT) await page.locator('.vz-modal').screenshot({ path: process.env.VZ_SHOT })
|
||||
|
||||
await page.mouse.dblclick(cx, cy)
|
||||
await sleep(140)
|
||||
const reset = await viewState()
|
||||
check('双击复位回 100% 且胶囊消失',
|
||||
reset.zoom === 1 && reset.panX === 0 && reset.panY === 0 && !reset.chip)
|
||||
|
||||
// 回归:滚轮必须无条件缩放。早先靠「deltaY 是 ±100 整数」识别鼠标滚轮,
|
||||
// 平滑滚动/高精度滚轮给小数步长时会被判成触控板滑动 → 退化成平移,用户看到「滚轮不放大」。
|
||||
const wheelBy = (deltaY, deltaX) => page.evaluate(([dy, dx]) => {
|
||||
const p = document.querySelector('[data-preview]')
|
||||
const r = p.getBoundingClientRect()
|
||||
p.dispatchEvent(new WheelEvent('wheel', {
|
||||
deltaY: dy, deltaX: dx, deltaMode: 0, bubbles: true, cancelable: true,
|
||||
clientX: r.left + r.width / 2, clientY: r.top + r.height / 2,
|
||||
}))
|
||||
}, [deltaY, deltaX])
|
||||
await wheelBy(-12.5, 0) // 小数步长 = 平滑滚轮 / 触控板
|
||||
await sleep(90)
|
||||
const smooth = await viewState()
|
||||
check('滚轮给小数步长也缩放(不被误判成触控板滑动)', smooth.zoom > 1.001, 'zoom=' + smooth.zoom)
|
||||
await wheelBy(0, -60) // 纯水平滚动(Shift+滚轮在 Chrome 里就是这种)
|
||||
await sleep(90)
|
||||
const horiz = await viewState()
|
||||
check('水平滚动只平移、不改倍率', horiz.zoom === smooth.zoom && Math.abs(horiz.panX - smooth.panX) > 20,
|
||||
'panX=' + horiz.panX.toFixed(1))
|
||||
|
||||
await page.mouse.dblclick(cx, cy)
|
||||
await sleep(120)
|
||||
await page.mouse.move(cx, cy)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(cx + 40, cy + 20, { steps: 5 })
|
||||
await page.mouse.up()
|
||||
await sleep(90)
|
||||
const dragAt1x = await viewState()
|
||||
check('100% 状态左键也能拖图(不要求先放大)',
|
||||
dragAt1x.zoom === 1 && Math.abs(dragAt1x.panX - 40) < 3 && Math.abs(dragAt1x.panY - 20) < 3,
|
||||
'pan=' + dragAt1x.panX.toFixed(1) + ',' + dragAt1x.panY.toFixed(1))
|
||||
|
||||
await page.mouse.dblclick(cx, cy)
|
||||
await sleep(120)
|
||||
|
||||
const monoPaths = Number(await pathsNow(page))
|
||||
const monoMs = Number((await page.locator('[data-stat="ms"]').textContent()).replace(/[^\d]/g, ''))
|
||||
check('单色描摹产出元素(文字图形都在)', monoPaths >= 1 && monoPaths <= 80, 'elements=' + monoPaths)
|
||||
@@ -335,8 +425,9 @@ await page.evaluate(() => {
|
||||
})
|
||||
await sleep(400)
|
||||
check('改单色填充色写进 SVG', await page.evaluate(() => /#c0392b/i.test(window.__lastSvg || '')), '')
|
||||
// 开发用:VZ_SHOT=/tmp/vz-panel.png 出一张面板截图(验证「填充 / 背景」这排没挤坏布局)
|
||||
if (process.env.VZ_SHOT) await page.locator('.vz-modal').screenshot({ path: process.env.VZ_SHOT })
|
||||
// 开发用:VZ_SHOT_PANEL=/tmp/vz-panel.png 出一张面板截图(验证「填充 / 背景」这排没挤坏布局)
|
||||
// ⚠️ 别和上面的 VZ_SHOT 共用同一个变量 —— 两处都写同一路径时,后一张会把前一张覆盖掉
|
||||
if (process.env.VZ_SHOT_PANEL) await page.locator('.vz-modal').screenshot({ path: process.env.VZ_SHOT_PANEL })
|
||||
|
||||
// ---------- 背景色 / 带底(v0.3.1) ----------
|
||||
const setBg = async (hex) => {
|
||||
@@ -432,6 +523,14 @@ check('重新打开沿用上次参数(mode=mono、颜色 #c0392b)', await pa
|
||||
}))
|
||||
|
||||
// ---------- 空格对比 / Esc ----------
|
||||
// 先缩放到非 1x:验证「按住空格切原图时视图不跳」—— 两张 img 共用同一套变量才做得到。
|
||||
// 注意不能拿 vector 的 computed transform 跟 original 比:display:none 的元素 compute 出来是 none。
|
||||
const pv2 = await page.locator('[data-preview]').boundingBox()
|
||||
await page.mouse.move(pv2.x + pv2.width / 2, pv2.y + pv2.height / 2)
|
||||
await page.mouse.wheel(0, -300)
|
||||
await sleep(150)
|
||||
const viewBefore = await page.evaluate(() =>
|
||||
getComputedStyle(document.querySelector('[data-stage="vector"]')).transform)
|
||||
await page.evaluate(() => document.body.focus())
|
||||
await page.keyboard.down('Space')
|
||||
await sleep(150)
|
||||
@@ -439,6 +538,16 @@ check('按住空格对比原图', await page.evaluate(() => {
|
||||
const o = document.querySelector('[data-stage="original"]')
|
||||
return Boolean(o && !o.hidden)
|
||||
}))
|
||||
const spaceCmp = await page.evaluate(() => {
|
||||
const p = document.querySelector('[data-preview]')
|
||||
return {
|
||||
z: Number(p.style.getPropertyValue('--vz-zoom') || 1),
|
||||
t: getComputedStyle(document.querySelector('[data-stage="original"]')).transform,
|
||||
}
|
||||
})
|
||||
check('缩放状态下切原图,视图完全不跳(两图共用变量)',
|
||||
spaceCmp.z > 1 && spaceCmp.t === viewBefore,
|
||||
'zoom=' + spaceCmp.z.toFixed(2) + ' ' + spaceCmp.t + ' vs ' + viewBefore)
|
||||
await page.keyboard.up('Space')
|
||||
await sleep(120)
|
||||
check('松开空格回到矢量', await page.evaluate(() => {
|
||||
|
||||
+3
-1
@@ -5,7 +5,9 @@
|
||||
"description": "IWB 插件仓:只写插件,不复制宿主契约",
|
||||
"scripts": {
|
||||
"validate": "node scripts/validate.mjs",
|
||||
"build": "node scripts/build-plugin.mjs"
|
||||
"build": "node scripts/build-plugin.mjs",
|
||||
"test": "npm run validate && npm run test:album",
|
||||
"test:album": "node album/tools/harness.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "^0.24.2"
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# promptlib 样式基线(重要)
|
||||
|
||||
- 正确基线:**v1.8.8**(commit `178b36c`)
|
||||
- 当前 v1.8.17 的样式与 1.8.8 视觉一致,仅颜色做了 `var(--plp-cN, #原色)` 兜底包装
|
||||
- 禁止批量改写颜色 token / 重写 CSS 声明(曾导致文字不可见、灰块、伪类失效)
|
||||
- 插入变量:禁止在 blur 记录选区;用 `execCommand("insertText")` 在光标处插入
|
||||
- 改样式后必须截图核对再发市场
|
||||
|
||||
详细说明见桌面仓 `docs/standards/promptlib-style-baseline.md`。
|
||||
@@ -0,0 +1,47 @@
|
||||
# promptlib Token 迁移映射表(第一批:颜色)
|
||||
|
||||
> 依据:`image-workbench-desktop/docs/standards/design-tokens.md` 与 `plugin-theme.md`。
|
||||
> 原则:**视觉目标仍是 1.8.8 基线**;先迁颜色(语义明确),尺寸后续单独批次 + 截图 diff。
|
||||
|
||||
## 1. 颜色映射(已落地 1.8.22)
|
||||
|
||||
| 原值 | Token | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `#fff` / `#ffffff`(background) | `--iwb-plugin-card` | 卡片/弹窗内白底 |
|
||||
| `#fbfcfd` / `#fcfcfd` | `--iwb-field` | 输入框/编辑区底 |
|
||||
| `#fafafb` / `#fafbfc` | `--iwb-plugin-surface` | 面板根 |
|
||||
| `#f5f6f7` `#f3f4f7` `#f2f4f7` `#eef0f4` `#f4f5f7` `#f4f6f9` `#f1f3f5` | `--iwb-plugin-inset` | 内嵌/分组底 |
|
||||
| `#eef0f3` `#eef1f4` `#e9ecf1` `#e7e9ee` `#d7dbe2` | `--iwb-plugin-hover` | 悬停/次级块 |
|
||||
| `#d5d9e0` `#e3e5e9` `#e6e8ec` `#eceef2` `#e2e6ec` `#e8eaee` `#eef0f2` `#dfe3e9` `#f1f3f5` `#f3f5f8` `#eef0f3` | `--iwb-plugin-border` | 常规描边/分割线 |
|
||||
| `#b9bfca` `#c2c7cf` `#9aa3ad` | `--iwb-border2` | 强调描边 |
|
||||
| `#1d2129` `#1c2333` `#2f3540` `#3f4450` `#3a4048` `#33383f` | `--iwb-text` | 主文字 |
|
||||
| `#5b6472` `#4d5668` `#8b929c` `#8a919c` | `--iwb-text2` | 次要文字 |
|
||||
| `#9aa1ac` `#aab0ba` `#b3b9c2` `#c2c7cf` | `--iwb-text-dim` | 占位/弱说明 |
|
||||
| `#5a3fd0` `#5a4bd0` `#7c4dff` `#6b4dff` `#8b7ff0` | `--iwb-plp-accent` | 插件强调色(高饱和,允许自有) |
|
||||
| `#f1ecff` `#f4f0ff` | `--iwb-plp-accent-soft` | 强调色浅底 |
|
||||
| `#cfc3ff` `#d8cbff` `#d9d3ff` | `--iwb-plp-accent-border` | 强调色描边 |
|
||||
| `#d97706` | `--iwb-warn` | 警告 |
|
||||
| `#c0392b` | `--iwb-err` | 错误/删除 |
|
||||
|
||||
白色文字(压在封面/渐变上)保留 `#fff`,属内容色。
|
||||
|
||||
## 2. 尺寸迁移(已完成 1.8.23)
|
||||
|
||||
迁移结果:promptlib 散值清零(字号/圆角/间距全部落入闭集),棘轮基线已下调;视觉对比无换行/溢出。
|
||||
|
||||
| 类别 | 目标闭集 | 归并规则 |
|
||||
| --- | --- | --- |
|
||||
| 字号 | 11/12/13/14/15/17/20/24 | 10→11、10.5→11、11.5→12、12.5→13、13.5→14、16→15、18→17 |
|
||||
| 圆角 | 6/8/10/12/14/999 | 2/3/4→6、7/9→8、11→10、16→14 |
|
||||
| 间距 | 0/2/4/6/8/10/12/16/20/24/32/40/48/64 | 1→2、3→4、5→6、7→6、9→8、14→12、18→16 |
|
||||
|
||||
尺寸批次要求:亮/暗两套截图 diff + 逐项确认后再发布。
|
||||
|
||||
## 3. 复查命令
|
||||
|
||||
```bash
|
||||
node scripts/token-audit.js --plugins
|
||||
node tests/plugin-theme-contract-test.js
|
||||
node tests/plugin-scale-contract-test.js
|
||||
npm run test:visual
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "@iwb-plugin/promptlib",
|
||||
"private": true,
|
||||
"version": "1.13.0",
|
||||
"description": "提示词库:右栏提示词列表(搜索/分组/收藏/新建编辑/插入画布/复制/删除),数据由宿主 promptlib 能力提供",
|
||||
"ibwPlugin": {
|
||||
"id": "promptlib",
|
||||
"entry": "src/index.js",
|
||||
"apiVersion": 1
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,594 @@
|
||||
.iwb-promptlib, .iwb-plp-dialog, .iwb-plp-mask, .iwb-plp-dragghost, .iwb-plp-placebox{--iwb-plp-accent:#6b4dff;--iwb-plp-accent-soft:#f1ecff;--iwb-plp-accent-border:#d9d3ff}
|
||||
/* promptlib(提示词库)自带样式
|
||||
作用域全部带 .iwb-plp-*,不影响宿主与其他插件;样式随插件发布,不必等客户端发版。 */
|
||||
|
||||
/* 分组胶囊「适应面板宽度」自动换行。
|
||||
宿主的 .iwb-lib-chips 是 flex-wrap: nowrap(配 .iwb-lib-chips-scroll 做单行横向滚动 + 右侧渐隐),
|
||||
分组多时靠后的分类看不见也点不到。双类选择器提高优先级(不依赖样式注入顺序)。 */
|
||||
.iwb-lib-chips.iwb-plp-chips {
|
||||
flex-wrap: wrap;
|
||||
row-gap: 6px;
|
||||
}
|
||||
|
||||
/* + / ⚙ 是动作按钮,不是分组名:不参与压缩,并与最后一个分组稍作分隔 */
|
||||
.iwb-plp-chips .iwb-plp-add {
|
||||
flex: 0 0 auto;
|
||||
margin-left: 2px;
|
||||
}
|
||||
|
||||
/* v1.0.2(2026-11-21):卡片化 —— 白卡 + 悬停 + 文本三行截断。
|
||||
颜色一律走宿主 --iwb-plugin-* / --iwb-* token,不在插件里写死。 */
|
||||
.iwb-promptlib .iwb-pname { font-weight: 600; }
|
||||
.iwb-promptlib .iwb-ptext {
|
||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3;
|
||||
overflow: hidden; color: var(--iwb-text2, #4d5668);
|
||||
}
|
||||
.iwb-promptlib .iwb-lib-cards { gap: 8px; }
|
||||
|
||||
/* v1.1.0(2026-11-21):封面网格 + 长文详情 + 宽编辑弹窗。
|
||||
颜色全部走宿主 token,不写死。 */
|
||||
.iwb-plp-card {
|
||||
position: relative; border-radius: 10px; overflow: hidden; cursor: pointer;
|
||||
aspect-ratio: 1 / 1; border: 1px solid var(--iwb-border, #d5d9e0);
|
||||
transition: border-color .12s ease, transform .12s ease;
|
||||
}
|
||||
.iwb-plp-card:hover { border-color: var(--iwb-border2, #b9bfca); }
|
||||
.iwb-plp-cover { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.iwb-plp-t {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; padding: 16px 6px 6px;
|
||||
background: linear-gradient(to bottom, rgba(0,0,0,0), rgba(0,0,0,.66));
|
||||
color: var(--plp-c1, #fff); font-size: 11px; line-height: 1.35; max-height: 48%;
|
||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden;
|
||||
text-shadow: 0 1px 2px rgba(0,0,0,.35);
|
||||
}
|
||||
/* 详情:长文阅读 */
|
||||
.iwb-plp-dhead { display: flex; align-items: center; gap: 6px; padding: 2px 0 8px; position: sticky; top: 0; z-index: 2; background: var(--iwb-plugin-surface, #fafafb); }
|
||||
.iwb-plp-dtop { align-items: flex-start; gap: 10px; margin-bottom: 8px; }
|
||||
.iwb-plp-dthumb { flex: 0 0 84px; width: 84px; height: 84px; border-radius: 8px; overflow: hidden; border: 1px solid var(--iwb-border, #d5d9e0); }
|
||||
.iwb-plp-dmeta { min-width: 0; display: flex; flex-direction: column; gap: 4px; }
|
||||
.iwb-plp-dtitle { font-size: 13px; font-weight: 600; color: var(--iwb-text, #1c2333); line-height: 1.45; }
|
||||
.iwb-plp-dtext {
|
||||
font-size: 12px; line-height: 1.75; color: var(--iwb-text2, #4d5668);
|
||||
white-space: pre-wrap; word-break: break-word; padding: 4px 0 12px;
|
||||
}
|
||||
.iwb-plp-dfoot { display: flex; align-items: center; gap: 6px; padding: 8px 0 2px; position: sticky; bottom: 0; background: var(--iwb-plugin-surface, #fafafb); }
|
||||
/* 编辑弹窗:760 宽 + 大文本框 */
|
||||
.iwb-promptlib-editor { width: 760px; max-width: 94vw; }
|
||||
.iwb-promptlib-editor .iwb-modal-body { max-height: 78vh; }
|
||||
.iwb-promptlib-text { min-height: 360px; height: 44vh; font-size: 13px; line-height: 1.9; resize: vertical; }
|
||||
.iwb-plp-editor-cover { display: flex; gap: 12px; align-items: flex-start; margin-bottom: 10px; }
|
||||
.iwb-plp-editor-thumb { flex: 0 0 96px; width: 96px; height: 128px; border-radius: 8px; overflow: hidden; border: 1px solid var(--iwb-border, #d5d9e0); }
|
||||
.iwb-plp-editor-coverops { display: flex; flex-direction: column; gap: 8px; }
|
||||
|
||||
/* v1.2.0:可拖动 / 可缩放的详情与编辑弹窗(同宽 880×640,最小 640×420) */
|
||||
.iwb-plp-mask { background: transparent; display: block; }
|
||||
.iwb-plp-dialog { display: flex; flex-direction: column; overflow: hidden; border-radius: 14px;
|
||||
box-shadow: 0 24px 60px rgba(0,0,0,.28); }
|
||||
.iwb-plp-dhead { display: flex; align-items: center; gap: 6px; padding: 10px 12px;
|
||||
border-bottom: 1px solid var(--iwb-border, #d5d9e0); cursor: move; user-select: none; }
|
||||
.iwb-plp-grip { display: grid; grid-template-columns: repeat(3, 3px); gap: 2px; margin-right: 6px; }
|
||||
.iwb-plp-grip i { width: 3px; height: 3px; border-radius: 50%; background: var(--iwb-border2, #b9bfca); display: block; }
|
||||
.iwb-plp-dbody { flex: 1 1 auto; min-height: 0; display: flex; gap: 12px; padding: 12px; }
|
||||
.iwb-plp-dcov { flex: 0 0 210px; width: 210px; height: 280px; border-radius: 10px; overflow: hidden;
|
||||
border: 1px solid var(--iwb-border, #d5d9e0); background: var(--iwb-plugin-inset, #f5f6f7); }
|
||||
.iwb-plp-dright { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 8px; }
|
||||
.iwb-plp-dtext { flex: 1 1 auto; min-height: 0; overflow: auto; white-space: pre-wrap; word-break: break-word;
|
||||
font-size: 12px; line-height: 1.9; color: var(--iwb-text2, #4d5668); }
|
||||
.iwb-plp-dfooter { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 10px 12px;
|
||||
border-top: 1px solid var(--iwb-border, #d5d9e0); }
|
||||
.iwb-plp-resize { position: absolute; right: 0; bottom: 0; width: 18px; height: 18px; cursor: nwse-resize;
|
||||
background: linear-gradient(135deg, transparent 0 45%, var(--iwb-border2, #b9bfca) 45% 50%, transparent 50% 62%, var(--iwb-border2, #b9bfca) 62% 67%, transparent 67%); }
|
||||
/* 编辑:左栏固定 240,右栏大文本框 */
|
||||
.iwb-plp-eleft { flex: 0 0 240px; width: 240px; display: flex; flex-direction: column; gap: 8px; min-height: 0; }
|
||||
.iwb-plp-ecov { width: 240px; height: 300px; border-radius: 10px; overflow: hidden;
|
||||
border: 1px solid var(--iwb-border, #d5d9e0); background: var(--iwb-plugin-inset, #f5f6f7); }
|
||||
.iwb-plp-lrow { display: flex; flex-direction: column; gap: 4px; font-size: 11px; color: var(--iwb-text2, #4d5668); }
|
||||
.iwb-plp-etext { flex: 1 1 auto; min-height: 0; height: auto; resize: none; font-size: 12px; line-height: 1.9; }
|
||||
/* 输入框边框柔化(用户反馈现在的边框太深) */
|
||||
.iwb-plp-dialog .iwb-input { border-color: color-mix(in srgb, var(--iwb-border, #d5d9e0) 72%, transparent); }
|
||||
.iwb-plp-dialog .iwb-input:focus { border-color: var(--iwb-brand, #6b7280); box-shadow: 0 0 0 2px color-mix(in srgb, var(--iwb-brand, #6b7280) 14%, transparent); }
|
||||
|
||||
/* v1.2.1:去掉弹窗里多余的线框(用户反馈“线框太多、太明显”) */
|
||||
.iwb-plp-dialog .iwb-plp-dcov,
|
||||
.iwb-plp-dialog .iwb-plp-ecov { border-color: transparent; }
|
||||
.iwb-plp-dialog .iwb-plp-dhead { border-bottom-color: color-mix(in srgb, var(--iwb-border, #d5d9e0) 45%, transparent); }
|
||||
.iwb-plp-dialog .iwb-plp-dfooter { border-top-color: color-mix(in srgb, var(--iwb-border, #d5d9e0) 45%, transparent); }
|
||||
/* 输入框:默认无边框,用浅底区分;聚焦才出现细描边 */
|
||||
.iwb-plp-dialog .iwb-input {
|
||||
border-color: transparent;
|
||||
background: var(--iwb-plugin-inset, #f5f6f7);
|
||||
box-shadow: none;
|
||||
}
|
||||
.iwb-plp-dialog .iwb-input:hover { background: var(--iwb-plugin-hover, #eef1f4); }
|
||||
.iwb-plp-dialog .iwb-input:focus {
|
||||
background: var(--iwb-panel, #fff);
|
||||
border-color: color-mix(in srgb, var(--iwb-brand, #6b7280) 55%, transparent);
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--iwb-brand, #6b7280) 12%, transparent);
|
||||
}
|
||||
/* 正文编辑区:无边框、无底色,像一张纸 */
|
||||
.iwb-plp-dialog .iwb-plp-etext { border-color: transparent; background: transparent; box-shadow: none; }
|
||||
.iwb-plp-dialog .iwb-plp-etext:focus { border-color: transparent; box-shadow: none; background: transparent; }
|
||||
/* 左侧封面区的两个按钮:去掉按钮描边,弱化成文字按钮 */
|
||||
.iwb-plp-dialog .iwb-plp-eleft .iwb-btn { border-color: transparent; background: var(--iwb-plugin-inset, #f5f6f7); }
|
||||
.iwb-plp-dialog .iwb-plp-eleft .iwb-btn:hover { background: var(--iwb-plugin-hover, #eef1f4); }
|
||||
|
||||
/* v1.3.3:封面比例不定 —— 详情/编辑里完整显示(contain,不裁切);列表保持方形裁切(网格整齐) */
|
||||
.iwb-plp-dialog .iwb-plp-dcov img,
|
||||
.iwb-plp-dialog .iwb-plp-ecov img { object-fit: contain; background: var(--iwb-plugin-inset, #f5f6f7); }
|
||||
.iwb-plp-dialog .iwb-plp-dcov,
|
||||
.iwb-plp-dialog .iwb-plp-ecov { background: var(--iwb-plugin-inset, #f5f6f7); }
|
||||
.iwb-plp-card .iwb-plp-cover { object-fit: cover; object-position: center; }
|
||||
|
||||
/* v1.3.4:瀑布流(列式)+ 卡片定宽不随面板拉伸;面板底色统一走 --iwb-plugin-surface */
|
||||
.iwb-promptlib .iwb-plp-card {
|
||||
display: inline-block; width: 100%; margin: 0 0 8px;
|
||||
break-inside: avoid; -webkit-column-break-inside: avoid;
|
||||
aspect-ratio: auto; /* 高度交给图片原始比例 */
|
||||
}
|
||||
.iwb-promptlib .iwb-plp-cover { width: 100%; height: auto; object-fit: contain; }
|
||||
/* 统一插件灰:面板底(宿主会给 --iwb-plugin-surface,这里只留兜底) */
|
||||
.iwb-promptlib { background: transparent; }
|
||||
|
||||
/* v1.3.5:无封面的提示词也给一个方形占位(否则瀑布流里会塌成一条线) */
|
||||
.iwb-promptlib .iwb-plp-card.no-cover { aspect-ratio: 1 / 1; }
|
||||
.iwb-promptlib .iwb-plp-card.no-cover .iwb-plp-t { max-height: 60%; }
|
||||
|
||||
/* v1.4.7:恢复瀑布流列规则(1.4.0 清理 CSS 时把这组规则一起删掉了,列表退化成单列、卡片被拉满宽) */
|
||||
.iwb-promptlib .iwb-lib-cards { display: block; column-width: 122px; column-gap: 8px; grid-template-columns: none; }
|
||||
.iwb-promptlib .iwb-plp-card { display: inline-block; width: 100%; margin: 0 0 8px; break-inside: avoid; -webkit-column-break-inside: avoid; aspect-ratio: auto; }
|
||||
.iwb-promptlib .iwb-plp-cover { width: 100%; height: auto; object-fit: contain; }
|
||||
.iwb-promptlib .iwb-plp-card.no-cover { aspect-ratio: 1 / 1; }
|
||||
|
||||
/* v1.5.0:模板节点 + 变量标记 */
|
||||
.iwb-plp-vdot{position:absolute;right:8px;top:8px;width:7px;height:7px;border-radius:50%;background:var(--iwb-plp-accent, #7c4dff);box-shadow:0 0 0 2px var(--iwb-plp-dot-ring, rgba(255,255,255,.75))}
|
||||
.iwb-plp-node{display:flex;flex-direction:column;gap:6px;padding:8px 10px;font-size:12px;color:var(--iwb-text,#1c2333)}
|
||||
.iwb-plp-nhead{display:flex;align-items:center;gap:8px}
|
||||
.iwb-plp-nthumb{width:44px;height:44px;border-radius:8px;object-fit:cover;flex:0 0 auto}
|
||||
.iwb-plp-ntitle{font-weight:600;font-size: 13px;line-height:1.3;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
|
||||
.iwb-plp-nvars{display:flex;flex-direction:column;gap:4px}
|
||||
/* v1.12.1:标签列定宽(此前是 flex:0 0 auto,宽度跟着名称长短变 ⇒ 每个变量输入框左边缘错位)。
|
||||
v1.13.0:用户要求按 4 字定宽 ⇒ 56px(12px 字号 × 4 + 8px 余量)。超过 4 字的名称省略号截断,完整名称在 title 里。 */
|
||||
.iwb-plp-nrow{display:flex;align-items:flex-start;gap:6px;min-height:26px}
|
||||
.iwb-plp-nk{flex:0 0 56px;width:56px;max-width:56px;padding-top:4px;color:var(--iwb-text2,#5b6472);font-size: 12px;line-height:1.35;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.iwb-plp-nin{flex:1 1 auto;min-width:0;height:auto;min-height:24px;padding:2px 8px;line-height:1.5;font-size: 12px;resize:none;overflow-y:hidden}
|
||||
.iwb-plp-nref{display:flex;align-items:center;gap:6px;font-size: 12px;color:var(--iwb-text2,#5b6472);border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px}
|
||||
.iwb-plp-nref em{font-style:normal;color:var(--iwb-text2,#8b929c)}
|
||||
.iwb-plp-nprev{margin-top:2px;border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px;color:var(--iwb-text2,#5b6472);font-size: 12px;line-height:1.6;max-height:88px;overflow:hidden}
|
||||
|
||||
/* v1.5.0:变量编辑器 / 详情变量 */
|
||||
.iwb-plp-emid{flex:1;min-width:0;display:flex;flex-direction:column;gap:8px}
|
||||
.iwb-plp-vars{border:1px solid var(--iwb-border,#e3e5e9);border-radius:10px;padding:8px 10px;display:flex;flex-direction:column;gap:6px;background:var(--iwb-plugin-surface,#fff)}
|
||||
.iwb-plp-vhead{display:flex;align-items:center;gap:8px;font-size: 12px;color:var(--iwb-text2,#5b6472)}
|
||||
.iwb-plp-vchips{display:flex;flex-wrap:wrap;gap:6px}
|
||||
.iwb-plp-vchip{display:inline-flex;align-items:center;gap:4px;padding: 2px 6px;border-radius:6px;background:color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 10%, transparent);color:var(--iwb-plp-accent, #5a4bd0);font-size: 12px}
|
||||
.iwb-plp-vx{font-style:normal;cursor:pointer;color:var(--iwb-plp-accent, #8b7ff0);font-weight:700}
|
||||
.iwb-plp-vrows{display:flex;flex-direction:column;gap: 6px}
|
||||
.iwb-plp-vrow{display:flex;align-items:center;gap:8px}
|
||||
.iwb-plp-vk{width:92px;flex:0 0 92px;font-size: 12px;color:var(--iwb-text2,#5b6472);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.iwb-plp-vin{flex:1;height:26px;font-size: 12px}
|
||||
.iwb-plp-vprev{margin-top:2px;border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px;font-size: 12px;line-height:1.6;color:var(--iwb-text2,#5b6472);max-height:72px;overflow:auto;white-space:pre-wrap}
|
||||
.iwb-plp-dvars{display:flex;flex-direction:column;gap: 6px;border:1px solid var(--iwb-border,#e3e5e9);border-radius:10px;padding:8px 10px}
|
||||
|
||||
/* v1.5.6:模板节点参照风格节点 —— 封面 + 名称 + 变量,正文不再铺开 */
|
||||
.iwb-plp-nthumb{width:56px;height:56px;border-radius:8px;object-fit:cover;flex:0 0 auto}
|
||||
.iwb-plp-ntitlebox{min-width:0;display:flex;flex-direction:column;gap:2px}
|
||||
.iwb-plp-ntitle{font-weight:600;font-size: 13px;line-height:1.3;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
|
||||
.iwb-plp-nmeta{font-size: 11px;color:var(--iwb-text2,#8b929c)}
|
||||
.iwb-plp-nempty{font-size:11px;color:var(--iwb-text2,#8b929c);padding:2px 0}
|
||||
.iwb-plp-nwarn{font-size:11px;line-height:1.5;color:var(--iwb-warn,#d97706)}
|
||||
|
||||
/* v1.5.10:设置页 */
|
||||
.iwb-plp-settings{display:flex;flex-direction:column;gap: 16px}
|
||||
/* 2026-11-24:插件设置页跟随宿主的设置分组 token(不再自画卡片,避免卡片套卡片) */
|
||||
.iwb-plp-ssec{border:0;border-top:1px solid var(--iwb-set-divider,var(--iwb-border,#e3e5e9));border-radius:0;padding:var(--iwb-space-12) 0 0;display:flex;flex-direction:column;gap:var(--iwb-space-8)}
|
||||
.iwb-plp-ssec:first-child{border-top:0;padding-top:0}
|
||||
.iwb-plp-stitle{font-weight:600;font-size:var(--iwb-font-md,13px);color:var(--iwb-text,#2a2f36)}
|
||||
.iwb-plp-sgroups{display:flex;flex-direction:column;border:1px solid var(--iwb-set-input-border,var(--iwb-border,#eef0f2));border-radius:var(--iwb-radius-card,10px);overflow:hidden}
|
||||
.iwb-plp-sgrow{display:flex;align-items:center;gap:8px;padding: 6px 10px;border-top:1px solid var(--iwb-border,#f1f3f5)}
|
||||
.iwb-plp-sgrow:first-child{border-top:0}
|
||||
.iwb-plp-sgrip{width:12px;height:12px;background:radial-gradient(var(--iwb-text2,#c2c7cf) 1px,transparent 1px);background-size:4px 4px;border-radius: 6px;flex:0 0 auto}
|
||||
.iwb-plp-sgname{width:170px;height:26px;font-size:12px}
|
||||
.iwb-plp-sgcount{font-size: 12px;color:var(--iwb-text2,#8b929c);width:56px}
|
||||
.iwb-plp-sadd{display:flex;gap:8px;align-items:center}
|
||||
.iwb-plp-sbtns{display:flex;gap:8px;align-items:center}
|
||||
.iwb-plp-sopt{display:flex;gap:8px;align-items:center;font-size:12px;color:var(--iwb-text2,#4d5668)}
|
||||
.iwb-plp-settings{max-height:calc(100vh - 230px);overflow:auto;padding-right:4px}
|
||||
|
||||
/* v1.6.2:正文上方工具行 */
|
||||
.iwb-plp-etool{display:flex;align-items:center;gap:8px}
|
||||
/* v1.13.0:中列变窄时按钮文字会被挤成「+ 插入变 / 量」,按钮不参与收缩,让右边的灰字提示去换行 */
|
||||
.iwb-plp-insvar{flex:0 0 auto;white-space:nowrap}
|
||||
.iwb-plp-insvar{border:1px solid var(--iwb-plp-accent,#d9d3ff);background:color-mix(in srgb,var(--iwb-plp-accent,#7c4dff) 8%,transparent);color:var(--iwb-plp-accent,#5a4bd0);font-weight:600}
|
||||
|
||||
/* v1.6.5:宿主基础样式的插件作用域副本 —— 宿主改全局样式不再影响插件 */
|
||||
.iwb-promptlib .iwb-grow {
|
||||
flex: 1;
|
||||
}
|
||||
.iwb-promptlib .iwb-row {
|
||||
display: flex; gap: 6px; align-items: center;
|
||||
}
|
||||
.iwb-promptlib .iwb-hint {
|
||||
font-size: 11px; color: var(--iwb-text2); margin-top: 4px;
|
||||
}
|
||||
.iwb-promptlib .iwb-toolbar-title {
|
||||
font-weight: 700; font-size: 13px; margin-right: 2px;
|
||||
}
|
||||
.iwb-plp-mask {
|
||||
position: fixed; inset: 0; background: rgba(0,0,0,0.45); z-index: 300; display: flex; align-items: center; justify-content: center;
|
||||
}
|
||||
.iwb-plp-dialog {
|
||||
width: 680px; max-width: calc(100vw - 60px); max-height: 82vh; background: var(--iwb-panel); border: 1px solid var(--iwb-border2); border-radius: 14px; display: flex; flex-direction: column; overflow: hidden;
|
||||
}
|
||||
.iwb-plp-dialog-head {
|
||||
display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid var(--iwb-border);
|
||||
}
|
||||
.iwb-plp-dialog-body {
|
||||
padding: 12px 16px; overflow: auto; display: flex; flex-direction: column; gap: 10px; max-height: 62vh;
|
||||
}
|
||||
.iwb-promptlib .iwb-lib-body {
|
||||
flex: 1; overflow: hidden; padding: 12px 12px; display: flex; flex-direction: column; gap: 8px;
|
||||
}
|
||||
.iwb-promptlib .iwb-lib-fixed {
|
||||
flex: 0 0 auto; display: flex; flex-direction: column; gap: 8px;
|
||||
}
|
||||
.iwb-promptlib .iwb-lib-scroll {
|
||||
flex: 1 1 auto; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding-right: 2px;
|
||||
}
|
||||
.iwb-promptlib .iwb-lib-chips-scroll::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.iwb-promptlib .iwb-lib-chips-scroll > .iwb-chip:last-child {
|
||||
margin-right: 16px;
|
||||
}
|
||||
.iwb-promptlib .iwb-lib-searchscope-back {
|
||||
display: inline-flex; align-items: center; justify-content: center; width: 15px; height: 15px; padding: 0; border: none; border-radius: 999px; background: transparent; color: var(--iwb-text2); font-size: 13px; line-height: 1; cursor: pointer;
|
||||
}
|
||||
.iwb-promptlib .iwb-lib-searchscope-back:hover {
|
||||
background: color-mix(in srgb, var(--iwb-text) 12%, transparent); color: var(--iwb-text);
|
||||
}
|
||||
.iwb-promptlib .iwb-chip {
|
||||
flex: 0 0 auto; display: inline-flex; align-items: center; gap: 4px; background: var(--iwb-layer); border: 1px solid var(--iwb-border); border-radius: 999px; padding: 4px 10px; font-size: 12px; color: var(--iwb-text2); cursor: pointer; white-space: nowrap; transition: all 0.15s;
|
||||
}
|
||||
.iwb-promptlib .iwb-chip:hover {
|
||||
color: var(--iwb-text); border-color: var(--iwb-border2);
|
||||
}
|
||||
.iwb-promptlib .iwb-chip-active {
|
||||
background: var(--iwb-panel); border-color: var(--iwb-border2); color: var(--iwb-text); font-weight: 600;
|
||||
}
|
||||
.iwb-promptlib .iwb-chip-active:hover {
|
||||
color: var(--iwb-text);
|
||||
}
|
||||
.iwb-promptlib .iwb-chip-count {
|
||||
font-size: 11px; opacity: 0.8;
|
||||
}
|
||||
.iwb-promptlib .iwb-chip-add {
|
||||
font-weight: 700;
|
||||
}
|
||||
.iwb-promptlib .iwb-pcard .iwb-btn:hover {
|
||||
opacity: 1; color: var(--iwb-text); background: transparent;
|
||||
}
|
||||
.iwb-promptlib .iwb-pcard .iwb-btn-starred {
|
||||
color: var(--iwb-text); opacity: 1;
|
||||
}
|
||||
.iwb-promptlib .iwb-pcard {
|
||||
border: 1px solid var(--iwb-border); border-radius: 8px; padding: 8px 10px; background: var(--iwb-panel);
|
||||
}
|
||||
.iwb-promptlib .iwb-tag {
|
||||
display: inline-block; background: color-mix(in srgb, var(--iwb-text) 7%, transparent); color: var(--iwb-text2); border-radius: 6px; font-size: 11px; padding: 2px 6px; margin: 4px 4px 0 0;
|
||||
}
|
||||
.iwb-plp-dialog-sm {
|
||||
width: 460px;
|
||||
}
|
||||
.iwb-promptlib .iwb-pcard {
|
||||
cursor: grab;
|
||||
}
|
||||
.iwb-promptlib .iwb-pcard:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
.iwb-promptlib .iwb-btn-primary .iwb-ic {
|
||||
width: 15px; height: 15px;
|
||||
}
|
||||
.iwb-promptlib .iwb-btn:hover {
|
||||
border-color: var(--iwb-brand); color: var(--iwb-brand);
|
||||
}
|
||||
.iwb-promptlib .iwb-btn:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
.iwb-promptlib .iwb-btn:focus-visible {
|
||||
outline: 2px solid color-mix(in srgb, var(--iwb-brand) 60%, transparent); outline-offset: 1px;
|
||||
}
|
||||
.iwb-promptlib .iwb-btn:disabled {
|
||||
opacity: 0.45; cursor: not-allowed; transform: none;
|
||||
}
|
||||
.iwb-promptlib .iwb-btn-primary {
|
||||
background: var(--iwb-brand); border-color: var(--iwb-brand); color: var(--iwb-on-brand);
|
||||
}
|
||||
.iwb-promptlib .iwb-btn-primary:hover {
|
||||
background: color-mix(in srgb, var(--iwb-brand) 85%, var(--iwb-text)); border-color: var(--iwb-brand); color: var(--iwb-on-brand);
|
||||
}
|
||||
.iwb-promptlib .iwb-btn-sm {
|
||||
padding: 4px 6px; font-size: 11px;
|
||||
}
|
||||
.iwb-promptlib .iwb-btn-danger {
|
||||
color: var(--iwb-err);
|
||||
}
|
||||
.iwb-promptlib .iwb-btn-danger:hover {
|
||||
border-color: var(--iwb-err); color: var(--iwb-err);
|
||||
}
|
||||
.iwb-promptlib .iwb-ctxmenu {
|
||||
position: fixed; min-width: 196px; max-width: 240px; max-height: calc(100vh - 24px); overflow-y: auto; padding: 6px; background: var(--iwb-layer); border: 1px solid var(--iwb-border); border-radius: 12px; box-shadow: 0 12px 32px rgba(0,0,0,0.28), 0 2px 8px rgba(0,0,0,0.16); z-index: 91; display: flex; flex-direction: column; gap: 2px;
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-title {
|
||||
font-size: 11px; font-weight: 700; color: var(--iwb-text2); letter-spacing: 1px; padding: 6px 10px 2px; text-transform: uppercase;
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-item {
|
||||
display: flex; align-items: center; gap: 8px; width: 100%; padding: 6px 10px; border: none; border-radius: 8px; background: transparent; color: var(--iwb-text); font-size: 13px; cursor: pointer; text-align: left;
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-item .iwb-ic {
|
||||
width: 14px; height: 14px; flex: 0 0 auto; color: var(--iwb-text2);
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-item:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--iwb-brand) 12%, transparent); color: var(--iwb-text);
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-item:hover:not(:disabled) .iwb-ic {
|
||||
color: var(--iwb-brand);
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-item:disabled {
|
||||
opacity: 0.38; cursor: default;
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-item.iwb-ctx-danger {
|
||||
color: var(--iwb-err);
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-item.iwb-ctx-danger .iwb-ic {
|
||||
color: var(--iwb-err);
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-item.iwb-ctx-danger:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--iwb-err) 10%, transparent); color: var(--iwb-err);
|
||||
}
|
||||
.iwb-promptlib .iwb-ctx-sep {
|
||||
height: 1px; margin: 4px 6px; background: var(--iwb-border); flex: 0 0 auto;
|
||||
}
|
||||
.iwb-promptlib .iwb-drawer-spacer {
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
/* v1.10.1:详情底部分享组(文本/文件分享)与插入组之间的竖向分割线 */
|
||||
.iwb-plp-dialog .iwb-plp-foot-vsep {
|
||||
display: inline-block; width: 1px; height: 18px; flex: 0 0 auto;
|
||||
align-self: center; margin: 0 12px; background: var(--iwb-border);
|
||||
}
|
||||
.iwb-plp-dialog .iwb-section-sub {
|
||||
margin-top: 2px;
|
||||
}
|
||||
.iwb-plp-mask.iwb-mask-ghost .iwb-settings-modal {
|
||||
box-shadow: 0 24px 60px rgba(0,0,0,.32);
|
||||
}
|
||||
|
||||
/* v1.6.7:卡片长按可拖的视觉反馈 */
|
||||
.iwb-plp-card{cursor:grab}
|
||||
.iwb-plp-card.is-armed{border-color:var(--iwb-plp-accent,#7c4dff);box-shadow:0 0 0 2px color-mix(in srgb,var(--iwb-plp-accent,#7c4dff) 20%,transparent)}
|
||||
.iwb-plp-card.is-dragging{opacity:.55;transform:scale(.98);cursor:grabbing}
|
||||
|
||||
/* v1.6.8:卡片悬停放大 + 按下/拖拽反馈 */
|
||||
.iwb-plp-card{transition:transform .14s ease, box-shadow .14s ease, border-color .14s ease, opacity .14s ease}
|
||||
.iwb-plp-card:hover{transform:scale(1.03);box-shadow:0 8px 22px rgba(0,0,0,.14);z-index:2}
|
||||
.iwb-plp-card.is-pressed{border-color:var(--iwb-plp-accent,#7c4dff);box-shadow:0 0 0 2px color-mix(in srgb,var(--iwb-plp-accent,#7c4dff) 22%,transparent)}
|
||||
.iwb-plp-card.is-dragging{opacity:.55;transform:scale(.98)}
|
||||
|
||||
/* v1.6.9:拖拽虚拟卡片(跟手预览) */
|
||||
.iwb-plp-dragghost{width:168px;display:flex;align-items:center;gap:8px;padding:8px 10px;background:var(--iwb-panel,#fff);border:2px solid var(--iwb-plp-accent,#7c4dff);border-radius: 10px;box-shadow:0 12px 28px rgba(0,0,0,.22);font-size:12px;pointer-events:none;z-index: var(--iwb-z-anchor, 3200)}
|
||||
.iwb-plp-ghostcov{width:38px;height:38px;border-radius:8px;object-fit:cover;flex:0 0 auto;background:var(--iwb-plugin-inset,#eef0f2)}
|
||||
.iwb-plp-ghosttxt{min-width:0;display:flex;flex-direction:column;gap:2px}
|
||||
.iwb-plp-ghostname{font-weight:600;color:var(--iwb-text,#1c2333);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.iwb-plp-ghosthint{font-size: 11px;color:var(--iwb-plp-accent,#5a4bd0)}
|
||||
|
||||
/* v1.6.10:悬停放大改为「内层背景层缩放」——卡片命中区域不变,渐变卡不再闪烁 */
|
||||
.iwb-plp-bg{position:absolute;inset:0;overflow:hidden;border-radius:inherit;transition:transform .16s ease;will-change:transform;backface-visibility:hidden}
|
||||
.iwb-plp-card:hover .iwb-plp-bg{transform:scale(1.045)}
|
||||
.iwb-plp-card:hover{border-color:var(--iwb-border2,#b9bfca);box-shadow:0 8px 22px rgba(0,0,0,.14)}
|
||||
/* 取消卡片本体的缩放/层级切换(闪烁与边缘点击丢失的来源) */
|
||||
.iwb-plp-card{transform:none}
|
||||
.iwb-plp-card:hover{transform:none;z-index:auto}
|
||||
.iwb-plp-card.is-dragging{opacity:.55}
|
||||
.iwb-plp-bg,.iwb-plp-cover{pointer-events:none}
|
||||
|
||||
/* v1.6.11:封面卡瀑布流高度由图片决定 —— 背景层必须是普通流,不能绝对定位(否则卡塌成一条线) */
|
||||
.iwb-plp-bg{position:relative;inset:auto;width:100%}
|
||||
.iwb-plp-card.no-cover .iwb-plp-bg{position:absolute;inset:0}
|
||||
.iwb-plp-bg .iwb-plp-cover{width:100%;height:auto;object-fit:contain;display:block}
|
||||
|
||||
/* v1.6.13:未选中时变量输入框不拦截指针 —— 单击节点=选中/可拖动;选中后再点输入框编辑 */
|
||||
.iwb-plp-node:not(.is-selected) input{pointer-events:none}
|
||||
.iwb-plp-card{user-select:none}
|
||||
body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webkit-user-select:none!important}
|
||||
.iwb-plp-placeghost{border-style:dashed!important;pointer-events:none}
|
||||
.iwb-plp-placehint{font-size: 11px;color:var(--iwb-plp-accent,#5a4bd0);margin-top:2px}
|
||||
.iwb-plp-placebox{position:fixed;left:-9999px;top:0;z-index: var(--iwb-z-anchor, 3200);pointer-events:none;border:2px dashed var(--iwb-plp-accent,#6b4dff);border-radius:12px;background:color-mix(in srgb,var(--iwb-plp-accent,#6b4dff) 9%,transparent);display:flex;align-items:center;justify-content:center;box-shadow:0 10px 26px rgba(30,20,80,.10)}
|
||||
.iwb-plp-placebox-t{font-size:12px;color:var(--iwb-plp-accent,#5a3fd0);background:rgba(255,255,255,.82);border-radius:999px;padding: 4px 10px}
|
||||
/* v1.6.23:放置指示改为灰色小方框 */
|
||||
.iwb-plp-placebox{border: 2px dashed var(--iwb-border2, #9aa3ad);border-radius:10px;background:rgba(122,130,142,.10);box-shadow:none}
|
||||
.iwb-plp-placebox-t{font-size:11px;color: var(--plp-c3, #6b7280);background:rgba(255,255,255,.75);padding:2px 8px}
|
||||
/* v1.7.0:编辑面板三栏 + 可拖宽;详情封面放大、变量高亮 */
|
||||
.iwb-plp-eleft{flex:0 0 236px;width:236px}
|
||||
.iwb-plp-emid{flex:1 1 auto;min-width:220px;display:flex;flex-direction:column;min-height:0}
|
||||
.iwb-plp-emid .iwb-plp-etext{flex:1 1 auto;min-height:0;resize:none}
|
||||
.iwb-plp-esplit{flex:0 0 10px;cursor:col-resize;display:flex;align-items:center;justify-content:center;border-radius:6px;background:var(--iwb-plugin-inset,#f3f4f7)}
|
||||
.iwb-plp-esplit:hover{background:var(--iwb-plugin-hover,#e9ecf1)}
|
||||
.iwb-plp-eright{flex:0 0 auto;width:300px;min-width:190px;max-width:460px;display:flex;flex-direction:column;min-height:0;background:var(--iwb-plugin-surface,#fafbfc);border:1px solid var(--iwb-border,#e6e8ec);border-radius:10px;padding:8px}
|
||||
.iwb-plp-vars{flex:1 1 auto;min-height:0;display:flex;flex-direction:column}
|
||||
.iwb-plp-vrows{flex:1 1 auto;min-height:0;overflow:auto}
|
||||
.iwb-plp-vitem{padding:4px 0;border-bottom:1px dashed var(--iwb-border,#eceef2)}
|
||||
.iwb-plp-vrow2{display:flex;align-items:center;gap:6px}
|
||||
.iwb-plp-vname{flex:1 1 auto;min-width:0;height:32px}
|
||||
.iwb-plp-vi{flex:0 0 auto;width:24px;height:24px;padding:0;border-radius:50%;border:1px solid var(--iwb-border,#dfe3e9);background: var(--iwb-plugin-card, #fff);color: var(--iwb-text-dim, #9aa1ac);font-size:11px;line-height:22px;text-align:center}
|
||||
.iwb-plp-vi.is-open{background: var(--iwb-plp-accent-soft, #f1ecff);border-color: var(--iwb-plp-accent-border, #d8cbff);color: var(--iwb-plp-accent, #5a3fd0)}
|
||||
.iwb-plp-vdesc{width:100%;height:28px;margin-top: 6px;border-style:dashed;background: var(--iwb-field, #fbfcfd);font-size: 12px;color: var(--plp-c3, #6b7280)}
|
||||
/* v1.12.0:变量编辑器折叠两态(收起一行名称+摘要,展开四字段)与内容多行框 */
|
||||
.iwb-plp-vrow2{cursor:pointer}
|
||||
.iwb-plp-vcaret{flex:0 0 12px;width:12px;text-align:center;font-size:11px;line-height:32px;color:var(--iwb-text2,#8b929c)}
|
||||
.iwb-plp-vlabelx{flex:1 1 auto;min-width:0;font-size:13px;line-height:32px;color:var(--iwb-text,#2a2f36);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.iwb-plp-vlabelx.is-empty{color:var(--iwb-text2,#8b929c)}
|
||||
.iwb-plp-vsum{flex:0 0 auto;font-size:11px;line-height:32px;white-space:nowrap;color:var(--iwb-text2,#8b929c)}
|
||||
.iwb-plp-vfield{display:flex;align-items:flex-start;gap:8px;margin-top:6px}
|
||||
.iwb-plp-vflabel{flex:0 0 40px;padding-top:8px;font-size:12px;color:var(--iwb-text2,#8b929c)}
|
||||
.iwb-plp-vbody{flex:1 1 auto;min-width:0}
|
||||
.iwb-plp-vbody .iwb-input{width:100%}
|
||||
.iwb-plp-vbody .iwb-plp-vdesc{margin-top:0}
|
||||
.iwb-plp-vdef{height:auto;min-height:66px;padding:4px 10px;line-height:1.65;font-size:12px;resize:none;overflow-y:hidden}
|
||||
.iwb-plp-dcov{flex:0 0 auto;width:180px;height:180px;border-radius:12px;overflow:hidden}
|
||||
.iwb-plp-dvar{background: var(--iwb-plp-accent-soft, #f1ecff);color: var(--iwb-plp-accent, #5a3fd0);border-radius: 6px;padding:0 4px;font-weight:500}
|
||||
/* v1.7.1:编辑面板视觉精修——输入框比底色更亮、去多余边框、细分隔线 */
|
||||
.iwb-plp-dialog .iwb-plp-dbody{gap:10px;padding:12px;background: var(--iwb-plugin-inset, #f4f5f7)}
|
||||
.iwb-plp-dialog .iwb-plp-eleft{flex:0 0 236px;width:236px;background: var(--iwb-plugin-card, #fff);border: 1px solid var(--iwb-plugin-border, #e6e8ec);border-radius:12px;padding:12px}
|
||||
.iwb-plp-dialog .iwb-plp-emid{background: var(--iwb-plugin-card, #fff);border: 1px solid var(--iwb-plugin-border, #e6e8ec);border-radius:12px;padding:10px 12px 12px}
|
||||
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-etext{border: 1px solid var(--iwb-plugin-border, #eef0f3);background: var(--iwb-field, #fbfcfd);border-radius: 8px;padding:10px 12px}
|
||||
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-etext:focus{background: var(--iwb-plugin-card, #fff);border-color: var(--iwb-plp-accent-border, #cfc3ff);box-shadow:0 0 0 3px rgba(107,77,255,.08)}
|
||||
.iwb-plp-dialog .iwb-plp-esplit{flex:0 0 6px;background:transparent;border-radius: 6px}
|
||||
.iwb-plp-dialog .iwb-plp-esplit:hover{background: var(--iwb-plugin-hover, #e7e9ee)}
|
||||
.iwb-plp-dialog .iwb-plp-esplit::before{content:'';display:block;width:2px;height:30px;border-radius: 6px;background: var(--iwb-plugin-hover, #d7dbe2)}
|
||||
.iwb-plp-dialog .iwb-plp-eright{background:transparent;border:0;padding:2px 0 0}
|
||||
.iwb-plp-dialog .iwb-plp-vitem{border:0;padding:2px 0}
|
||||
.iwb-plp-dialog .iwb-plp-vrow2{gap:6px}
|
||||
.iwb-plp-dialog .iwb-plp-vname{background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eceef2);border-radius:8px;height:32px;padding:0 10px;font-size: 13px;color: var(--iwb-text, #33383f)}
|
||||
.iwb-plp-dialog .iwb-plp-vname:focus{background: var(--iwb-plugin-card, #fff);border-color: var(--iwb-plp-accent-border, #cfc3ff);box-shadow:0 0 0 3px rgba(107,77,255,.08)}
|
||||
.iwb-plp-dialog .iwb-plp-vi{background:transparent;border:0;color: var(--iwb-text-dim, #aab0ba);width:22px;height:22px;line-height:20px}
|
||||
.iwb-plp-dialog .iwb-plp-vi:hover{background: var(--iwb-plugin-inset, #eef0f4);color: var(--plp-c3, #6b7280)}
|
||||
.iwb-plp-dialog .iwb-plp-vi.is-open{background: var(--iwb-plp-accent-soft, #f1ecff);color: var(--iwb-plp-accent, #5a3fd0)}
|
||||
.iwb-plp-dialog .iwb-plp-vdesc{background: var(--iwb-field, #fbfcfd);border: 1px dashed var(--iwb-plugin-border, #e2e6ec);border-radius: 8px;height:28px;margin-top:4px}
|
||||
.iwb-plp-dialog .iwb-plp-lrow span{color: var(--iwb-text2, #8a919c);font-size: 12px}
|
||||
.iwb-plp-dialog .iwb-plp-lrow .iwb-input{background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eceef2);border-radius:8px;height:32px}
|
||||
.iwb-plp-dialog .iwb-plp-lrow .iwb-input:focus{background: var(--iwb-plugin-card, #fff);border-color: var(--iwb-plp-accent-border, #cfc3ff)}
|
||||
/* v1.7.2:正文变量高亮(黑粗)+ 说明灰按钮 + 说明背景回归面板底 */
|
||||
.iwb-plp-ewrap{position:relative;flex:1 1 auto;min-height:0;display:flex;border-radius: 8px;background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eef0f3)}
|
||||
.iwb-plp-ewrap:focus-within{background: var(--iwb-plugin-card, #fff);border-color: var(--iwb-plp-accent-border, #cfc3ff);box-shadow:0 0 0 3px rgba(107,77,255,.08)}
|
||||
.iwb-plp-ewrap .iwb-plp-etext{flex:1 1 auto;min-height:0;border:0;background:transparent;box-shadow:none;color:transparent;caret-color:var(--plp-c22, #1d2129);position:relative;z-index:1;resize:none}
|
||||
.iwb-plp-ewrap .iwb-plp-etext:focus{background:transparent;border:0;box-shadow:none}
|
||||
.iwb-plp-hl{position:absolute;inset:0;padding:10px 12px;overflow:hidden;white-space:pre-wrap;word-wrap:break-word;font-size:13px;line-height:1.9;color: var(--iwb-text2, #5b6472);pointer-events:none;z-index:0}
|
||||
.iwb-plp-hlvar{color: var(--iwb-text, #1d2129);font-weight:600}
|
||||
.iwb-plp-dialog .iwb-plp-vi.is-open{background: var(--iwb-plugin-hover, #eef0f3);color: var(--iwb-text2, #5b6472)}
|
||||
.iwb-plp-dialog .iwb-plp-vdesc{background:transparent;border: 1px dashed var(--iwb-plugin-border, #dfe3e9)}
|
||||
.iwb-plp-dvar{background:transparent;color: var(--iwb-text, #1d2129);font-weight:600;padding:0}
|
||||
.iwb-plp-hres{height:6px;margin: -4px 0 0;cursor:ns-resize;flex:0 0 auto;border-radius: 6px}
|
||||
.iwb-plp-hres:hover{background: var(--iwb-plugin-hover, #e7e9ee)}
|
||||
/* 正文可见性:textarea 透明,显示下方高亮层 */
|
||||
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap{flex:1 1 auto;min-height:0;position:relative;display:flex;background: var(--iwb-field, #fbfcfd);border: 1px solid var(--iwb-plugin-border, #eef0f3);border-radius: 8px}
|
||||
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext{background:transparent!important;color:transparent!important;border:0!important;box-shadow:none!important;padding:10px 12px}
|
||||
.iwb-plp-dialog .iwb-plp-hl{padding:10px 12px;font-size:13px;line-height:1.9}
|
||||
.iwb-plp-namebox{min-height:34px;height:34px;line-height:1.45;padding: 6px 10px;resize:vertical;overflow:auto;font-size: 13px}
|
||||
.iwb-plp-insvar{color: var(--iwb-text, #1d2129)!important;background: var(--iwb-plugin-card, #fff)!important;border-color: var(--iwb-plugin-border, #e2e6ec)!important}
|
||||
.iwb-plp-insvar:hover{background: var(--iwb-plugin-inset, #f4f6f9)!important}
|
||||
/* v1.7.5:编辑封面卡在框内;详情封面放大 */
|
||||
.iwb-plp-dialog .iwb-plp-ecov{width:100%;height:250px;overflow:hidden;border-radius:12px;background:var(--iwb-plugin-inset,#f3f4f7)}
|
||||
.iwb-plp-dialog .iwb-plp-ecov .iwb-plp-cover{width:100%;height:100%;object-fit:cover;object-position:center;display:block;border-radius:12px}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dbody{align-items:flex-start}
|
||||
.iwb-plp-dialog .iwb-plp-dcov{width:264px;height:264px;flex:0 0 auto;overflow:hidden;border-radius:12px;background:var(--iwb-plugin-inset,#f3f4f7)}
|
||||
.iwb-plp-dialog .iwb-plp-dcov .iwb-plp-cover{width:100%;height:100%;object-fit:cover;object-position:center;display:block;border-radius:12px}
|
||||
/* v1.7.6:封面完整展示(contain),不裁剪 */
|
||||
.iwb-plp-dialog .iwb-plp-ecov .iwb-plp-cover{object-fit:contain;background:transparent}
|
||||
.iwb-plp-dialog .iwb-plp-dcov .iwb-plp-cover{object-fit:contain;background:transparent}
|
||||
.iwb-plp-dialog .iwb-plp-ecov{background:var(--iwb-plugin-inset,#f3f4f7)}
|
||||
.iwb-plp-dialog .iwb-plp-dcov{background:var(--iwb-plugin-inset,#f3f4f7)}
|
||||
/* v1.7.7:编辑区文字层与高亮层使用完全一致的字体度量,修复光标/选区错位 */
|
||||
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext,
|
||||
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-hl{
|
||||
font-family:-apple-system,BlinkMacSystemFont,'PingFang SC','Helvetica Neue',system-ui,sans-serif!important;
|
||||
font-size:13px!important;
|
||||
line-height:1.85!important;
|
||||
letter-spacing:0!important;
|
||||
padding:10px 12px!important;
|
||||
margin:0!important;
|
||||
border:0!important;
|
||||
box-sizing:border-box!important;
|
||||
white-space:pre-wrap!important;
|
||||
overflow-wrap:break-word!important;
|
||||
word-break:break-word!important;
|
||||
tab-size:4!important;
|
||||
}
|
||||
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext{overflow-y:auto!important;scrollbar-gutter:stable}
|
||||
/* v1.9.3:高亮层与 textarea 用同样的滚动条占位,避免换行位置不一致导致色块漂移 */
|
||||
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-hl{overflow:hidden!important;scrollbar-gutter:stable}
|
||||
/* v1.7.9:详情正文独立滚动,长文不再压到底部按钮 */
|
||||
.iwb-plp-dialog-detail .iwb-plp-dbody{overflow:hidden;align-items:stretch}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dright{flex:1 1 auto;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dtext{flex:1 1 auto;min-height:0;overflow:auto;padding-right:10px;margin-bottom:6px}
|
||||
/* v1.8.0:详情标题/分组/标签移到封面下方;编辑标签改为输入+加号 */
|
||||
.iwb-plp-dialog-detail .iwb-plp-dbody{align-items:flex-start}
|
||||
.iwb-plp-dleftcol{flex:0 0 264px;width:264px;display:flex;flex-direction:column;min-width:0}
|
||||
.iwb-plp-dtitle{font-size: 17px;font-weight:650;line-height:1.35;margin-top: 12px;color:var(--iwb-text,#1d2129)}
|
||||
.iwb-plp-dmeta{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-top:8px}
|
||||
.iwb-plp-dgroup{font-size: 12px;background: var(--iwb-plugin-inset, #eef0f4);color: var(--iwb-text2, #5b6472);border-radius:999px;padding: 2px 8px}
|
||||
.iwb-plp-dtag{font-size: 12px;background: var(--iwb-plp-accent-soft, #f4f0ff);color: var(--iwb-plp-accent, #5a3fd0);border-radius:999px;padding: 2px 8px}
|
||||
.iwb-plp-dlen{font-size: 12px;color: var(--iwb-text-dim, #9aa1ac)}
|
||||
.iwb-plp-tagwrap{display:flex;flex-direction:column;gap:6px;flex:1;min-width:0}
|
||||
.iwb-plp-tagchips{display:flex;flex-wrap:wrap;gap: 6px}
|
||||
.iwb-plp-tagchip{display:inline-flex;align-items:center;gap:4px;font-size: 12px;background: var(--iwb-plugin-inset, #eef0f4);border-radius:999px;padding:2px 8px;color: var(--iwb-text, #3f4450)}
|
||||
.iwb-plp-tagx{cursor:pointer;color: var(--iwb-text-dim, #9aa1ac);font-style:normal}
|
||||
.iwb-plp-tagx:hover{color: var(--iwb-err, #c0392b)}
|
||||
.iwb-plp-tagrow{display:flex;gap:6px}
|
||||
.iwb-plp-tagin{flex:1;min-width:0;height:30px}
|
||||
.iwb-plp-lrow-tags{align-items:flex-start}
|
||||
.iwb-plp-tagadd{flex:0 0 auto;width:30px;height:30px;padding:0;font-size:15px;line-height:28px}
|
||||
/* v1.8.1:详情标题/分组/标签左对齐并带标题;标签加号对齐修复 */
|
||||
.iwb-plp-dtitle{font-size:20px;font-weight:650;line-height:1.35;margin-top:16px;color:var(--iwb-text,#1d2129)}
|
||||
.iwb-plp-dmeta{display:flex;flex-direction:column;gap: 6px;margin-top:12px;align-items:flex-start}
|
||||
.iwb-plp-dmrow{display:flex;align-items:center;gap:10px;width:100%}
|
||||
.iwb-plp-dmk{flex:0 0 30px;width:30px;font-size: 12px;color: var(--iwb-text-dim, #9aa1ac)}
|
||||
.iwb-plp-dmv{display:flex;flex-wrap:wrap;align-items:center;gap: 6px;min-width:0}
|
||||
.iwb-plp-dgroup{font-size:12px;color: var(--iwb-text, #3f4450);background: var(--iwb-plugin-inset, #f2f4f7);border-radius:6px;padding: 2px 8px}
|
||||
.iwb-plp-dtag{font-size: 12px;color: var(--iwb-plp-accent, #5a3fd0);background: var(--iwb-plp-accent-soft, #f4f0ff);border-radius:6px;padding: 2px 8px}
|
||||
.iwb-plp-dempty{font-size:12px;color: var(--iwb-text-dim, #b3b9c2)}
|
||||
.iwb-plp-dlen{font-size:12px;color: var(--iwb-text2, #8a919c)}
|
||||
.iwb-plp-tagrow{display:flex;align-items:center;gap:6px}
|
||||
.iwb-plp-tagin{height:30px;border-radius:8px}
|
||||
.iwb-plp-tagadd{flex:0 0 auto;width:30px;height:30px;padding:0;border-radius:8px;background: var(--iwb-plugin-inset, #f2f4f7);border: 1px solid var(--iwb-plugin-border, #e2e6ec);color: var(--iwb-text2, #5b6472);font-size: 15px;line-height:1;display:inline-flex;align-items:center;justify-content:center}
|
||||
.iwb-plp-tagadd:hover{background: var(--iwb-plugin-hover, #e9ecf1)}
|
||||
/* v1.8.2:详情左右两栏卡片化 + 分割线 */
|
||||
.iwb-plp-dialog-detail .iwb-plp-dbody{gap: 12px;padding:16px;background: var(--iwb-plugin-inset, #f4f5f7)}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dleftcol{flex:0 0 300px;width:300px;padding:12px;border: 1px solid var(--iwb-plugin-border, #e8eaee);border-radius:14px;background: var(--iwb-plugin-card, #fff);align-self:flex-start}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dcov{width:100%;height:270px;border-radius:10px}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dtitle{font-size:20px;font-weight:650;line-height:1.35;margin-top: 12px;color:var(--iwb-text,#1d2129)}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dmeta{margin-top:12px;padding-top:12px;border-top: 1px solid var(--iwb-plugin-border, #eef0f3);gap:8px}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dright{flex:1 1 auto;min-width:0;min-height:0;display:flex;flex-direction:column;padding: 12px 16px;border: 1px solid var(--iwb-plugin-border, #e8eaee);border-radius:14px;background: var(--iwb-plugin-card, #fff);overflow:hidden}
|
||||
.iwb-plp-dsec{font-size: 12px;font-weight:600;color: var(--iwb-text2, #8a919c);letter-spacing:.04em;padding-bottom:8px;margin-bottom:8px;border-bottom: 1px solid var(--iwb-plugin-border, #eef0f3);flex:0 0 auto}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dtext{flex:1 1 auto;min-height:0;overflow:auto;padding-right:10px;font-size: 14px;line-height:2;color: var(--iwb-text, #3a4048)}
|
||||
/* v1.8.3:详情左卡片撑到底、四边等距;正文恢复滚动不被底部遮挡 */
|
||||
.iwb-plp-dialog-detail{display:flex;flex-direction:column;overflow:hidden}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dbody{display:flex;flex:1 1 auto;min-height:0;overflow:hidden;gap: 12px;padding:16px;background: var(--iwb-plugin-inset, #f4f5f7)}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dleftcol{align-self:stretch;display:flex;flex-direction:column;overflow:auto;padding:12px;border: 1px solid var(--iwb-plugin-border, #e8eaee);border-radius:14px;background: var(--iwb-plugin-card, #fff)}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dright{flex:1 1 auto;min-width:0;min-height:0;overflow:hidden;display:flex;flex-direction:column;padding: 12px 16px;border: 1px solid var(--iwb-plugin-border, #e8eaee);border-radius:14px;background: var(--iwb-plugin-card, #fff)}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dtext{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;padding-right:8px}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dfooter{flex:0 0 auto}
|
||||
/* v1.8.4:右卡片纵向拉伸填满,正文出现滚动条 */
|
||||
.iwb-plp-dialog-detail .iwb-plp-dbody{align-items:stretch!important}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dright{align-self:stretch!important;height:100%;max-height:100%;overflow:hidden!important}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dtext{flex:1 1 0;min-height:0;overflow-y:auto!important;overflow-x:hidden}
|
||||
/* v1.8.7:详情标题缩小;分组/标签去底色;元信息加分割线与行高 */
|
||||
.iwb-plp-dialog-detail .iwb-plp-dtitle{font-size:17px!important;font-weight:650;margin-top:12px}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dmeta{margin-top:12px;padding-top: 12px;border-top: 1px solid var(--iwb-plugin-border, #eef0f3);gap:10px}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dmrow{gap:6px}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dmk{flex:0 0 auto;width:auto;font-size:12px;line-height:1.6;color: var(--iwb-text-dim, #9aa1ac)}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dgroup,.iwb-plp-dialog-detail .iwb-plp-dtag{background:transparent!important;padding:0!important;border-radius:0!important;font-size: 13px;line-height:1.6;color: var(--iwb-text, #2f3540)}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dtag{color: var(--iwb-plp-accent, #5a3fd0);}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dlen{font-size: 13px;line-height:1.6;color: var(--iwb-text, #2f3540)}
|
||||
/* v1.8.8:详情标题 14px;元信息行间浅分割线;封面底色更接近白色(编辑/详情统一) */
|
||||
.iwb-plp-dialog-detail .iwb-plp-dtitle{font-size:14px!important;font-weight:650;line-height:1.5;margin-top:12px}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dmeta{gap:0}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dmrow{padding: 6px 0;border-bottom: 1px solid var(--iwb-plugin-border, #f3f5f8)}
|
||||
.iwb-plp-dialog-detail .iwb-plp-dmrow:last-child{border-bottom:0}
|
||||
.iwb-plp-dialog .iwb-plp-dcov,.iwb-plp-dialog .iwb-plp-ecov{background: var(--iwb-field, #fcfcfd)!important}
|
||||
.iwb-plp-dialog .iwb-plp-dcov .iwb-plp-cover,.iwb-plp-dialog .iwb-plp-ecov .iwb-plp-cover{background:transparent!important}
|
||||
/* v1.8.19:编辑区高亮变量不得加粗——加粗会改变字形宽度,导致点击位置逐次向左偏移 */
|
||||
.iwb-plp-hlvar{font-weight:400!important;letter-spacing:normal!important}
|
||||
/* v1.9.3:变量着色改为「textarea 只负责文字 + 背层只画浅主色色块」——
|
||||
两层字体/换行/滚动条占位由 v1.7.7 规则保持一致,变量 span 沿用 400 字重(不加粗,宽度不漂移),
|
||||
文字仍由 textarea 自己画(可见),所以插入点/点击/选区完全不受影响。
|
||||
注:v1.8.20 停用高亮层是因为当时「透明 textarea + 背层画文字」两层文字错位;本版不画文字,只画色块,不会复发。 */
|
||||
.iwb-plp-ewrap .iwb-plp-hl{display:block!important;color:transparent!important;-webkit-text-fill-color:transparent!important}
|
||||
.iwb-plp-hlvar{color:transparent!important;-webkit-text-fill-color:transparent!important;background:color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 16%, transparent);border-radius:6px;box-shadow:0 0 0 1px color-mix(in srgb, var(--iwb-plp-accent, #7c4dff) 22%, transparent)}
|
||||
.iwb-plp-ewrap .iwb-plp-etext{color:var(--iwb-text,#2a2f36)!important;background:transparent!important}
|
||||
/* v1.8.21:正文文字必须可见(覆盖旧的 transparent !important) */
|
||||
.iwb-plp-dialog .iwb-plp-emid .iwb-plp-ewrap .iwb-plp-etext{color:var(--iwb-text,#2a2f36)!important;caret-color:var(--iwb-text,#2a2f36)!important;-webkit-text-fill-color:var(--iwb-text,#2a2f36)!important}
|
||||
/* v1.9.3:右侧变量名与详情正文里的变量也用主色呼应(只读区,零功能风险) */
|
||||
.iwb-plp-dialog .iwb-plp-vname{color:var(--iwb-plp-accent,#5a3fd0)}
|
||||
.iwb-plp-dialog .iwb-plp-dvar{color:var(--iwb-plp-accent,#5a3fd0);background:var(--iwb-plp-accent-soft,#f1ecff);border-radius:6px;padding:0 2px}
|
||||
/* 回滚开关:若真机发现任何点击/光标异常,把下行打开即回到 v1.8.20 纯 textarea 状态。
|
||||
.iwb-plp-ewrap .iwb-plp-hl{display:none!important} */
|
||||
@@ -0,0 +1,244 @@
|
||||
// promptlib 本地契约测试(纯 node):
|
||||
// - v1.9.2:分享带封面开关
|
||||
// - v1.9.3:编辑区变量浅主色底色(方案 C,只画色块不改输入)
|
||||
// - v1.10.0:文本分享 / 文件分享双路径 + 顶部三按钮 + 右键去分类 + 设置去导入入口
|
||||
// - v1.10.1:移除「分享时附带封面图片」开关 + 详情底部分享/插入组间竖向分割线
|
||||
// 运行:node promptlib/tools/harness.mjs (退出码 0 = 全过)
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = path.resolve(HERE, '..')
|
||||
const src = fs.readFileSync(path.join(ROOT, 'src/index.js'), 'utf8')
|
||||
const css = fs.readFileSync(path.join(ROOT, 'styles.css'), 'utf8')
|
||||
let failed = 0
|
||||
const ok = (name, cond) => {
|
||||
if (!cond) failed++
|
||||
console.log((cond ? '✓ ' : '✗ ') + name)
|
||||
}
|
||||
|
||||
// ---- 1) 版本 / manifest ----
|
||||
ok("manifest.version = 1.13.0", /version:\s*'1\.13\.0'/.test(src))
|
||||
ok('package.json version = 1.13.0',
|
||||
JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version === '1.13.0')
|
||||
ok('manifest 已移除「分享时附带封面图片」开关声明',
|
||||
!/shareWithCover:\s*\{\s*type:\s*'boolean'/.test(src))
|
||||
ok('源码不再定义/读取 shareWithCover 设置',
|
||||
!/function shareWithCover \(\)/.test(src) && !/S\.get\('shareWithCover'\)/.test(src))
|
||||
|
||||
// ---- 2) sharePayload 两条显式分支 ----
|
||||
const m = src.match(/ function sharePayload \(p, withCover\) \{[\s\S]*?\n \}\n function shareFileName/)
|
||||
ok('从 src 找到 sharePayload(p, withCover)', !!m)
|
||||
const fnSrc = m ? m[0].replace(/\n function shareFileName$/, '') : ''
|
||||
const sandbox = {
|
||||
SHARE_TAG: 'IWB-PROMPT-SHARE',
|
||||
varsOf: () => [],
|
||||
coverToDataUrl: () => { throw new Error('不该读封面') },
|
||||
Promise, JSON, String, Number, Array, Object,
|
||||
}
|
||||
vm.createContext(sandbox)
|
||||
vm.runInContext(fnSrc, sandbox)
|
||||
const p = { name: '测试词', text: '一只猫', group: '分组A', tags: ['x'], cover: { img: 'a.jpg' } }
|
||||
|
||||
const textPlain = await sandbox.sharePayload(p, false)
|
||||
const bodyPlain = JSON.parse(textPlain.split('\n')[1])
|
||||
ok('文本分享(false):分享文本无 cover 字段', !('cover' in bodyPlain.sharing))
|
||||
ok('文本分享(false):不读封面(stub 抛错未触发)', true)
|
||||
ok('文本分享(false):名字/正文/分组仍在',
|
||||
bodyPlain.sharing.name === '测试词' && bodyPlain.sharing.text === '一只猫' && bodyPlain.sharing.group === '分组A')
|
||||
|
||||
sandbox.coverToDataUrl = () => Promise.resolve('data:image/jpeg;base64,AAAA')
|
||||
const textFile = await sandbox.sharePayload(p, true)
|
||||
const bodyFile = JSON.parse(textFile.split('\n')[1])
|
||||
ok('文件分享(true):分享文本带 cover', bodyFile.sharing.cover === 'data:image/jpeg;base64,AAAA')
|
||||
|
||||
// ---- 3) v1.10.0 UI 契约 ----
|
||||
ok('文本分享复制纯文字(doShareText 用 api.copy)',
|
||||
/function doShareText \(p\)[\s\S]{0,260}api\.copy\(text\)/.test(src))
|
||||
ok('文件分享导出为文件(doShareFile 用 api.exportText)',
|
||||
/function doShareFile \(p\)[\s\S]{0,260}api\.exportText\(shareFileName\(p\), text\)/.test(src))
|
||||
ok('文件名做安全化(过滤 \\/:*?"<>|)',
|
||||
/replace\(\/\[\\\\\/:\*\?"<>\|]\/g, '_'\)/.test(src))
|
||||
ok('剪贴板导入与文件导入共用 importShareItem(1 定义 + 2 调用)',
|
||||
(src.match(/importShareItem\s*\(item\)/g) || []).length >= 3)
|
||||
ok('文件导入走 api.importText()',
|
||||
/function importShareFromFile \(\)[\s\S]{0,160}api\.importText\(\)/.test(src))
|
||||
ok('顶部三按钮:文件 / 文本 / 新建',
|
||||
/text: '文件'[\s\S]{0,200}text: '文本'[\s\S]{0,200}text: '新建'/.test(src))
|
||||
ok('右键菜单已去掉「移动到分组」分类',
|
||||
!/移动到分组/.test(src))
|
||||
ok('右键菜单含 文本分享 / 文件分享(iwb-ctx-item 项)',
|
||||
/iwb-ctx-item', text: '文本分享'[\s\S]{0,260}iwb-ctx-item', text: '文件分享'/.test(src))
|
||||
ok('详情底部含 文本分享 / 文件分享 两按钮',
|
||||
/text: '文本分享'/.test(src) && /text: '文件分享'/.test(src))
|
||||
ok('详情底部分享组与插入组之间是竖向分割线(DOM 顺序:文件分享 → 竖线 → 复制全文)',
|
||||
/footEl\.appendChild\(shareFile\)[\s\S]{0,240}iwb-plp-foot-vsep[\s\S]{0,160}footEl\.appendChild\(cp\)/.test(src))
|
||||
ok('竖线样式:1px 宽 / 18px 高 / 边框色 / 居中',
|
||||
/\.iwb-plp-foot-vsep\s*\{[^}]*width:\s*1px[^}]*height:\s*18px[^}]*align-self:\s*center[^}]*background:\s*var\(--iwb-border\)/.test(css))
|
||||
ok('设置面板不再有单条导入入口(impShareBtn 已移除)',
|
||||
!/impShareBtn/.test(src))
|
||||
ok('旧的「分享…」按钮(带图完整版)已删除',
|
||||
!/text: '分享'/.test(src) && !/function doShare \(p\)/.test(src))
|
||||
|
||||
// ---- 4) v1.9.3 变量着色样式不变量(回归保护)----
|
||||
ok('高亮层恢复显示(不再 display:none)',
|
||||
/\.iwb-plp-ewrap \.iwb-plp-hl\{display:block!important/.test(css))
|
||||
ok('高亮层整层文字透明(不与 textarea 重影)',
|
||||
/\.iwb-plp-ewrap \.iwb-plp-hl\{[^}]*color:transparent!important[^}]*-webkit-text-fill-color:transparent!important/.test(css))
|
||||
ok('变量 span 只画主色背景、不画文字',
|
||||
/\.iwb-plp-hlvar\{[^}]*color:transparent!important[^}]*background:color-mix\(in srgb, var\(--iwb-plp-accent/.test(css))
|
||||
ok('变量 span 不加粗(避开点击偏移根因)',
|
||||
/\.iwb-plp-hlvar\{font-weight:400!important/.test(css))
|
||||
ok('textarea 文字仍可见(-webkit-text-fill-color 兜底)',
|
||||
/\.iwb-plp-etext\{color:var\(--iwb-text[^}]*-webkit-text-fill-color:var\(--iwb-text/.test(css))
|
||||
ok('高亮层与 textarea 滚动条占位一致',
|
||||
/\.iwb-plp-emid \.iwb-plp-ewrap \.iwb-plp-hl\{overflow:hidden!important;scrollbar-gutter:stable\}/.test(css))
|
||||
ok('高亮层跟随 textarea 横向滚动',
|
||||
/hl\.scrollTop = textIn\.scrollTop; hl\.scrollLeft = textIn\.scrollLeft/.test(src))
|
||||
ok('右侧变量名与详情变量用主色呼应',
|
||||
/\.iwb-plp-vname\{color:var\(--iwb-plp-accent/.test(css) && /\.iwb-plp-dvar\{color:var\(--iwb-plp-accent/.test(css))
|
||||
|
||||
// ---- 5) v1.11.0 封面文件治理(P1)----
|
||||
// 目标:① 保存/上传时把内联 base64 落成文件;② 孤儿封面能被回收;③ 回收不能误删。
|
||||
// 纯文本断言跑不了真实 FS ⇒ 这里用「函数抽出来 + 假 fileApi」跑行为。
|
||||
ok('封面命名统一走 coverFileName(哈希只在它内部实现一次)',
|
||||
/function coverFileName \(dataUrl\)/.test(src) && (src.match(/var h = 5381/g) || []).length === 1 && (src.match(/coverFileName\(/g) || []).length >= 6)
|
||||
ok('保存路径先落文件(ensureCoverFile 包住 doSave)',
|
||||
/function doSave \(\)[\s\S]{0,600}ensureCoverFile\(c\.cover\)/.test(src))
|
||||
ok('上传封面即落文件(不再把 dataURL 写回 draft.cover)',
|
||||
/api\.putCover\([\s\S]{0,400}ensureCoverFile\(r\.ref\)/.test(src))
|
||||
ok('删词条后安排一次回收', /已删除'[\s\S]{0,80}scheduleCoverGc\(/.test(src))
|
||||
ok('启动加载后安排一次回收(等 convertInlineCovers 写完)',
|
||||
/convertInlineCovers\(\)[\s\S]{0,120}scheduleCoverGc\(4000\)/.test(src))
|
||||
ok('自动回收有「数据来源」闸门(不是插件 JSON 读来的就不删)',
|
||||
/!o\.manual && !dataFromPlugin\) return Promise\.resolve\(\{ removed: 0, bytes: 0, skipped: 'no-source' \}\)/.test(src))
|
||||
ok('keep 为空时不删(空集合 = 全删的形状)',
|
||||
/if \(!kept && !o\.manual\) return Promise\.resolve\(\{ removed: 0, bytes: 0, skipped: 'empty' \}\)/.test(src))
|
||||
ok('只删图片扩展名文件', src.includes('/\\.(jpg|jpeg|png|webp)$/i.test(name)'))
|
||||
ok('设置页有显式清理入口 + 现读一次数据',
|
||||
/text: '清理未引用封面'/.test(src) && /plpGcCoverFiles\(FA, plpCoverNamesOf\(state\.prompts\), \{ manual: true \}\)/.test(src))
|
||||
ok('pending(刚 put 未被引用)不会被回收',
|
||||
/Object\.keys\(pendingCoverNames\)\.forEach\(function \(n\) \{ names\.push\(n\) \}\)/.test(src))
|
||||
|
||||
// 行为:抽出 plpGcCoverFiles 本体,用假 fileApi 验证「只删未被引用的图片文件」
|
||||
const gcMatch = src.match(/ function plpGcCoverFiles \(FA, keepNames, opts\) \{[\s\S]*?\n \}\n/)
|
||||
ok('从 src 抽出 plpGcCoverFiles', !!gcMatch)
|
||||
if (gcMatch) {
|
||||
const removed = []
|
||||
const fakeFA = {
|
||||
list: async () => [
|
||||
{ name: 'cused1.jpg', size: 100 },
|
||||
{ name: 'corphan1.jpg', size: 200 },
|
||||
{ name: 'cshared.jpg', size: 300 },
|
||||
{ name: 'notes.txt', size: 1 },
|
||||
],
|
||||
remove: async (name) => { removed.push(name); return { ok: true } },
|
||||
}
|
||||
const gcSandbox = { Promise, JSON, String, Number, Array, Object, RegExp, console }
|
||||
vm.createContext(gcSandbox)
|
||||
vm.runInContext('var PLP_GC_BUSY = false\n' + gcMatch[0] + '\nthis.gc = plpGcCoverFiles', gcSandbox)
|
||||
const r1 = await gcSandbox.gc(fakeFA, ['cused1.jpg'], {})
|
||||
ok('回收:只删未引用图片(保留引用项与非图片文件)',
|
||||
JSON.stringify(removed) === '["corphan1.jpg","cshared.jpg"]')
|
||||
ok('回收:返回删除数与字节数', r1.removed === 2 && r1.bytes === 500)
|
||||
const r2 = await gcSandbox.gc(fakeFA, [], {})
|
||||
ok('回收:keep 为空且非人工 ⇒ 不删(skipped=empty)', r2.skipped === 'empty' && r2.removed === 0)
|
||||
const r3 = await gcSandbox.gc(null, [], {})
|
||||
ok('回收:无文件能力 ⇒ skipped=no-fs', r3.skipped === 'no-fs')
|
||||
}
|
||||
|
||||
// ---- 8) v1.12.0 变量四字段(名称/内容/说明/占位符)+ 节点多行变量框 ----
|
||||
ok('节点变量框已换成 textarea 且显式 rows=1(默认 2 行会把单行撑成两行高)',
|
||||
src.includes("el('textarea', { class: 'iwb-input iwb-plp-nin', rows: '1'"))
|
||||
ok('自动增高三步:先 height=auto 再读 scrollHeight',
|
||||
/ta\.style\.height = 'auto'[\s\S]{0,160}scrollHeight/.test(src))
|
||||
ok('节点变量框拦 pointerdown(宿主白名单不含 textarea,否则拖选文字会拖动节点)',
|
||||
src.includes("inp.addEventListener('pointerdown'") && src.includes('e.stopPropagation()'))
|
||||
ok('节点变量框只在内容溢出时拦滚轮(不破坏画布缩放)',
|
||||
src.includes('if (inp.scrollHeight > inp.clientHeight + 1) e.stopPropagation()'))
|
||||
ok('v1.13.0 插入变量时选中的原文直接当占位符(塞不进 {} 才退到变量N)',
|
||||
src.includes('var embed = contentKeyOf(picked)') && src.includes("if (picked) varEd.preset(name, { def: picked })"))
|
||||
ok('v1.12.3 编辑器只有三个输入项(名称/内容/说明),占位符框已移除',
|
||||
src.includes("'变量名称(节点上最多显示 4 字)'") &&
|
||||
src.includes("class: 'iwb-input iwb-plp-vdef', rows: '3'") &&
|
||||
src.includes("placeholder: '说明(可选)'") &&
|
||||
!src.includes('iwb-plp-vkey') && !src.includes('占位符(≤'))
|
||||
ok('v1.12.3 变量区的功能性说明文案已删(顶部 hint / 橙色 tip / 底部 khint)',
|
||||
!src.includes('名称只影响显示 · 内容可多行 · 与正文双向同步') &&
|
||||
!src.includes('iwb-plp-vtip') && !src.includes('iwb-plp-vkhint'))
|
||||
ok('sync 保留 label 与 def(旧实现每次 sync 吃掉名称与内容)',
|
||||
src.includes('label: prev.label, desc: prev.desc, def: prev.def'))
|
||||
ok('v1.13.0 内容框显示「内容」,空时退回正文里的键',
|
||||
src.includes('function bodyOf (v) { return v.def || v.key }'))
|
||||
ok('v1.12.3 新建节点不再预填 vars(输入框默认为空)',
|
||||
src.includes('vars: {}, cover:') && !src.includes('vars: defaultVarsOf'))
|
||||
ok('v1.12.3 节点 placeholder 取「说明 → 内容」(不填说明时展示内容文案)',
|
||||
src.includes('placeholder: v.desc || v.def ||'))
|
||||
ok('v1.12.3 节点输入框默认空(不再回退 def 当 value)',
|
||||
src.includes("inp.value = String((d.vars && d.vars[v.key]) || '')"))
|
||||
ok('v1.12.3 留空时输出用内容兜底(否则 outputText 会把这段从提示词删掉)',
|
||||
src.includes('vv[k] = st.inputs[k].value || st.defOf(k)') &&
|
||||
src.includes('eff[k] = String(raw[k] || \'\') || defOf(k)'))
|
||||
ok('v1.12.3 vars 只存原始输入(空就是空,下次打开仍为空)',
|
||||
src.includes('var patch = { vars: raw, text: outputText'))
|
||||
ok('v1.12.3 「未填」只统计既没填也没内容的变量',
|
||||
src.includes('!st.defOf(k).trim()) missing++'))
|
||||
ok('v1.12.3 defOf 挂在 st 上(scheduleUpdate 与 syncTplNode 是两个函数,局部声明会 ReferenceError)',
|
||||
src.includes('st.defOf = function (k)') &&
|
||||
src.includes("var defOf = (typeof st.defOf === 'function') ? st.defOf"))
|
||||
ok('v1.12.3 空框按 placeholder 折行量高度(提示第二行不被裁)',
|
||||
src.includes('ta.value = ph; restore = true') && src.includes('if (restore) { ta.value = \'\''))
|
||||
ok('样式:变量行不再是固定 26px 单行',
|
||||
!css.includes('.iwb-plp-nrow{display:flex;align-items:center;gap:6px;height:26px}') &&
|
||||
css.includes('.iwb-plp-nrow{display:flex;align-items:flex-start;gap:6px;min-height:26px}'))
|
||||
ok('样式:变量框不再固定 24px 高',
|
||||
!css.includes('.iwb-plp-nin{flex:1;height:24px') && css.includes('min-height:24px'))
|
||||
ok('样式:收起态摘要与三角已定义',
|
||||
css.includes('.iwb-plp-vsum{') && css.includes('.iwb-plp-vcaret{'))
|
||||
ok('样式:内容多行框 3 行起步(min-height 66px,overflow 由 JS 控制)',
|
||||
css.includes('.iwb-plp-vdef{height:auto;min-height:66px'))
|
||||
|
||||
ok('v1.13.0 节点变量标签列定宽 4 字(56px),输入框左边缘才对齐',
|
||||
css.includes('.iwb-plp-nk{flex:0 0 56px;width:56px;max-width:56px') &&
|
||||
!css.includes('.iwb-plp-nk{flex:0 0 auto'))
|
||||
ok('v1.13.0 名称框提示说明「节点上最多显示 4 字」',
|
||||
src.includes("'变量名称(节点上最多显示 4 字)'"))
|
||||
|
||||
// ---- 10) v1.13.0 名称 ⇄ 正文联动 + 内容框 10 行 ----
|
||||
ok('v1.13.0 内容框上限 10 行(VDEF_MAX 212,用户要求 +4 行)',
|
||||
/var VDEF_MAX = 212/.test(src) && !/var VDEF_MAX = 132/.test(src))
|
||||
ok('v1.13.0 占位符上限与所有正则一致(KEY_MAX 60,5 处 {1,60})',
|
||||
/var KEY_MAX = 60/.test(src) &&
|
||||
(src.match(/\{1,60\}/g) || []).length >= 6 &&
|
||||
!/\{1,24\}/.test(src))
|
||||
ok('v1.13.0 内容 → 正文联动:改内容即改 {…}(curText 取实时正文,不吃防抖的旧值)',
|
||||
src.includes('function curText ()') &&
|
||||
src.includes('var next = contentKeyOf(area.value)') &&
|
||||
src.includes("cur.split('{' + old + '}').join('{' + next + '}')"))
|
||||
ok('v1.13.0 名称只改节点显示,不动正文',
|
||||
/nameIn\.addEventListener\('input', function \(\) \{\s*\n\s*v\.label = nameIn\.value\s*\n\s*title\.textContent = v\.label \|\| v\.key/.test(src))
|
||||
ok('v1.13.0 内容塞不进 {} 时保留原键 + 摘要里提示(绝不硬塞,免得变量被识别掉)',
|
||||
src.includes('正文未同步(需单行 ≤') &&
|
||||
/v1\.13\.0: 不|v1\.13\.0:不再在打开时改写正文/.test(src))
|
||||
ok('v1.13.0 抽屉把实时正文 getText 交给编辑器',
|
||||
src.includes('getText: function () { return textIn.value }'))
|
||||
|
||||
// ---- 9) v1.12.2 搜索框常驻(中文输入法组合态不被重建打断)----
|
||||
ok('v1.12.2 搜索框不再在 render 里 clear(fixed) 重建(render 只清其余节点)',
|
||||
!/function render \(\) \{\s*\n\s*clear\(fixed\); clear\(scrollBox\)/.test(src) &&
|
||||
src.includes('Array.prototype.slice.call(fixed.children).forEach'))
|
||||
ok('v1.12.2 搜索框只创建一次(ensureSearchRow 复用同一个节点)',
|
||||
src.includes('function ensureSearchRow ()') && src.includes('if (searchRow) return searchRow'))
|
||||
ok('v1.12.2 输入法组合态:compositionstart/end + 组合中不重排',
|
||||
src.includes("searchEl.addEventListener('compositionstart'") &&
|
||||
src.includes("searchEl.addEventListener('compositionend'") &&
|
||||
/composing \|\| \(e && e\.isComposing\)\) return/.test(src))
|
||||
ok('v1.12.2 结果重排走 120ms 防抖(打字不再逐键全量重建)',
|
||||
src.includes('function scheduleResults ()') && src.includes('setTimeout(function () { searchTimer = 0; render() }, 120)'))
|
||||
ok('v1.12.2 清空搜索后焦点回到搜索框',
|
||||
/query = ''; render\(\)\s*\n\s*if \(searchEl\)/.test(src))
|
||||
|
||||
console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过')
|
||||
if (failed) process.exitCode = 1
|
||||
@@ -0,0 +1,164 @@
|
||||
// 搜索框中文输入法回归验证(v1.12.2 起)
|
||||
// 为什么单独一个脚本:宿主 CI 里没有 playwright,跑不进 harness 门禁;但改搜索框时值得手动跑一次。
|
||||
// 依赖宿主仓的 playwright:image-workbench-desktop/node_modules/playwright。
|
||||
// 用法:node promptlib/tools/plp-search-ime-check.mjs
|
||||
// PLP_SRC=/path/to/other/index.js node promptlib/tools/plp-search-ime-check.mjs # 对照旧版
|
||||
// 覆盖:组合态中搜索框不被重建 / 不按拼音过滤 / 光标不跳末尾 / 上屏后过滤生效
|
||||
// CDP Input.imeSetComposition 走真实输入法通道
|
||||
// 验证 promptlib 搜索框:中文输入法组合态不再被打断(v1.12.2)
|
||||
// 做法:真实 Chromium 加载插件源码 + 最小宿主 stub,挂载面板后
|
||||
// ① 模拟 compositionstart → input(拼音) → compositionend(中文)
|
||||
// ② 用 CDP Input.imeSetComposition 走真实输入法通道
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
// playwright 装在宿主仓(插件仓没有 node_modules);按本级目录推,别写死绝对路径
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const PW = pathToFileURL(path.resolve(HERE, '..', '..', '..', 'image-workbench-desktop', 'node_modules', 'playwright', 'index.mjs')).href
|
||||
const { chromium } = await import(PW)
|
||||
|
||||
const SRC = process.env.PLP_SRC || path.resolve(HERE, '..', 'src', 'index.js')
|
||||
|
||||
const browser = await chromium.launch()
|
||||
const page = await browser.newPage({ viewport: { width: 900, height: 700 } })
|
||||
const errors = []
|
||||
page.on('pageerror', (e) => errors.push(String(e)))
|
||||
|
||||
await page.setContent('<!doctype html><html><body style="margin:0"><div id="host"></div></body></html>')
|
||||
|
||||
// 宿主 stub:捕获 register → 拿到 factory
|
||||
await page.evaluate(() => {
|
||||
window.IWBPluginHost = { register: (meta, factory) => { window.__reg = { meta, factory } } }
|
||||
})
|
||||
|
||||
await page.addScriptTag({ path: SRC })
|
||||
|
||||
const mountInfo = await page.evaluate(() => {
|
||||
const prompts = [
|
||||
{ id: 'a', name: '水光肌底妆', text: '水光 底妆 提亮 通透', group: '美妆' },
|
||||
{ id: 'b', name: '复古胶片', text: '胶片 颗粒 暖调 怀旧', group: '风格' },
|
||||
{ id: 'c', name: '水果静物', text: '水果 静物 清新', group: '美妆' },
|
||||
{ id: 'd', name: '水波纹背景', text: '水波 纹理 背景', group: '风格' },
|
||||
]
|
||||
const groups = [{ id: '美妆', name: '美妆' }, { id: '风格', name: '风格' }]
|
||||
const data = { schemaVersion: 3, prompts, groups }
|
||||
const ctx = {
|
||||
data: {
|
||||
read: async () => data,
|
||||
write: async () => ({ ok: true }),
|
||||
set: async () => ({ ok: true }),
|
||||
get: async () => null,
|
||||
},
|
||||
promptlib: {
|
||||
list: async () => ({ prompts, groups }),
|
||||
save: async () => ({ ok: true }),
|
||||
insert: async () => ({ ok: true }),
|
||||
notify: () => {},
|
||||
onChanged: () => () => {},
|
||||
filePut: async () => ({ ok: true }),
|
||||
fileGet: async () => '',
|
||||
fileList: async () => [],
|
||||
fileRemove: async () => ({ ok: true }),
|
||||
fileStat: async () => ({ count: 0, bytes: 0 }),
|
||||
},
|
||||
files: {
|
||||
put: async () => ({ ok: true }),
|
||||
get: async () => '',
|
||||
list: async () => [],
|
||||
remove: async () => ({ ok: true }),
|
||||
stat: async () => ({ count: 0, bytes: 0 }),
|
||||
},
|
||||
storage: { set: () => {}, get: () => null },
|
||||
ui: { registerPanel: (p) => { window.__panel = p }, toast: () => {} },
|
||||
}
|
||||
window.__reg.factory(ctx)
|
||||
const host = document.getElementById('host')
|
||||
window.__dispose = window.__panel.mount(host)
|
||||
return { meta: window.__reg.meta.version, hasPanel: !!window.__panel }
|
||||
})
|
||||
console.log('插件版本', mountInfo.meta, '面板已注册', mountInfo.hasPanel)
|
||||
|
||||
await page.waitForTimeout(600)
|
||||
|
||||
const countCards = () => page.evaluate(() => document.querySelectorAll('.iwb-plp-card').length)
|
||||
const before = await countCards()
|
||||
console.log('初始卡片数', before)
|
||||
|
||||
// ---- ① 合成事件:组合态期间搜索框不能被重建、列表不能按拼音过滤 ----
|
||||
const synth = await page.evaluate(async () => {
|
||||
const host = document.getElementById('host')
|
||||
const el = host.querySelector('input.iwb-grow')
|
||||
el.__mark = 'same-node'
|
||||
el.focus()
|
||||
el.setSelectionRange(2, 2)
|
||||
|
||||
const fire = (type, extra) => el.dispatchEvent(new (type === 'input' ? InputEvent : CompositionEvent)(type, Object.assign({ bubbles: true }, extra || {})))
|
||||
|
||||
fire('compositionstart', { data: '' })
|
||||
// 拼音逐个上屏:真实输入法每敲一个字母都会派发 isComposing=true 的 input
|
||||
el.value = '水'
|
||||
fire('input', { isComposing: true, data: 'shui' })
|
||||
el.value = '水s'
|
||||
fire('input', { isComposing: true, data: 'shuis' })
|
||||
await new Promise((r) => setTimeout(r, 250)) // 超过 120ms 防抖窗口
|
||||
|
||||
const during = {
|
||||
sameNode: host.querySelector('input.iwb-grow') === el,
|
||||
connected: el.isConnected,
|
||||
mark: el.__mark,
|
||||
cards: document.querySelectorAll('.iwb-plp-card').length,
|
||||
selStart: el.selectionStart,
|
||||
}
|
||||
|
||||
// 上屏
|
||||
el.value = '水'
|
||||
el.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '水' }))
|
||||
await new Promise((r) => setTimeout(r, 300))
|
||||
|
||||
const after = {
|
||||
sameNode: host.querySelector('input.iwb-grow') === el,
|
||||
value: el.value,
|
||||
cards: document.querySelectorAll('.iwb-plp-card').length,
|
||||
names: Array.from(document.querySelectorAll('.iwb-plp-t')).map((n) => n.textContent),
|
||||
}
|
||||
return { during, after }
|
||||
})
|
||||
console.log('组合态中 :', JSON.stringify(synth.during))
|
||||
console.log('上屏之后 :', JSON.stringify(synth.after))
|
||||
|
||||
// ---- ② CDP 真实输入法通道 ----
|
||||
const cdp = await page.context().newCDPSession(page)
|
||||
await page.evaluate(() => { const el = document.querySelector('#host input.iwb-grow'); el.value = ''; el.focus() })
|
||||
await cdp.send('Input.imeSetComposition', { text: 'shui', selectionStart: 4, selectionEnd: 4 })
|
||||
await page.waitForTimeout(120)
|
||||
const composingState = await page.evaluate(() => document.querySelector('#host input.iwb-grow').value)
|
||||
await cdp.send('Input.insertText', { text: '水' })
|
||||
await page.waitForTimeout(300)
|
||||
const imeState = await page.evaluate(() => ({
|
||||
value: document.querySelector('#host input.iwb-grow').value,
|
||||
cards: document.querySelectorAll('.iwb-plp-card').length,
|
||||
names: Array.from(document.querySelectorAll('.iwb-plp-t')).map((n) => n.textContent),
|
||||
}))
|
||||
console.log('imeSetComposition 后 value =', JSON.stringify(composingState))
|
||||
console.log('真实输入法提交后 :', JSON.stringify(imeState))
|
||||
|
||||
// ---- 判定 ----
|
||||
const checks = [
|
||||
['组合态中搜索框未被重建(同一节点)', synth.during.sameNode === true],
|
||||
['组合态中搜索框仍在文档里(没被移除)', synth.during.connected === true],
|
||||
['组合态中保留自定义属性(未被克隆替换)', synth.during.mark === 'same-node'],
|
||||
['组合态中不按拼音过滤(卡片数不变)', synth.during.cards === before],
|
||||
['组合态中光标位置不被打到末尾', synth.during.selStart === 2],
|
||||
['上屏后搜索框仍是同一节点', synth.after.sameNode === true],
|
||||
['上屏后搜索框值 = 水', synth.after.value === '水'],
|
||||
['上屏后过滤到 3 条含水的结果', synth.after.cards === 3],
|
||||
['真实输入法:组合态拼音留在框内', composingState === 'shui'],
|
||||
['真实输入法:提交后可搜到 3 条', imeState.cards === 3],
|
||||
]
|
||||
|
||||
let failed = 0
|
||||
for (const [name, okv] of checks) { if (!okv) failed++; console.log((okv ? '✓ ' : '✗ ') + name) }
|
||||
if (errors.length) { console.log('页面异常:', errors.slice(0, 3)) }
|
||||
console.log(failed ? `✗ ${failed} 项失败` : '✓ 全部通过')
|
||||
await page.screenshot({ path: '/tmp/plp-search.png' })
|
||||
await browser.close()
|
||||
process.exit(failed ? 1 : 0)
|
||||
@@ -0,0 +1,206 @@
|
||||
// 变量编辑器 + 模板节点 渲染验证(v1.12.3)
|
||||
// 真实 Chromium 挂载 promptlib 面板,走「新建」弹窗与模板节点 render,
|
||||
// 断言用户能看到的三件事:
|
||||
// ① 变量区只有 名称 / 内容 / 说明 三个输入项,没有占位符、没有功能性说明文案
|
||||
// ② 内容框是多行(3 行起步,不再被压成一行裁切)
|
||||
// ③ 节点输入框默认为空,不填说明时灰字显示「内容」文案
|
||||
// 依赖宿主仓 playwright:node promptlib/tools/plp-vars-editor-check.mjs
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const PW = pathToFileURL(path.resolve(HERE, '..', '..', '..', 'image-workbench-desktop', 'node_modules', 'playwright', 'index.mjs')).href
|
||||
const { chromium } = await import(PW)
|
||||
const SRC = process.env.PLP_SRC || path.resolve(HERE, '..', 'src', 'index.js')
|
||||
const CSS = path.resolve(HERE, '..', 'styles.css')
|
||||
|
||||
const browser = await chromium.launch()
|
||||
const page = await browser.newPage({ viewport: { width: 1080, height: 900 }, deviceScaleFactor: 2 })
|
||||
const errors = []
|
||||
page.on('pageerror', (e) => errors.push(String(e)))
|
||||
|
||||
await page.setContent('<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0"><div id="host"></div><div id="nodehost"></div></body></html>')
|
||||
await page.addStyleTag({ path: CSS })
|
||||
await page.evaluate(() => {
|
||||
window.IWBPluginHost = { register: (meta, factory) => { window.__reg = { meta, factory } } }
|
||||
})
|
||||
await page.addScriptTag({ path: SRC })
|
||||
|
||||
const info = await page.evaluate(() => {
|
||||
const prompts = [{ id: 'a', name: '示例', text: '风格 {主色调}', group: '默认' }]
|
||||
const groups = [{ id: '默认', name: '默认' }]
|
||||
const data = { schemaVersion: 3, prompts, groups }
|
||||
let nodeDef = null
|
||||
const ctx = {
|
||||
data: { read: async () => data, write: async () => ({ ok: true }), set: async () => ({ ok: true }), get: async () => null },
|
||||
promptlib: {
|
||||
list: async () => ({ prompts, groups }), save: async () => ({ ok: true }), insert: async () => ({ ok: true }),
|
||||
notify: () => {}, onChanged: () => () => {},
|
||||
filePut: async () => ({ ok: true }), fileGet: async () => '', fileList: async () => [], fileRemove: async () => ({ ok: true }), fileStat: async () => ({ count: 0, bytes: 0 }),
|
||||
},
|
||||
files: { put: async () => ({ ok: true }), get: async () => '', list: async () => [], remove: async () => ({ ok: true }), stat: async () => ({ count: 0, bytes: 0 }) },
|
||||
storage: { set: () => {}, get: () => null },
|
||||
ui: { registerPanel: (p) => { window.__panel = p }, toast: () => {} },
|
||||
nodes: { register: (def) => { nodeDef = def } },
|
||||
canvas: { screenToWorld: (x, y) => ({ x, y }) },
|
||||
canvasWrite: { createNode: () => 'n1', createImageNode: () => 'n2' },
|
||||
}
|
||||
window.__reg.factory(ctx)
|
||||
window.__panel.mount(document.getElementById('host'))
|
||||
|
||||
// 模板节点:同样用真实 render
|
||||
const node = {
|
||||
id: 'n1',
|
||||
data: {
|
||||
name: '测试模板',
|
||||
tpl: '风格 {主色调},背景 {留白}',
|
||||
vdefs: [
|
||||
{ key: '主色调', label: '主色调', desc: '', def: '橙红 金色描边' },
|
||||
{ key: '留白', label: '留白', desc: '画面留白比例', def: '四周留 10%' },
|
||||
],
|
||||
vars: {}, // 默认为空(新节点就是这个状态)
|
||||
outKind: 'prompt',
|
||||
},
|
||||
}
|
||||
// 收集节点写回的 patch —— 用户最关心的「留空时提示词还有没有内容」只能从这里看
|
||||
window.__patches = []
|
||||
const props = { onUpdate: (id, patch) => { window.__patches.push(patch) }, onSelect: () => {}, selected: false }
|
||||
nodeDef.render(node, props, document.getElementById('nodehost'))
|
||||
return { version: window.__reg.meta.version, nodeTitle: nodeDef.title }
|
||||
})
|
||||
console.log('插件版本', info.version, '| 节点', info.nodeTitle)
|
||||
|
||||
await page.waitForTimeout(500)
|
||||
|
||||
// ---- 打开「新建」弹窗,正文里写一段带变量的提示词 ----
|
||||
await page.evaluate(() => {
|
||||
const btn = Array.from(document.querySelectorAll('#host button')).find((b) => b.textContent.trim() === '新建')
|
||||
btn.click()
|
||||
})
|
||||
await page.waitForTimeout(400)
|
||||
await page.evaluate(() => {
|
||||
const ta = document.querySelector('.iwb-plp-etext')
|
||||
ta.value = '一个顶部金色、顶部和底部有金色边缘、底部悬挂红色,整体风格 {主色调}'
|
||||
ta.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
await page.waitForTimeout(300)
|
||||
// 展开第一个变量
|
||||
await page.evaluate(() => {
|
||||
const row = document.querySelector('.iwb-plp-vrow2')
|
||||
if (row) row.click()
|
||||
})
|
||||
await page.waitForTimeout(400)
|
||||
|
||||
const dom = await page.evaluate(() => {
|
||||
const q = (s) => document.querySelectorAll(s).length
|
||||
const area = document.querySelector('.iwb-plp-vdef')
|
||||
const nodeIns = Array.from(document.querySelectorAll('#nodehost .iwb-plp-nin'))
|
||||
const text = document.querySelector('.iwb-plp-vars').textContent
|
||||
return {
|
||||
counts: { name: q('.iwb-plp-vname'), def: q('.iwb-plp-vdef'), desc: q('.iwb-plp-vdesc'), key: q('.iwb-plp-vkey') },
|
||||
areaH: area ? Math.round(area.getBoundingClientRect().height) : 0,
|
||||
areaRows: area ? area.getAttribute('rows') : '',
|
||||
varText: text.replace(/\s+/g, ' ').trim().slice(0, 80),
|
||||
nodeInputs: nodeIns.map((n) => ({ tag: n.tagName, value: n.value, ph: n.placeholder })),
|
||||
nodeLabels: Array.from(document.querySelectorAll('#nodehost .iwb-plp-nk')).map((n) => n.textContent),
|
||||
}
|
||||
})
|
||||
console.log('编辑器输入项', JSON.stringify(dom.counts))
|
||||
console.log('内容框高 / rows =', dom.areaH, '/', dom.areaRows)
|
||||
console.log('变量区文案 =', JSON.stringify(dom.varText))
|
||||
console.log('节点输入框 =', JSON.stringify(dom.nodeInputs))
|
||||
console.log('节点标签 =', JSON.stringify(dom.nodeLabels))
|
||||
|
||||
// ---- v1.13.0:改内容 ⇒ 正文 {…} 同步(用户报的「没关联」)+ 输入框不失焦 ----
|
||||
const link = await page.evaluate(async () => {
|
||||
const wait = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
const area = document.querySelector('.iwb-plp-vdef')
|
||||
const nameIn = document.querySelector('.iwb-plp-vname')
|
||||
const ta = document.querySelector('.iwb-plp-etext')
|
||||
const before = ta.value
|
||||
area.focus()
|
||||
area.value = '主色'
|
||||
area.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
await wait(80)
|
||||
const afterContent = ta.value
|
||||
const focusOnArea = document.activeElement === area
|
||||
nameIn.value = '主面积色'
|
||||
nameIn.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
await wait(80)
|
||||
return {
|
||||
before,
|
||||
afterContent,
|
||||
afterName: ta.value,
|
||||
focused: focusOnArea,
|
||||
hl: document.querySelectorAll('.iwb-plp-hlvar').length,
|
||||
}
|
||||
})
|
||||
console.log('改内容前正文 =', JSON.stringify(link.before), '→', JSON.stringify(link.afterContent))
|
||||
|
||||
// ---- v1.13.0:内容框最高 10 行(212px)后框内滚动 ----
|
||||
const areaMax = await page.evaluate(() => {
|
||||
const area = document.querySelector('.iwb-plp-vdef')
|
||||
area.value = Array.from({ length: 20 }, (_, i) => '第' + (i + 1) + '行内容').join('\n')
|
||||
area.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
return { h: Math.round(area.getBoundingClientRect().height), scroll: area.scrollHeight > area.clientHeight + 1 }
|
||||
})
|
||||
// ---- v1.13.0:节点变量名列定宽 4 字(56px)----
|
||||
const nkWidth = await page.evaluate(() => {
|
||||
const nk = document.querySelector('#nodehost .iwb-plp-nk')
|
||||
return nk ? Math.round(nk.getBoundingClientRect().width) : 0
|
||||
})
|
||||
console.log('内容框封顶高 =', areaMax.h, '| 滚动 =', areaMax.scroll, '| 节点名宽 =', nkWidth)
|
||||
|
||||
// ---- 留空 / 填写 / 再清空:看节点写回的 text 与 vars ----
|
||||
const flow = await page.evaluate(async () => {
|
||||
const ta = document.querySelectorAll('#nodehost .iwb-plp-nin')[0]
|
||||
const wait = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
// 已填:用用户输入
|
||||
ta.value = '深蓝'
|
||||
ta.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
await wait(420)
|
||||
const filled = window.__patches[window.__patches.length - 1]
|
||||
// 清空:回到内容兜底
|
||||
ta.value = ''
|
||||
ta.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
await wait(420)
|
||||
const cleared = window.__patches[window.__patches.length - 1]
|
||||
return {
|
||||
filledText: filled && filled.text,
|
||||
filledVars: filled && filled.vars,
|
||||
clearedText: cleared && cleared.text,
|
||||
clearedVars: cleared && cleared.vars,
|
||||
}
|
||||
})
|
||||
console.log('填写后 text =', JSON.stringify(flow.filledText))
|
||||
console.log('清空后 text =', JSON.stringify(flow.clearedText), '| vars =', JSON.stringify(flow.clearedVars))
|
||||
|
||||
await page.screenshot({ path: '/tmp/plp-vars-1123.png', fullPage: true })
|
||||
|
||||
const checks = [
|
||||
['编辑器只有 名称/内容/说明 三项(无占位符框)', dom.counts.key === 0 && dom.counts.name === 1 && dom.counts.def === 1 && dom.counts.desc === 1],
|
||||
['内容框 rows=3', dom.areaRows === '3'],
|
||||
['内容框实际高度 ≥ 60px(3 行,不再被压成一行)', dom.areaH >= 60],
|
||||
['变量区没有功能性说明文案', !/名称只影响显示|与正文双向同步/.test(dom.varText)],
|
||||
['变量区没有「占位符」字眼', !/占位符/.test(dom.varText)],
|
||||
['节点输入框默认为空(2 个都是空 value)', dom.nodeInputs.length === 2 && dom.nodeInputs.every((n) => n.value === '')],
|
||||
['无说明时 placeholder = 内容文案', dom.nodeInputs[0] && dom.nodeInputs[0].ph === '橙红 金色描边'],
|
||||
['有说明时 placeholder = 说明', dom.nodeInputs[1] && dom.nodeInputs[1].ph === '画面留白比例'],
|
||||
['节点仍是 textarea(可多行)', dom.nodeInputs.every((n) => n.tag === 'TEXTAREA')],
|
||||
['填写后提示词用填写值', /深蓝/.test(flow.filledText || '') && !/橙红 金色描边/.test(flow.filledText || '')],
|
||||
['填写值写进 vars', flow.filledVars && flow.filledVars['主色调'] === '深蓝'],
|
||||
['清空后提示词回到「内容」兜底(不丢内容)', /橙红 金色描边/.test(flow.clearedText || '') && !/\{主色调\}/.test(flow.clearedText || '')],
|
||||
['清空后 vars 里是空串(输入框下次仍为空)', flow.clearedVars && flow.clearedVars['主色调'] === ''],
|
||||
['v1.13.0 改内容 ⇒ 正文 {…} 同步改名(联动)', /\{主色调\}/.test(link.before) && /\{主色\}/.test(link.afterContent) && !/\{主色调\}/.test(link.afterContent)],
|
||||
['v1.13.0 改内容时高亮块仍在(正文重绘后不丢色)', link.hl >= 1],
|
||||
['v1.13.0 改内容时焦点留在内容框(不重绘整行)', link.focused === true],
|
||||
['v1.13.0 改名称不动正文(名称只影响节点显示)', link.afterName === link.afterContent],
|
||||
['v1.13.0 内容框最多 10 行(约 222px 盒高)后框内滚动', areaMax.h > 200 && areaMax.h <= 230 && areaMax.scroll === true],
|
||||
['v1.13.0 节点变量名列定宽 4 字(56px)', nkWidth === 56],
|
||||
]
|
||||
let failed = 0
|
||||
for (const [name, okv] of checks) { if (!okv) failed++; console.log((okv ? '✓ ' : '✗ ') + name) }
|
||||
if (errors.length) console.log('页面异常:', errors.slice(0, 3))
|
||||
console.log(failed ? `✗ ${failed} 项失败` : '✓ 全部通过')
|
||||
await browser.close()
|
||||
process.exit(failed ? 1 : 0)
|
||||
@@ -0,0 +1,152 @@
|
||||
// promptlib v1.12.0 变量编辑器行为测试(纯 node + 极简 DOM stub)
|
||||
// 覆盖三件静态断言看不出来的事:
|
||||
// 1) 输入名称/内容后 list() 带 label / def
|
||||
// 2) sync 之后 label / def 不被吃掉(旧实现会)
|
||||
// 3) v1.13.0:正文 {} 里放的就是内容 —— 改内容,正文跟着改;名称只影响节点显示
|
||||
// 运行:node promptlib/tools/vars-editor-test.mjs
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = path.resolve(HERE, '..')
|
||||
const src = fs.readFileSync(path.join(ROOT, 'src/index.js'), 'utf8')
|
||||
|
||||
let failed = 0
|
||||
const ok = (name, cond, extra) => { if (!cond) failed++; console.log((cond ? '✓ ' : '✗ ') + name + (cond ? '' : ' » ' + (extra || ''))) }
|
||||
|
||||
// ---- 从真实源码里切出:变量检测/自适应/长名判定 + 变量编辑器 ----
|
||||
const helpers = src.slice(src.indexOf(' function detectVars (text) {'), src.indexOf(' // 提交给下游/生图的文本'))
|
||||
const editorStart = src.indexOf(' // ===== v1.5.0:变量编辑器')
|
||||
const editorEndMark = ' return { node: box, sync: sync, preset: preset, list: function () { return list }, values: values }\n }'
|
||||
const editorEnd = src.indexOf(editorEndMark)
|
||||
if (editorStart < 0 || editorEnd < 0) { console.error('✗ 找不到 makeVarsEditor 源码段'); process.exit(1) }
|
||||
const editor = src.slice(editorStart, editorEnd + editorEndMark.length)
|
||||
|
||||
// ---- 极简 DOM stub(只实现编辑器用到的 API)----
|
||||
function makeEl (tag, attrs, ...kids) {
|
||||
const n = {
|
||||
tag,
|
||||
className: (attrs && attrs.class) || '',
|
||||
textContent: (attrs && attrs.text != null) ? String(attrs.text) : '',
|
||||
title: '',
|
||||
value: '',
|
||||
rows: (attrs && attrs.rows != null) ? String(attrs.rows) : '',
|
||||
style: {},
|
||||
children: [],
|
||||
listeners: {},
|
||||
}
|
||||
n.appendChild = (c) => { n.children.push(c); return c }
|
||||
n.addEventListener = (ev, fn) => { n.listeners[ev] = fn }
|
||||
n.focus = () => { n.focused = true }
|
||||
n.blur = () => {}
|
||||
kids.forEach((k) => { if (k) n.appendChild(k) })
|
||||
return n
|
||||
}
|
||||
const walk = (n, out = []) => { out.push(n); (n.children || []).forEach((c) => walk(c, out)); return out }
|
||||
const byClass = (root, cls) => walk(root).filter((n) => String(n.className || '').split(/\s+/).includes(cls))[0]
|
||||
const fire = (n, ev, extra) => { if (n && n.listeners[ev]) n.listeners[ev](Object.assign({ stopPropagation () {}, preventDefault () {}, target: n }, extra || {})) }
|
||||
|
||||
const sandbox = {
|
||||
el: makeEl,
|
||||
clear: (n) => { n.children.length = 0 },
|
||||
notify: (msg) => { sandbox.__notified.push(String(msg)) },
|
||||
__notified: [],
|
||||
setTimeout,
|
||||
console,
|
||||
}
|
||||
vm.createContext(sandbox)
|
||||
vm.runInContext(helpers + '\n' + editor, sandbox)
|
||||
const makeVarsEditor = sandbox.makeVarsEditor
|
||||
ok('能从真实源码跑起 makeVarsEditor', typeof makeVarsEditor === 'function')
|
||||
|
||||
// ---- 1) 新建:正文里的 {变量} 自动进入列表 ----
|
||||
const text1 = '风格 {主色},背景 {留白}'
|
||||
let t1 = text1
|
||||
const ed = makeVarsEditor(text1, [], (t) => { t1 = t }, { getText: () => t1 })
|
||||
ok('自动识别 2 个变量', ed.list().length === 2 && ed.list()[0].key === '主色')
|
||||
ok('默认收起(首项展开区无名称框)', !byClass(ed.node, 'iwb-plp-vname'))
|
||||
|
||||
// ---- 2) 展开后填名称与多行内容 ----
|
||||
const item0 = byClass(ed.node, 'iwb-plp-vrow2')
|
||||
fire(item0, 'click')
|
||||
const nameIn = byClass(ed.node, 'iwb-plp-vname')
|
||||
const area = byClass(ed.node, 'iwb-plp-vdef')
|
||||
ok('展开后出现名称框与内容框', !!nameIn && !!area)
|
||||
nameIn.value = '主色调'
|
||||
fire(nameIn, 'input')
|
||||
area.value = '橙红\n金色描边'
|
||||
fire(area, 'input')
|
||||
ok('名称写入 label', ed.list()[0].label === '主色调')
|
||||
ok('多行内容写入 def(换行保留)', ed.list()[0].def === '橙红\n金色描边')
|
||||
ok('v1.13.0 名称只写 label,不改正文', t1 === text1)
|
||||
|
||||
// ---- 3) 正文改动触发 sync,label/def 不能被吃掉(旧实现的 bug)----
|
||||
t1 = t1 + ',再加 {补充}'
|
||||
ed.sync(t1)
|
||||
ok('sync 后变量数 3', ed.list().length === 3)
|
||||
ok('sync 后 label 仍在', ed.list()[0].label === '主色调')
|
||||
ok('sync 后 def 仍在', ed.list()[0].def === '橙红\n金色描边')
|
||||
ok('新增变量默认空名称', ed.list()[2].label === '')
|
||||
|
||||
// ---- 3b) 用户直接在正文里改 {} 的字 ⇒ 名称/说明不能丢(内容跟着这段字走)----
|
||||
t1 = t1.replace('{主色}', '{深红金}')
|
||||
ed.sync(t1)
|
||||
ok('正文里直接改占位符 ⇒ 名称不丢', ed.list()[0].label === '主色调')
|
||||
ok('正文里直接改占位符 ⇒ 内容 = 新键', ed.list()[0].def === '深红金', JSON.stringify(ed.list()))
|
||||
|
||||
// ---- 4) v1.13.0:正文占位符 = 内容原文(老数据本来就该这样,不再改写)----
|
||||
const LONG = '一个顶部金色、顶部和底部有金色边缘、底部悬挂红色'
|
||||
const longText = '{' + LONG + '}'
|
||||
let patched = longText
|
||||
const ed2 = makeVarsEditor(longText, [{ key: LONG, label: '物品名称', desc: '主题内容描述', def: '' }], (t) => { patched = t }, { getText: () => patched })
|
||||
ok('打开时正文保持原样(不动存档、不偷偷改名)', patched === longText && ed2.list()[0].key === LONG)
|
||||
const it2 = byClass(ed2.node, 'iwb-plp-vrow2')
|
||||
fire(it2, 'click')
|
||||
const area2 = byClass(ed2.node, 'iwb-plp-vdef')
|
||||
ok('内容框显示的就是正文里 {…} 那段字', area2 && area2.value === LONG)
|
||||
ok('收起摘要显示内容字数', walk(ed2.node).some((n) => /内容 \d+ 字/.test(String(n.textContent || ''))))
|
||||
ok('v1.12.3 展开区只有 名称/内容/说明 三个输入(占位符框已移除)',
|
||||
!!byClass(ed2.node, 'iwb-plp-vname') && !!byClass(ed2.node, 'iwb-plp-vdef') &&
|
||||
!!byClass(ed2.node, 'iwb-plp-vdesc') && !byClass(ed2.node, 'iwb-plp-vkey'))
|
||||
ok('v1.12.3 内容框是多行 textarea(rows=3)',
|
||||
area2.tag === 'textarea' && area2.rows === '3')
|
||||
|
||||
// 改内容 ⇒ 正文跟着改(用户要的「关联」)
|
||||
area2.value = '一个顶部金色、顶部和底部有银色边缘、底部悬挂红色'
|
||||
fire(area2, 'input')
|
||||
ok('v1.13.0 改内容 ⇒ 正文 {…} 立刻跟着改',
|
||||
patched === '{一个顶部金色、顶部和底部有银色边缘、底部悬挂红色}' &&
|
||||
ed2.list()[0].key === '一个顶部金色、顶部和底部有银色边缘、底部悬挂红色')
|
||||
ok('改内容后名称不受影响', ed2.list()[0].label === '物品名称')
|
||||
|
||||
// 名称改回:不应影响正文
|
||||
const nameIn2 = byClass(ed2.node, 'iwb-plp-vname')
|
||||
const beforeName = patched
|
||||
nameIn2.value = '主色'
|
||||
fire(nameIn2, 'input')
|
||||
ok('v1.13.0 改名称不动正文', patched === beforeName && ed2.list()[0].label === '主色')
|
||||
|
||||
// 内容塞不进 {}(含换行 / 超 60 字)⇒ 正文保留原键,不硬塞
|
||||
const beforeBreak = patched
|
||||
area2.value = '第一行\n第二行'
|
||||
fire(area2, 'input')
|
||||
ok('v1.13.0 内容含换行 ⇒ 正文保留原键(塞不进 {} 就不塞)',
|
||||
patched === beforeBreak && ed2.list()[0].def === '第一行\n第二行')
|
||||
ok('v1.13.0 摘要提示「正文未同步」', walk(ed2.node).some((n) => /正文未同步/.test(String(n.textContent || ''))))
|
||||
|
||||
// ---- 5) 顶部功能性说明文案与橙色提示都不再渲染 ----
|
||||
ok('v1.12.3 顶部只剩「变量」标签(无功能说明)',
|
||||
!walk(ed2.node).some((n) => String(n.textContent || '').indexOf('名称只影响显示') >= 0))
|
||||
ok('v1.12.3 不再出现「占位符」相关提示',
|
||||
!walk(ed2.node).some((n) => String(n.textContent || '').indexOf('占位符') >= 0))
|
||||
|
||||
// ---- 6) preset:插入长句后内容落位、默认展开 ----
|
||||
const ed4 = makeVarsEditor('{变量1}', [], () => {})
|
||||
ed4.preset('变量1', { def: '一整句原文' })
|
||||
ok('preset 写入内容', ed4.list()[0].def === '一整句原文')
|
||||
ok('preset 展开该变量(出现名称框)', !!byClass(ed4.node, 'iwb-plp-vname'))
|
||||
|
||||
console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过')
|
||||
if (failed) process.exitCode = 1
|
||||
@@ -0,0 +1,123 @@
|
||||
# sticky · 便利贴(v1.0.7)
|
||||
|
||||
画布上的便签节点:一张纸片,写多行文字,能调字号、粗细、背景色,能拖大拖小。
|
||||
**不连线、不进生图链路**——纯标注用途(说明节点、分组标题、随手记)。
|
||||
|
||||
## 设计由来
|
||||
|
||||
用户要一个"在画布上建立说明文字"的插件。最初设想是"标题节点",后来改成便签:
|
||||
不要单独的"标题"概念——**便签上方那条"便利贴"标签是宿主强制的标题带**(插件节点的
|
||||
`hasTitle: true` 写死,只有中继节点才不显示),注册节点名即可,用户不用再填标题字段。
|
||||
想当说明标题就把字号调大(**无上限**,A+ 每点一次 +2),想放多行正文就用小字(默认 14)。
|
||||
|
||||
> v1.0.1 修复三个真机问题:① 节点拖动变大后下半漏出宿主底色(根容器改 `flex:1` 撑满);
|
||||
> ② 字号被闭集钳在 24(改为无上限、±2 步进);③ 正文单击即编辑(改为照宿主文本节点那样
|
||||
> **单击选中/拖动、双击才进编辑**)。
|
||||
>
|
||||
> v1.0.2 修复两个体验问题:① 便签高度不能贴近文字(下方一大块空白)——textarea 改为
|
||||
> **高度随内容自适应**(`flex:0 0 auto` + JS 按 `scrollHeight` 算高),节点外框 `height:auto`
|
||||
> 会跟着收缩,resize 手柄就能拖到贴字;② 色板弹在便签右下角、盖住 resize 手柄——
|
||||
> 色板 DOM 从根节点挪进**工具条**(`top:100%` 落在调色按钮正下方)。
|
||||
> 选中气泡上的「节点颜色」按钮是宿主画的、对本插件无效,需改宿主才能去掉——本版不动。
|
||||
>
|
||||
> v1.0.3 修掉「v1.0.2 看着修了其实没修透」的高度问题:宿主 `NodeCard` 把 `node.h` 写成
|
||||
> 外框 `minHeight`(`height:auto`),旧的 `h` 仍在撑着外框,所以正文贴字了、下面还是一截空白,
|
||||
> resize 手柄也拖不下去。现在插件在渲染时按「工具条 + 正文」算内容高度,首次遇到旧 `h`
|
||||
> 明显大于内容时把它校正到内容高度,并同步覆盖外框 `minHeight`;用户后续拖大的 `h` 会保留,
|
||||
> 仍能拖大拖小。调色圆点移到工具条**最右上**,色板 `right:8px` 正对圆点右缘、落其下方。
|
||||
>
|
||||
> v1.0.4 修掉最后一行空白:textarea 没写 `rows`,浏览器默认是 **2 行**;`fitBody()` 把高度
|
||||
> 设成 `auto` 再读 `scrollHeight` 时,单行文字也被算成两行高,于是一行字和两行字的便签一样高。
|
||||
> 现在显式 `rows="1"`,`scrollHeight` 才等于真实内容行数;多行文本照常换行、高度跟着涨。
|
||||
>
|
||||
> v1.0.5 统一圆角:纸片内圈从写死的 10px 改成 `calc(var(--iwb-node-radius, 14px) - 1px)`,
|
||||
> 与宿主节点选中框(外圈 14px + 1px 边框)对齐,选中时两层边缘不再错开。
|
||||
>
|
||||
> v1.0.6 修行高回缩:v1.0.3 为了「内容长高时 resize 起点不滞后」把 `node.h` 顶到内容高度,
|
||||
> 但文本从两行删回一行时这个 h 没跟着降,外框就一直留着两行高。现在区分**自动跟随**与
|
||||
> **用户手动拖尺寸**:自动写出的 h 双向贴合内容(长高就涨、缩回就降);用户拖手柄改过 h
|
||||
> 后退出自动跟随,手动尺寸照旧保留。
|
||||
>
|
||||
> v1.0.7 修自定义调色后面板不退出:预设色块点完会收起,但色轮走的是隐藏的原生
|
||||
> `<input type="color">`,`change` 回调只写 `bgColor`、没关浮层,选完色色板仍压在便签上。
|
||||
> 现在**点色轮打开系统取色器时即收起**(确认/取消都不留浮层),自定义色 `change` 到达时再兜底收一次。
|
||||
|
||||
## 长什么样
|
||||
|
||||
画布上是一张暖色纸片(圆角、细边、一点阴影),顶上一条工具条:
|
||||
|
||||
| 控件 | 作用 |
|
||||
|---|---|
|
||||
| `−` / `+` | 字号缩放,每步 ±2,下限 6、**无上限** |
|
||||
| `B` | 正文粗细在 400 / 600 间切换(按钮高亮表示已加粗) |
|
||||
| 圆点 | 展开色板:8 个预设色 + 底部彩虹色轮;**色板落在圆点正下方**,不挡 resize 手柄 |
|
||||
| 色轮 | 调起系统颜色选择器,可选任意色;点开即收起色板,选完色不再压在便签上 |
|
||||
| 正文区 | 多行 textarea,透明底,随字号自动换行;**单击=选中/拖动节点,双击=进入编辑,失焦/ESC 退出** |
|
||||
|
||||
选中节点后宿主自带的浮动气泡(信息 / 删除、复制、缩放手柄)照常出现,不是本插件画的。
|
||||
|
||||
## 状态存在哪
|
||||
|
||||
全部写进节点 `data`,走 `props.onUpdate(node.id, patch)`,随画布落盘:
|
||||
|
||||
| 字段 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `text` | `''` | 多行正文 |
|
||||
| `fontSize` | `14` | 任意有限数(下限 6),A± 每步 ±2,无上限 |
|
||||
| `fontWeight` | `400` | `400` / `600` |
|
||||
| `bgColor` | `#FCE8B0` | 纸片背景色 |
|
||||
|
||||
**文字颜色不存**——运行时按背景亮度自动取深色 `#1c2333` 或白色 `#ffffff`(阈值 Y=0.55),
|
||||
深色纸片不会配黑字看不见。这是运行时计算,源码里没有写死的中性色,不触发守门测试。
|
||||
|
||||
## 关键实现点
|
||||
|
||||
- **注册**:`ctx.nodes.register({ id:'sticky', title:'便利贴', ports:{in:false,out:false}, height:180, render })`
|
||||
—— `ports` 全关,纯标注节点;宿主生成的类型是 `plugin:sticky:sticky`。
|
||||
- **节点尺寸**:节点缩放用宿主自带手柄(右下角 `.iwb-resize`,对插件节点天然生效),插件不写
|
||||
`w/h`。两层 flex 各管一件事:**根容器 `.iwb-sticky-node` 用 `flex:1 1 auto; min-height:0` 撑满**
|
||||
宿主容器 `.iwb-plugin-node-body`(flex 列、`padding:0`)——只写 `height:100%` 在 WKWebView 下
|
||||
对 flex 项算不准,拖大后下半会露出宿主底色(v1.0.0 的问题);**textarea 反过来用 `flex:0 0 auto`
|
||||
+ JS 按 `scrollHeight` 算高**(`rows="1"` 去掉浏览器默认 2 行的预留;文本/字号变了才重算,
|
||||
缓存 `fitText/fitSize` 避免每次 render reflow),
|
||||
让内容自然高度贴着文字(v1.0.2)。**外框 minHeight(v1.0.3)**:宿主 `NodeCard` 的
|
||||
`style.minHeight = node.h` 才是拖不下去的真凶——插件在 `fitOuterBox()` 里用
|
||||
`工具条 offsetHeight + 正文 style.height + 2px 边框` 算内容高度,首次把旧 `h` 校正到该值,
|
||||
并直接把宿主外框的 `minHeight` 覆盖掉。插件自动写出的 h **双向跟随内容**(v1.0.6:
|
||||
两行退回一行会缩回去);一旦检测到 h 被外部拖手柄改写,就退出自动跟随、尊重手动尺寸,
|
||||
所以拖大拖小仍然有效。
|
||||
- **色板定位**:色板挂在工具条 `tools`(`position:relative`)内而非便签根节点,CSS `top:100%`
|
||||
落在调色圆点正下方;挂在根节点时会贴便签底部右下角、盖住 resize 手柄(v1.0.2 的问题)。
|
||||
圆点用 `margin-left:auto` 推到工具条最右上(v1.0.3),色板 `right:8px` 与圆点右缘对齐。
|
||||
- **样式时机**:CSS 在脚本执行时就注入唯一 `<style id="iwb-sticky-style">`,不等 setup / mount
|
||||
—— 从存档直接进画布(面板从不 mount)时节点也有样式。
|
||||
- **幂等同步**:`render(node, props, host)` 每次渲染都被宿主无依赖地调一次;插件缓存 host 上的
|
||||
骨架 `host.__sticky`,只在数据真的变了才写 DOM;**编辑态(`st.editing`)或 `document.activeElement
|
||||
=== textarea`** 时跳过 `value` 覆盖,否则用户打字会被打断/失焦。sync 只碰 style 和 bold/dot 的
|
||||
className,不动 textarea 的 editing class,重渲染不会失焦。
|
||||
- **单击/双击编辑**:照宿主文本节点的做法——textarea 默认 `readonly`,宿主 CSS
|
||||
`.iwb-node textarea[readonly]{pointer-events:none}` 让**单击穿透**给节点卡片(选中/拖动);
|
||||
双击由插件在 root 上接管(宿主 `onDoubleClick` 只处理内置文本类型,不管 `plugin:` 节点),
|
||||
解除 readonly + focus 进入编辑;失焦 / ESC 退出。编辑态下 `pointerdown`/`mousedown`/`keydown`
|
||||
不冒泡给宿主,避免拖节点和触发画布快捷键。插件自己维护 `st.editing`,不依赖宿主的
|
||||
`props.editingBody`(那是给内置文本节点用的)。
|
||||
- **面板**:一个「+ 插入便利贴」按钮 → `ctx.canvas.createNode('plugin:sticky:sticky', null, null, {...})`,
|
||||
坐标 `null/null` 走宿主 `findSpot()`(视口中心螺旋找空位),插件不自己算坐标。
|
||||
|
||||
## 校验
|
||||
|
||||
```bash
|
||||
node sticky/tools/harness.mjs # 纯 node,58 项:注册/渲染/字号无上限/贴字自适应/rows=1/外框 minHeight 双向回缩/圆角对齐/色板定位/自定义色后面板收起/双击编辑/换色/文本/幂等/插入
|
||||
npm run validate # 全仓契约校验
|
||||
```
|
||||
|
||||
## 发布
|
||||
|
||||
本仓是桌面客户端的插件源仓。发布链路(详见根 README):
|
||||
|
||||
```
|
||||
sticky/src/index.js → 桌面仓 sync-plugins-from-repo.js → plugins/runtime/plugin-sticky.<sha12>.js
|
||||
→ gen-market.js → market/index.json + zip → 上传 NAS
|
||||
```
|
||||
|
||||
上架需在桌面仓 `scripts/sync-plugins-from-repo.js` 的 `IDS` 白名单和 `plugins/meta.json` 里加入 `sticky`。
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "@iwb-plugin/sticky",
|
||||
"private": true,
|
||||
"version": "1.0.7",
|
||||
"description": "画布便利贴:多行文本 + 字号/粗细调节 + 8 色背景,纯标注节点不连线",
|
||||
"ibwPlugin": {
|
||||
"id": "sticky",
|
||||
"entry": "src/index.js",
|
||||
"apiVersion": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
// iwb-plugin: 画布便利贴 —— 多行文本 + 字号/粗细调节 + 8 色背景,纯标注节点不连线。
|
||||
//
|
||||
// 设计口径(用户 2026-11-24 确认):
|
||||
// - 不要"标题"概念:便签上方那条"便利贴"标签是宿主强制的标题带(hasTitle 写死),
|
||||
// 节点名注册成"便利贴"即可,用户不用再填标题字段。
|
||||
// - 想当说明标题就把字号调大(无上限,A+ 每点一次 +2),想放多行正文就用小字(默认 14)。
|
||||
// - 不连线:ports:{in:false,out:false}。
|
||||
// - 节点缩放用宿主自带手柄(右下角),插件不设宽高。
|
||||
//
|
||||
// 状态全部存 node.data(props.onUpdate 写回,随画布落盘):
|
||||
// text / fontSize / fontWeight / bgColor
|
||||
// 字号:A−/A+ 每步 ±2,下限 6、无上限(用户明确要求去掉最大字号限制);
|
||||
// 8 个预设色是运行时数据、色轮走系统颜色选择器,源码里不写死中性色(守门只卡字面量)。
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
|
||||
if (!global.IWBPluginHost) return
|
||||
|
||||
// 必须在脚本执行时就注入:面板可能瞬间挂载、节点可能从存档直接出现(面板从不 mount)。
|
||||
function ensureStyle() {
|
||||
if (typeof document === 'undefined' || !document.createElement) return
|
||||
if (document.getElementById('iwb-sticky-style')) return
|
||||
var css = '' +
|
||||
'#iwb-sticky-style{}' +
|
||||
'[hidden]{display:none!important}' +
|
||||
'.iwb-sticky-panel{display:flex;flex-direction:column;gap:12px;font-size:13px;color:var(--iwb-text,#1c2333)}' +
|
||||
'.iwb-sticky-panel-tip{font-size:12px;line-height:1.6;color:var(--iwb-text2,#4d5668);opacity:.9}' +
|
||||
'.iwb-sticky-add{cursor:pointer;border:1px solid var(--iwb-brand,#6b7280);border-radius:8px;background:var(--iwb-layer2,#fff);color:var(--iwb-text,#1c2333);font-size:13px;padding:10px 14px;font-family:inherit}' +
|
||||
'.iwb-sticky-add:hover{background:var(--iwb-hover,#f0f1f4)}' +
|
||||
'.iwb-sticky-list{display:flex;flex-direction:column;gap:8px;margin-top:4px}' +
|
||||
'.iwb-sticky-row{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:8px 10px;border:1px solid var(--iwb-border,#d5d9e0);border-radius:8px;background:var(--iwb-layer,#f5f6f8)}' +
|
||||
'.iwb-sticky-row-txt{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0}' +
|
||||
'.iwb-sticky-go{cursor:pointer;border:1px solid var(--iwb-border,#d5d9e0);border-radius:6px;background:var(--iwb-layer2,#fff);color:var(--iwb-text,#1c2333);font-size:12px;padding:4px 10px;white-space:nowrap;font-family:inherit}' +
|
||||
'.iwb-sticky-go:hover{border-color:var(--iwb-brand,#6b7280)}' +
|
||||
// ---- 节点体 ----
|
||||
// 宿主容器 .iwb-plugin-node-body 是 flex 列且 padding:0;这里必须 flex:1 撑满,
|
||||
// 不能只写 height:100%(WKWebView 下百分比对 flex 项算不准,拖大后下半露出宿主底色)。
|
||||
// 圆角对齐宿主节点:外框 .iwb-node 用 var(--iwb-node-radius)=14px 且有 1px 边框,
|
||||
// 纸片在框内 ⇒ 内圈半径 = 外圈 - 1px,选中时两层边缘才不会错开。
|
||||
'.iwb-sticky-node{position:relative;display:flex;flex-direction:column;flex:1 1 auto;min-height:0;width:100%;box-sizing:border-box;border-radius:calc(var(--iwb-node-radius, 14px) - 1px);overflow:visible}' +
|
||||
'.iwb-sticky-tools{display:flex;align-items:center;gap:6px;padding:6px 8px;border-bottom:1px solid rgba(0,0,0,.08);flex:0 0 auto;position:relative;z-index:2}' +
|
||||
'.iwb-sticky-btn{cursor:pointer;border:1px solid rgba(0,0,0,.2);border-radius:6px;background:transparent;color:inherit;font-size:11px;padding:2px 6px;font-family:inherit;line-height:1.4;user-select:none}' +
|
||||
'.iwb-sticky-btn:hover{background:rgba(0,0,0,.07)}' +
|
||||
'.iwb-sticky-btn-on{font-weight:600;background:rgba(0,0,0,.1)}' +
|
||||
// 调色圆点推到工具条最右端(右上),色板 right:8px 与圆点右缘对齐,落在其正下方。
|
||||
'.iwb-sticky-dot{display:inline-block;width:14px;height:14px;border-radius:50%;border:1px solid rgba(0,0,0,.25);cursor:pointer;vertical-align:middle;padding:0;margin-left:auto}' +
|
||||
'.iwb-sticky-dot-on{box-shadow:0 0 0 2px rgba(0,0,0,.55)}' +
|
||||
'.iwb-sticky-pal{position:absolute;top:100%;right:8px;z-index:20;display:grid;grid-template-columns:repeat(4,18px);gap:8px 6px;padding:10px;border-radius:10px;border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer2,#fff);box-shadow:0 4px 16px rgba(0,0,0,.18)}' +
|
||||
'.iwb-sticky-pal-sw{width:18px;height:18px;border-radius:50%;border:1px solid rgba(0,0,0,.2);cursor:pointer;padding:0}' +
|
||||
'.iwb-sticky-wheel{grid-column:1/-1;display:flex;justify-content:center;padding-top:8px;border-top:1px solid var(--iwb-border,#d5d9e0)}' +
|
||||
'.iwb-sticky-wheel-btn{cursor:pointer;width:22px;height:22px;border-radius:50%;border:0;padding:0;background:conic-gradient(#e24b4a,#ef9f27,#fac775,#639922,#1d9e75,#378add,#7f77dd,#d4537e,#e24b4a)}' +
|
||||
// 高度随内容自适应(贴字):不再 flex:1 撑满剩余空间,否则字号大/文字少时
|
||||
// 下方留出大片空白;高度由 syncSkeleton 按行数×字号算,宿主外框 height:auto
|
||||
// 会跟着内容收缩,resize 手柄就能拖到贴字。overflow:hidden 避免自适应高度出滚动条。
|
||||
'.iwb-sticky-body{flex:0 0 auto;min-height:1.7em;width:100%;box-sizing:border-box;resize:none;border:0;outline:0;background:transparent;color:inherit;font-family:inherit;line-height:1.7;padding:12px;overflow:hidden;overflow-wrap:anywhere;cursor:move}' +
|
||||
// 与宿主文本节点一致:只读态单击穿透给节点拖动/选中;双击进入编辑才变 text 光标。
|
||||
// 宿主 style.css 有 `.iwb-node textarea[readonly]{pointer-events:none}`,这里用自身 class 兜底。
|
||||
'.iwb-sticky-body.iwb-sticky-editing{cursor:text}' +
|
||||
'.iwb-sticky-body::placeholder{opacity:.45}' +
|
||||
'.iwb-sticky-color-input{position:absolute;width:0;height:0;opacity:0;pointer-events:none}'
|
||||
try {
|
||||
var styleEl = el('style', { text: css })
|
||||
styleEl.setAttribute('id', 'iwb-sticky-style')
|
||||
;(document.head || document.documentElement).appendChild(styleEl)
|
||||
} catch (e) { /* 样式注入失败不影响功能 */ }
|
||||
}
|
||||
|
||||
// 插件面板/节点体是真实 DOM(不是 React vDOM):createElement + addEventListener。
|
||||
function el(tag, attrs, kids) {
|
||||
var node = document.createElement(tag)
|
||||
if (attrs) {
|
||||
for (var key in attrs) {
|
||||
var value = attrs[key]
|
||||
if (value === null || value === undefined) continue
|
||||
if (key === 'class' || key === 'className') node.className = value
|
||||
else if (key === 'text') node.textContent = String(value)
|
||||
else if (key === 'hidden') node.hidden = Boolean(value)
|
||||
else if (key.slice(0, 2) === 'on') node.addEventListener(key.slice(2).toLowerCase(), value)
|
||||
else node.setAttribute(key, String(value))
|
||||
}
|
||||
}
|
||||
if (kids !== null && kids !== undefined) {
|
||||
var list = Array.isArray(kids) ? kids : [kids]
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (list[i] === null || list[i] === undefined || list[i] === false) continue
|
||||
node.appendChild(typeof list[i] === 'string' ? document.createTextNode(list[i]) : list[i])
|
||||
}
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
var MIN_SIZE = 6 // 下限(用户只要求取消上限,下限保留防误操作缩到看不见)
|
||||
var SIZE_STEP = 2 // A−/A+ 每步 ±2
|
||||
var DEFAULT_SIZE = 14
|
||||
var PALETTE = [
|
||||
{ name: '黄', value: '#FCE8B0' },
|
||||
{ name: '粉', value: '#F4C0D1' },
|
||||
{ name: '橙', value: '#EF9F27' },
|
||||
{ name: '绿', value: '#9FE1CB' },
|
||||
{ name: '蓝', value: '#B5D4F4' },
|
||||
{ name: '浅紫', value: '#CECBF6' },
|
||||
{ name: '玫红', value: '#ED93B1' },
|
||||
{ name: '灰', value: '#D3D1C7' },
|
||||
]
|
||||
var DEFAULT_BG = '#FCE8B0'
|
||||
|
||||
// 只保证是 >= 下限的有限数,不再钳到闭集/上限;A+ 可无限放大。
|
||||
function normSize(v) {
|
||||
var n = Number(v)
|
||||
if (!isFinite(n) || n < MIN_SIZE) return DEFAULT_SIZE
|
||||
return Math.round(n)
|
||||
}
|
||||
|
||||
// 依据背景亮度取黑/白文字(运行时计算,源码里不写死中性色)。
|
||||
function textColorOf(hex) {
|
||||
var m = /^#?([0-9a-f]{6})$/i.exec(String(hex || ''))
|
||||
if (!m) return '#1c2333'
|
||||
var n = parseInt(m[1], 16)
|
||||
var r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255
|
||||
// 相对亮度(sRGB 简化)
|
||||
var lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255
|
||||
return lum < 0.55 ? '#ffffff' : '#1c2333'
|
||||
}
|
||||
|
||||
// 脚本执行时就注入(不等 setup / mount,存档直入画布也有样式)。
|
||||
ensureStyle()
|
||||
|
||||
var ctxRef = null
|
||||
|
||||
// ---------------- 节点体 ----------------
|
||||
// 宿主契约:render(node, props, host) 往 host 这个真实 DOM 里画,不是返回 vDOM。
|
||||
// host 由宿主固定、不重建;插件自己缓存骨架 + 幂等同步,编辑中的 textarea 不覆盖值。
|
||||
function renderSticky(node, props, host) {
|
||||
ensureStyle()
|
||||
var data = (node && node.data) || {}
|
||||
var st = host.__sticky
|
||||
if (!st) {
|
||||
host.textContent = ''
|
||||
st = host.__sticky = buildSkeleton(host, props)
|
||||
}
|
||||
st.node = node
|
||||
st.props = props
|
||||
syncSkeleton(st, data, node)
|
||||
}
|
||||
|
||||
function buildSkeleton(host, props) {
|
||||
var root = el('div', { className: 'iwb-sticky-node' })
|
||||
var tools = el('div', { className: 'iwb-sticky-tools' })
|
||||
|
||||
var minus = el('button', { className: 'iwb-sticky-btn', type: 'button', title: '缩小字号', 'data-act': 'minus' }, '−')
|
||||
var plus = el('button', { className: 'iwb-sticky-btn', type: 'button', title: '放大字号', 'data-act': 'plus' }, '+')
|
||||
var bold = el('button', { className: 'iwb-sticky-btn', type: 'button', title: '切换粗细', 'data-act': 'bold' }, 'B')
|
||||
var dot = el('button', { className: 'iwb-sticky-dot', type: 'button', title: '背景色', 'data-act': 'palette' })
|
||||
var pal = el('div', { className: 'iwb-sticky-pal', hidden: true })
|
||||
var colorInput = el('input', { type: 'color', className: 'iwb-sticky-color-input', 'data-act': 'color' })
|
||||
// rows=1 是关键:textarea 默认 rows=2,fitBody() 把高度设 auto 读 scrollHeight 时,
|
||||
// 单行文字也会被算成两行高(用户报的“预留了一行文本高度”)。显式 1 行后,
|
||||
// scrollHeight 才等于真实内容行数——多行文本仍会自动换行、高度跟着涨。
|
||||
var body = el('textarea', { className: 'iwb-sticky-body', rows: '1', spellcheck: 'false', placeholder: '双击编辑…' })
|
||||
// 对齐宿主文本节点:默认只读。宿主 CSS `.iwb-node textarea[readonly]{pointer-events:none}`
|
||||
// ⇒ 单击穿透给节点卡片(选中/拖动);双击由本插件在 root 上接管进入编辑。
|
||||
body.readOnly = true
|
||||
body.setAttribute('readonly', '')
|
||||
|
||||
tools.appendChild(minus); tools.appendChild(plus); tools.appendChild(bold); tools.appendChild(dot)
|
||||
// 色板挂在工具条内(tools 已 position:relative):CSS top:100% 落在调色按钮正下方,
|
||||
// 而不是贴整个便签底部右下角(那样会盖住宿主 resize 手柄、且离按钮很远)。
|
||||
tools.appendChild(pal)
|
||||
root.appendChild(tools); root.appendChild(colorInput); root.appendChild(body)
|
||||
host.appendChild(root)
|
||||
|
||||
var st = { root: root, tools: tools, minus: minus, plus: plus, bold: bold, dot: dot,
|
||||
pal: pal, colorInput: colorInput, body: body, data: null, palOpen: false, editing: false }
|
||||
|
||||
function onTool(e) {
|
||||
var t = e.target || {}
|
||||
var act = t.getAttribute && t.getAttribute('data-act')
|
||||
if (!act) return
|
||||
e.stopPropagation && e.stopPropagation()
|
||||
var d = (st.node && st.node.data) || {}
|
||||
var up = st.props && st.props.onUpdate
|
||||
var id = st.node && st.node.id
|
||||
if (!up || !id) return
|
||||
if (act === 'minus' || act === 'plus') {
|
||||
var cur = normSize(d.fontSize == null ? DEFAULT_SIZE : d.fontSize)
|
||||
var next = act === 'minus' ? Math.max(MIN_SIZE, cur - SIZE_STEP) : cur + SIZE_STEP
|
||||
if (next !== cur) up(id, { fontSize: next })
|
||||
} else if (act === 'bold') {
|
||||
up(id, { fontWeight: d.fontWeight === 600 ? 400 : 600 })
|
||||
} else if (act === 'palette') {
|
||||
st.palOpen = !st.palOpen
|
||||
pal.hidden = !st.palOpen
|
||||
}
|
||||
}
|
||||
tools.addEventListener('click', onTool)
|
||||
|
||||
// 色板里的色块 + 色轮(事件委托到 pal)
|
||||
for (var i = 0; i < PALETTE.length; i++) {
|
||||
var sw = el('button', { type: 'button', className: 'iwb-sticky-pal-sw', 'data-bg': PALETTE[i].value,
|
||||
title: PALETTE[i].name, style: 'background:' + PALETTE[i].value })
|
||||
pal.appendChild(sw)
|
||||
}
|
||||
var wheelWrap = el('div', { className: 'iwb-sticky-wheel' })
|
||||
var wheel = el('button', { type: 'button', className: 'iwb-sticky-wheel-btn', title: '自定义颜色', 'data-act': 'wheel' })
|
||||
wheelWrap.appendChild(wheel); pal.appendChild(wheelWrap)
|
||||
|
||||
function onPal(e) {
|
||||
var t = e.target || {}
|
||||
e.stopPropagation && e.stopPropagation()
|
||||
var up = st.props && st.props.onUpdate
|
||||
var id = st.node && st.node.id
|
||||
if (!up || !id) return
|
||||
var bg = t.getAttribute && t.getAttribute('data-bg')
|
||||
if (bg) {
|
||||
up(id, { bgColor: bg })
|
||||
st.palOpen = false; pal.hidden = true
|
||||
return
|
||||
}
|
||||
var act = t.getAttribute && t.getAttribute('data-act')
|
||||
if (act === 'wheel') {
|
||||
// 点开系统取色器后这个浮层就完成使命:无论最终确认还是取消都先收起,
|
||||
// 避免取色器关闭后色板还压在便签上(用户报的“自定义调色后面板不退出”)。
|
||||
st.palOpen = false; pal.hidden = true
|
||||
try { colorInput.click() } catch (e2) { /* noop */ }
|
||||
}
|
||||
}
|
||||
pal.addEventListener('click', onPal)
|
||||
|
||||
function onColor(e) {
|
||||
var up = st.props && st.props.onUpdate
|
||||
var id = st.node && st.node.id
|
||||
if (up && id && e.target && e.target.value) up(id, { bgColor: e.target.value })
|
||||
// 自定义色确认后兜底再收一次(个别平台 change 先于上面的收起逻辑到达)。
|
||||
st.palOpen = false; pal.hidden = true
|
||||
}
|
||||
colorInput.addEventListener('change', onColor)
|
||||
|
||||
// ---- 正文编辑状态机(照宿主文本节点:双击进编辑、失焦退出、只读态单击穿透)----
|
||||
function setEditing(on) {
|
||||
st.editing = on
|
||||
body.readOnly = !on
|
||||
if (on) { try { body.removeAttribute('readonly') } catch (e2) { /* noop */ } }
|
||||
else body.setAttribute('readonly', '')
|
||||
body.className = 'iwb-sticky-body' + (on ? ' iwb-sticky-editing' : '')
|
||||
}
|
||||
|
||||
// 双击进入编辑:绑在 root 上(不是 readonly textarea —— 它 pointer-events:none 收不到双击)。
|
||||
// 宿主卡片 onDoubleClick 只处理内置文本类型,plugin: 节点它不接管,所以这里自己 stopPropagation。
|
||||
function onDblClick(e) {
|
||||
// 工具条/色板/按钮上的双击不进编辑
|
||||
var t = e.target || {}
|
||||
if (t.getAttribute && t.getAttribute('data-act')) return
|
||||
if (t.getAttribute && t.getAttribute('data-bg')) return
|
||||
e.stopPropagation && e.stopPropagation()
|
||||
setEditing(true)
|
||||
try { body.focus() } catch (e2) { /* noop */ }
|
||||
}
|
||||
root.addEventListener('dblclick', onDblClick)
|
||||
|
||||
// 编辑态:按下/按键不冒泡给宿主(否则会拖节点 / 触发画布快捷键);失焦退出编辑。
|
||||
;['pointerdown', 'mousedown'].forEach(function (ev) {
|
||||
body.addEventListener(ev, function (e) {
|
||||
if (st.editing) e.stopPropagation && e.stopPropagation()
|
||||
// 只读态不拦:让宿主选中节点 + 拖动
|
||||
})
|
||||
})
|
||||
body.addEventListener('keydown', function (e) {
|
||||
e.stopPropagation && e.stopPropagation()
|
||||
if (e.key === 'Escape') { try { body.blur() } catch (e2) { /* noop */ } }
|
||||
})
|
||||
body.addEventListener('blur', function () { setEditing(false) })
|
||||
|
||||
// 输入即写回(防抖交给宿主的 commitCanvas),编辑中不重建 DOM 故不失焦。
|
||||
function onInput(e) {
|
||||
var up = st.props && st.props.onUpdate
|
||||
var id = st.node && st.node.id
|
||||
if (up && id) up(id, { text: e.target.value })
|
||||
e.stopPropagation && e.stopPropagation()
|
||||
}
|
||||
body.addEventListener('input', onInput)
|
||||
|
||||
st._listeners = { tools: onTool, pal: onPal, color: onColor, input: onInput, dblclick: onDblClick, setEditing: setEditing }
|
||||
return st
|
||||
}
|
||||
|
||||
// textarea 高度贴字:数据(文本/字号)变了才重算,避免每次 render 都 reflow。
|
||||
// 设 auto → 读 scrollHeight → 写回,是 textarea 自适应的标准做法;浏览器里行数/自动换行都算准。
|
||||
function fitBody(st, text, size) {
|
||||
if (st.fitText === text && st.fitSize === size) return
|
||||
st.fitText = text; st.fitSize = size
|
||||
var b = st.body
|
||||
var prev = b.style.height
|
||||
b.style.height = 'auto'
|
||||
var h = b.scrollHeight
|
||||
b.style.height = (h && h > 0 ? h : Math.max(1, text.split('\n').length) * Math.round(size * 1.7) + 24) + 'px'
|
||||
// 高度没变就不留空字符串(兼容 stub:style.height 是普通对象)
|
||||
if (!b.style.height && prev) b.style.height = prev
|
||||
}
|
||||
|
||||
// 宿主 NodeCard 把 node.h 当作 minHeight 写在外框上(style.minHeight = node.h, height:auto)。
|
||||
// 这就是 v1.0.2「内容贴字了但外框还有一截空白、手柄拖不下去」的真正原因:插件只改了
|
||||
// textarea 高度,外框仍被 node.h 撑住。这里做两件事:
|
||||
// 1. 内容高度 = 工具条 + 正文(不用 root.offsetHeight:root 会被旧的 minHeight 拉高,
|
||||
// 读出来还是旧高度,会自我锁死);
|
||||
// 2. 首次遇到「旧 h 明显大于内容」时把 node.h 校正到内容高度,顺手把外框 minHeight
|
||||
// 覆盖成同一个值——resize 起点 (onResizeStart 读 n0.h) 才和实际视觉一致,拖小立刻生效。
|
||||
// 区分两种 h:
|
||||
// - 插件自动跟随内容写出的 h:内容长高就涨、缩回就降(v1.0.6 修的「两行退回一行不缩」);
|
||||
// - 用户拖手柄改出的 h:h 相对上一帧变了 ⇒ 尊重手动尺寸,只在内容超过它时顶一下。
|
||||
// 首次遇到的旧大 h 校正一次(staleH),之后进入自动跟随。
|
||||
function fitOuterBox(st, node) {
|
||||
if (!st || !st.root || !node) return
|
||||
var toolsH = st.tools.offsetHeight || 30
|
||||
var bodyH = parseFloat(st.body.style.height) || 0
|
||||
if (!bodyH) return
|
||||
var content = Math.round(toolsH + bodyH + 2) // +2 = 宿主节点上下各 1px 边框
|
||||
var h = Number(node.h) || 0
|
||||
if (st.staleH == null) st.staleH = h
|
||||
|
||||
if (st.lastBoxH != null && h !== st.lastBoxH) {
|
||||
// 外部(用户拖手柄)改了 h:退出自动跟随,保留手动尺寸
|
||||
st.autoFollow = false
|
||||
} else if (st.autoFollow == null) {
|
||||
// 首帧:旧 h 若明显大于内容,先校正一次,然后进入自动跟随
|
||||
if (h > content + 2 && st.staleH === h) { node.h = content; h = content }
|
||||
st.autoFollow = true
|
||||
}
|
||||
|
||||
if (st.autoFollow) {
|
||||
// 自动跟随:文本/字号增减都双向贴合(这是两行退回一行能缩回去的关键)
|
||||
if (Math.abs(h - content) > 1) { node.h = content; h = content }
|
||||
} else if (h < content - 2) {
|
||||
// 手动尺寸只在内容超出时才顶高,不覆盖用户主动拖大的高度
|
||||
node.h = content; h = content
|
||||
}
|
||||
st.lastBoxH = h
|
||||
var floor = Math.max(content, Number(node.h) || 0)
|
||||
// root → host(.iwb-plugin-node-body) → card(.iwb-node)
|
||||
var card = st.root.parentNode && st.root.parentNode.parentNode
|
||||
if (card && card.style && card.style.minHeight !== floor + 'px') card.style.minHeight = floor + 'px'
|
||||
}
|
||||
|
||||
function syncSkeleton(st, data, node) {
|
||||
var bg = data.bgColor || DEFAULT_BG
|
||||
var size = normSize(data.fontSize == null ? DEFAULT_SIZE : data.fontSize)
|
||||
var weight = data.fontWeight === 600 ? 600 : 400
|
||||
var text = data.text == null ? '' : String(data.text)
|
||||
var color = textColorOf(bg)
|
||||
|
||||
// 幂等:只在值真的变了才写 DOM,避免重建/覆盖正在编辑的 textarea。
|
||||
if (st.root.style.background !== bg) st.root.style.background = bg
|
||||
if (st.root.style.color !== color) st.root.style.color = color
|
||||
if (!st.editing && document.activeElement !== st.body && st.body.value !== text) st.body.value = text
|
||||
if (st.body.style.fontSize !== size + 'px') st.body.style.fontSize = size + 'px'
|
||||
if (st.body.style.fontWeight !== String(weight)) st.body.style.fontWeight = String(weight)
|
||||
fitBody(st, text, size)
|
||||
fitOuterBox(st, node)
|
||||
if (st.bold.className !== 'iwb-sticky-btn' + (weight === 600 ? ' iwb-sticky-btn-on' : '')) {
|
||||
st.bold.className = 'iwb-sticky-btn' + (weight === 600 ? ' iwb-sticky-btn-on' : '')
|
||||
}
|
||||
if (st.dot.style.background !== bg) st.dot.style.background = bg
|
||||
}
|
||||
|
||||
// ---------------- 面板 ----------------
|
||||
var ctxForPanel = null
|
||||
var noteList = []
|
||||
|
||||
function refreshList() {
|
||||
if (!ctxForPanel) return
|
||||
var host = ctxForPanel.__stickyPanelRoot
|
||||
if (!host || typeof host.innerHTML !== 'undefined' && !host.innerHTML && !host.appendChild) return
|
||||
var list = host.querySelector ? host.querySelector('.iwb-sticky-list') : null
|
||||
if (!list) return
|
||||
// 尽力从画布读回便利贴节点(只读画布能力给了 getNodes)
|
||||
var nodes = []
|
||||
try {
|
||||
var api = ctxRef && ctxRef.canvas
|
||||
if (api && typeof api.getNodes === 'function') nodes = api.getNodes() || []
|
||||
} catch (e) { nodes = [] }
|
||||
var mine = nodes.filter(function (n) { return String(n.type || '').indexOf('plugin:sticky:') === 0 })
|
||||
// 用最近插入的本地记录补足(getNodes 快照不含自定义状态没关系,这里只显示文本)
|
||||
var seen = {}
|
||||
var rows = []
|
||||
mine.concat(noteList).forEach(function (n) {
|
||||
var key = n.id
|
||||
if (!key || seen[key]) return
|
||||
seen[key] = 1
|
||||
var text = String((n.data && n.data.text) || '').replace(/\s+/g, ' ').slice(0, 30) || '(空便利贴)'
|
||||
rows.push({ id: key, text: text })
|
||||
})
|
||||
while (list.firstChild) list.removeChild(list.firstChild)
|
||||
rows.slice(-20).forEach(function (r) {
|
||||
var row = el('div', { className: 'iwb-sticky-row' })
|
||||
row.appendChild(el('span', { className: 'iwb-sticky-row-txt' }, r.text))
|
||||
var go = el('button', { className: 'iwb-sticky-go', type: 'button' }, '定位')
|
||||
go.addEventListener('click', function () {
|
||||
try { if (ctxRef && ctxRef.canvas && typeof ctxRef.canvas.focusNode === 'function') ctxRef.canvas.focusNode(r.id) } catch (e) { /* noop */ }
|
||||
})
|
||||
row.appendChild(go)
|
||||
list.appendChild(row)
|
||||
})
|
||||
}
|
||||
|
||||
function mountPanel(host, ctx) {
|
||||
ensureStyle()
|
||||
ctxForPanel = ctx
|
||||
host.textContent = ''
|
||||
host.style.minWidth = '0'; host.style.minHeight = '0'; host.style.height = '100%'
|
||||
var wrap = el('div', { className: 'iwb-sticky-panel' })
|
||||
wrap.appendChild(el('div', { className: 'iwb-sticky-panel-tip' },
|
||||
'在画布上放一张便利贴:字调大当说明标题,字调小放多行正文。点右下角拖动手柄可改变便签大小。'))
|
||||
var add = el('button', { className: 'iwb-sticky-add', type: 'button' }, '+ 插入便利贴')
|
||||
add.addEventListener('click', function () { insertNote() })
|
||||
wrap.appendChild(add)
|
||||
var list = el('div', { className: 'iwb-sticky-list' })
|
||||
wrap.appendChild(list)
|
||||
host.appendChild(wrap)
|
||||
ctxForPanel.__stickyPanelRoot = host
|
||||
refreshList()
|
||||
}
|
||||
|
||||
function insertNote() {
|
||||
var api = ctxRef && ctxRef.canvas
|
||||
if (!api || typeof api.createNode !== 'function') return null
|
||||
var id = api.createNode('plugin:sticky:sticky', null, null, {
|
||||
text: '', fontSize: DEFAULT_SIZE, fontWeight: 400, bgColor: DEFAULT_BG,
|
||||
})
|
||||
if (id) {
|
||||
noteList.push({ id: id, data: { text: '' } })
|
||||
refreshList()
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
ctxRef = null
|
||||
ctxForPanel = null
|
||||
noteList = []
|
||||
}
|
||||
|
||||
global.IWBPluginHost.register({
|
||||
id: 'sticky',
|
||||
name: '便利贴',
|
||||
version: '1.0.7',
|
||||
apiVersion: 1,
|
||||
capabilities: ['panels', 'nodeTypes', 'canvas'],
|
||||
}, function (ctx) {
|
||||
ctxRef = ctx
|
||||
if (ctx.nodes && typeof ctx.nodes.register === 'function') {
|
||||
ctx.nodes.register({
|
||||
id: 'sticky',
|
||||
title: '便利贴',
|
||||
defaults: {},
|
||||
ports: { in: false, out: false },
|
||||
height: 180,
|
||||
render: renderSticky,
|
||||
})
|
||||
}
|
||||
if (ctx.ui && typeof ctx.ui.registerPanel === 'function') {
|
||||
ctx.ui.registerPanel({
|
||||
id: 'sticky',
|
||||
title: '便利贴',
|
||||
icon: 'note',
|
||||
mount: mountPanel,
|
||||
})
|
||||
}
|
||||
return { dispose: dispose }
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -0,0 +1,343 @@
|
||||
// 便利贴插件本地契约测试(纯 node,不依赖 playwright / 真浏览器)。
|
||||
// 用最小 DOM / window stub 跑真实 src/index.js(IIFE),验证:
|
||||
// manifest 字段 / 节点类型注册(标题/不连线/height)/ 面板注册 /
|
||||
// CSS 脚本执行时就注入 / 字号闭集与 A+/A− / 粗细切换 / 8 色背景 + 色轮自定义 /
|
||||
// 多行文本写回 data / 幂等同步(编辑中不覆盖、值变才写 DOM)/ 插入走 createNode(null,null)。
|
||||
//
|
||||
// 运行:node sticky/tools/harness.mjs (退出码 0 = 全过)
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const ENTRY = path.resolve(HERE, '../src/index.js')
|
||||
const source = readFileSync(ENTRY, 'utf8')
|
||||
|
||||
let failed = 0
|
||||
const check = (name, ok, detail) => {
|
||||
if (!ok) failed++
|
||||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||||
}
|
||||
|
||||
// ---------- 极简 DOM stub ----------
|
||||
function makeNode(tag) {
|
||||
return {
|
||||
tagName: String(tag).toUpperCase(),
|
||||
children: [], parentNode: null, _text: '', attrs: {}, listeners: {},
|
||||
style: {}, className: '', hidden: false, value: '',
|
||||
// textarea 自适应高度需要 scrollHeight:按「行数 × 行高 + 上下 padding」模拟。
|
||||
get scrollHeight() {
|
||||
if (String(tag).toUpperCase() !== 'TEXTAREA') return 0
|
||||
const lines = Math.max(1, String(this.value || '').split('\n').length)
|
||||
const size = parseFloat(this.style.fontSize) || 14
|
||||
return Math.ceil(lines * size * 1.7) + 24
|
||||
},
|
||||
get textContent() { return this._text },
|
||||
set textContent(v) { this._text = String(v); this.children = [] },
|
||||
get firstChild() { return this.children[0] || null },
|
||||
appendChild(c) { this.children.push(c); c.parentNode = this; return c },
|
||||
removeChild(c) { const i = this.children.indexOf(c); if (i >= 0) this.children.splice(i, 1); return c },
|
||||
setAttribute(k, v) { this.attrs[k] = String(v); if (k === 'style') this.style = parseStyle(String(v)) },
|
||||
removeAttribute(k) { delete this.attrs[k] },
|
||||
getAttribute(k) { return k in this.attrs ? this.attrs[k] : null },
|
||||
focus() { this.__doc && (this.__doc.activeElement = this) },
|
||||
blur() { this.__doc && this.__doc.activeElement === this && (this.__doc.activeElement = null); this.fire('blur') },
|
||||
addEventListener(ev, fn) { (this.listeners[ev] = this.listeners[ev] || []).push(fn) },
|
||||
fire(ev, data) {
|
||||
const payload = Object.assign({ target: this, stopPropagation() {} }, data)
|
||||
let n = this
|
||||
while (n) {
|
||||
;(n.listeners[ev] || []).forEach((fn) => fn(payload))
|
||||
n = n.parentNode
|
||||
}
|
||||
},
|
||||
querySelector(cls) {
|
||||
const needle = cls.replace('.', '')
|
||||
const q = [this]
|
||||
while (q.length) {
|
||||
const n = q.shift()
|
||||
if (String(n.className).split(/\s+/).indexOf(needle) >= 0) return n
|
||||
q.push(...(n.children || []))
|
||||
}
|
||||
return null
|
||||
},
|
||||
click() { this.fire('click') },
|
||||
}
|
||||
}
|
||||
function parseStyle(s) {
|
||||
const out = {}
|
||||
s.split(';').forEach((part) => {
|
||||
const i = part.indexOf(':')
|
||||
if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim()
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
function runPlugin() {
|
||||
const head = makeNode('head')
|
||||
const bodyEl = makeNode('body')
|
||||
const document = {
|
||||
head, documentElement: head, body: bodyEl, activeElement: null,
|
||||
createElement: (tag) => { const n = makeNode(tag); n.__doc = document; return n },
|
||||
createTextNode: (t) => ({ nodeType: 3, textContent: String(t) }),
|
||||
getElementById: (id) => findById(head, id) || findById(bodyEl, id),
|
||||
}
|
||||
const registrations = []
|
||||
let panelApi = null, nodeApi = null
|
||||
const updates = []
|
||||
const createCalls = []
|
||||
const host = {
|
||||
IWBPluginHost: {
|
||||
register(manifest, factory) {
|
||||
registrations.push({ manifest, factory })
|
||||
},
|
||||
},
|
||||
document,
|
||||
React: null,
|
||||
}
|
||||
const ctx = {
|
||||
nodes: { register(def) { nodeApi = def; return true } },
|
||||
ui: { registerPanel(def) { panelApi = def; return true } },
|
||||
canvas: {
|
||||
createNode(type, x, y, data) { createCalls.push({ type, x, y, data }); return 'n1' },
|
||||
getNodes() { return [] },
|
||||
focusNode() {},
|
||||
},
|
||||
}
|
||||
const sandbox = Object.assign(host, {
|
||||
console: { log() {}, warn() {}, error() {} },
|
||||
window: host,
|
||||
globalThis: host,
|
||||
})
|
||||
vm.createContext(sandbox)
|
||||
vm.runInContext(source, sandbox)
|
||||
// 触发工厂
|
||||
registrations[0].factory(ctx)
|
||||
return { registrations, manifest: registrations[0].manifest, nodeApi, panelApi, ctx, updates, createCalls, document, head }
|
||||
}
|
||||
function findById(root, id) {
|
||||
if (root.attrs && root.attrs.id === id) return root
|
||||
for (const c of root.children || []) { const r = findById(c, id); if (r) return r }
|
||||
return null
|
||||
}
|
||||
|
||||
// ---------- 测试 ----------
|
||||
const r = runPlugin()
|
||||
|
||||
check('manifest.id = sticky', r.manifest.id === 'sticky')
|
||||
check('manifest.name = 便利贴', r.manifest.name === '便利贴')
|
||||
check('manifest.version = 1.0.7', r.manifest.version === '1.0.7')
|
||||
check('manifest.apiVersion = 1', r.manifest.apiVersion === 1)
|
||||
check('capabilities 含 panels/nodeTypes/canvas',
|
||||
['panels', 'nodeTypes', 'canvas'].every((c) => r.manifest.capabilities.includes(c)))
|
||||
check('CSS 在脚本执行时就注入(#iwb-sticky-style)', !!findById(r.head, 'iwb-sticky-style'))
|
||||
|
||||
check('节点类型已注册', !!r.nodeApi)
|
||||
check('节点 ports 全关(不连线)', r.nodeApi && r.nodeApi.ports.in === false && r.nodeApi.ports.out === false)
|
||||
check('节点 title = 便利贴', r.nodeApi && r.nodeApi.title === '便利贴')
|
||||
check('节点有 render 函数', r.nodeApi && typeof r.nodeApi.render === 'function')
|
||||
check('面板已注册', !!r.panelApi && typeof r.panelApi.mount === 'function')
|
||||
|
||||
// 构造节点 host 并渲染(带 onUpdate 收集 patch)
|
||||
function makeNodeHost() {
|
||||
const h = makeNode('div')
|
||||
h.__updates = []
|
||||
const props = { onUpdate(id, patch) { h.__updates.push({ id, patch }) } }
|
||||
const node = { id: 'n1', type: 'plugin:sticky:sticky', data: { text: '标题', fontSize: 14, fontWeight: 400, bgColor: '#FCE8B0' } }
|
||||
r.nodeApi.render(node, props, h)
|
||||
return { h, node, props }
|
||||
}
|
||||
const nh = makeNodeHost()
|
||||
check('节点体注入 .iwb-sticky-node', !!findByClass(nh.h, 'iwb-sticky-node'))
|
||||
check('节点体有工具条 A+/A−/B + 色板按钮', !!findByClass(nh.h, 'iwb-sticky-tools') && !!findByClass(nh.h, 'iwb-sticky-pal'))
|
||||
check('节点体有 textarea', findByClass(nh.h, 'iwb-sticky-body') && findByClass(nh.h, 'iwb-sticky-body').tagName === 'TEXTAREA')
|
||||
check('默认文本同步到 textarea', findByClass(nh.h, 'iwb-sticky-body').value === '标题')
|
||||
|
||||
// v1.0.2:色板挂在工具条内(top:100% 落调色按钮下方),不再贴便签底部右下角盖住 resize 手柄
|
||||
const toolsBox = findByClass(nh.h, 'iwb-sticky-tools')
|
||||
const palBox = findByClass(nh.h, 'iwb-sticky-pal')
|
||||
check('色板挂在工具条内(跟随调色按钮,不盖 resize 手柄)', palBox && palBox.parentNode === toolsBox)
|
||||
check('色板 CSS top:100%(落按钮下方)', /\.iwb-sticky-pal\{position:absolute;top:100%/.test(injectedCssOf(r)))
|
||||
// v1.0.2:textarea 高度随内容自适应(flex:0 0 auto + JS 写 height)
|
||||
check('textarea flex:0 0 auto(不 flex 撑满留白)', /\.iwb-sticky-body\{flex:0 0 auto/.test(injectedCssOf(r)))
|
||||
function injectedCssOf(rr) { return (findById(rr.head, 'iwb-sticky-style') || {}).textContent || '' }
|
||||
const taInit = findByClass(nh.h, 'iwb-sticky-body')
|
||||
check('textarea 显式 rows=1(不预留默认第二行)', taInit.getAttribute('rows') === '1')
|
||||
check('textarea 初始高度按内容算出(贴字)', parseFloat(taInit.style.height) > 0)
|
||||
check('调色圆点推到工具条最右(右上)', /\.iwb-sticky-dot\{[^}]*margin-left:auto/.test(injectedCssOf(r)))
|
||||
|
||||
// v1.0.3:宿主外框 minHeight 来自 node.h —— 旧 h 会把便签撑出一截空白且手柄拖不下去。
|
||||
// 用带父节点卡片的 host 复现:渲染后必须把外框 minHeight 校正成内容高度,并同步改正 node.h。
|
||||
const card = makeNode('div')
|
||||
card.style.minHeight = '360px'
|
||||
const host2 = makeNode('div')
|
||||
card.appendChild(host2)
|
||||
const node2 = { id: 'n2', type: 'plugin:sticky:sticky', h: 360,
|
||||
data: { text: '范例', fontSize: 40, fontWeight: 600, bgColor: '#FCE8B0' } }
|
||||
r.nodeApi.render(node2, { onUpdate() {} }, host2)
|
||||
const expectedH = Math.round(30 + parseFloat(findByClass(host2, 'iwb-sticky-body').style.height) + 2)
|
||||
check('外框 minHeight 覆盖为内容高度(不再被旧 h 撑住)', card.style.minHeight === expectedH + 'px',
|
||||
'card=' + card.style.minHeight + ' expected=' + expectedH + 'px')
|
||||
check('旧 node.h 校正为内容高度(resize 起点贴字)', node2.h === expectedH, 'h=' + node2.h)
|
||||
// 用户之后手动拖大的 h 不能被再次压回(仍然可拖大拖小)
|
||||
node2.h = 260
|
||||
r.nodeApi.render(node2, { onUpdate() {} }, host2)
|
||||
check('用户拖大后的 h 保留(可拖大)', node2.h === 260 && card.style.minHeight === '260px',
|
||||
'h=' + node2.h + ' minH=' + card.style.minHeight)
|
||||
|
||||
// v1.0.6:自动跟随内容的 h 必须双向伸缩——两行退回一行时外框要跟着缩回去。
|
||||
const card3 = makeNode('div')
|
||||
const host3 = makeNode('div')
|
||||
card3.appendChild(host3)
|
||||
const node3 = { id: 'n3', type: 'plugin:sticky:sticky',
|
||||
data: { text: '一行', fontSize: 40, fontWeight: 400, bgColor: '#FCE8B0' } }
|
||||
const pass3 = { onUpdate() {} }
|
||||
r.nodeApi.render(node3, pass3, host3)
|
||||
const hOneLine = node3.h
|
||||
node3.data.text = '第一行\n第二行'
|
||||
r.nodeApi.render(node3, pass3, host3)
|
||||
const hTwoLines = node3.h
|
||||
check('文本一行变两行:外框自动长高', hTwoLines > hOneLine, hOneLine + ' → ' + hTwoLines)
|
||||
node3.data.text = '一行'
|
||||
r.nodeApi.render(node3, pass3, host3)
|
||||
check('文本两行退回一行:外框自动缩回(v1.0.6)',
|
||||
node3.h === hOneLine && card3.style.minHeight === hOneLine + 'px',
|
||||
'h=' + node3.h + ' minH=' + card3.style.minHeight)
|
||||
|
||||
function findByClass(root, cls) {
|
||||
const needle = cls.split('.').filter(Boolean).pop()
|
||||
const q = [root]
|
||||
while (q.length) {
|
||||
const n = q.shift()
|
||||
if (String(n.className).split(/\s+/).indexOf(needle) >= 0) return n
|
||||
q.push(...(n.children || []))
|
||||
}
|
||||
return null
|
||||
}
|
||||
const btn = (cls) => {
|
||||
const q = [nh.h]
|
||||
while (q.length) {
|
||||
const n = q.shift()
|
||||
if (String(n.className).split(/\s+/).indexOf(cls) >= 0) return n
|
||||
q.push(...(n.children || []))
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// A+ → +2 步进(无上限)
|
||||
btn('iwb-sticky-btn') // 占位,实际按 data-act 找
|
||||
const plus = nh.h.querySelectorAll ? null : findByAct(nh.h, 'plus')
|
||||
function findByAct(root, act) {
|
||||
const q = [root]
|
||||
while (q.length) {
|
||||
const n = q.shift()
|
||||
if (n.attrs && n.attrs['data-act'] === act) return n
|
||||
q.push(...(n.children || []))
|
||||
}
|
||||
return null
|
||||
}
|
||||
findByAct(nh.h, 'plus').fire('click', { target: findByAct(nh.h, 'plus') })
|
||||
check('A+ 写 fontSize=16(+2 步进)', nh.h.__updates.some((u) => u.patch.fontSize === 16))
|
||||
findByAct(nh.h, 'minus').fire('click', { target: findByAct(nh.h, 'minus') })
|
||||
check('A− 写 fontSize=12(−2 步进)', nh.h.__updates.some((u) => u.patch.fontSize === 12))
|
||||
// 无上限:把数据设成 100,A+ 仍继续涨(旧闭集会钳回 24)
|
||||
nh.node.data.fontSize = 100
|
||||
nh.h.__updates.length = 0
|
||||
findByAct(nh.h, 'plus').fire('click', { target: findByAct(nh.h, 'plus') })
|
||||
check('字号无上限(100 → 102)', nh.h.__updates.some((u) => u.patch.fontSize === 102))
|
||||
// 字号变大 → textarea 高度跟着涨(贴字自适应)
|
||||
const taSize = findByClass(nh.h, 'iwb-sticky-body')
|
||||
const hBefore = parseFloat(taSize.style.height)
|
||||
nh.node.data.fontSize = 40
|
||||
r.nodeApi.render(nh.node, nh.props, nh.h)
|
||||
check('字号 14→40 时 textarea 高度重算变大', parseFloat(taSize.style.height) > hBefore)
|
||||
nh.node.data.fontSize = 14
|
||||
findByAct(nh.h, 'bold').fire('click', { target: findByAct(nh.h, 'bold') })
|
||||
check('B 切 fontWeight=600', nh.h.__updates.some((u) => u.patch.fontWeight === 600))
|
||||
|
||||
// 色板:展开 + 点第 3 个色块(橙)写 bgColor
|
||||
const paletteBtn = findByAct(nh.h, 'palette')
|
||||
paletteBtn.fire('click', { target: paletteBtn })
|
||||
const pal = findByClass(nh.h, 'iwb-sticky-pal')
|
||||
check('点背景按钮展开色板', pal.hidden === false)
|
||||
const swatches = []
|
||||
;(function walk(n) { (n.children || []).forEach((c) => { if (String(c.className).indexOf('iwb-sticky-pal-sw') >= 0) swatches.push(c); walk(c) }) })(pal)
|
||||
check('色板有 8 个预设色', swatches.length === 8)
|
||||
swatches[2].fire('click', { target: swatches[2] })
|
||||
check('点色块写 bgColor=#EF9F27', nh.h.__updates.some((u) => u.patch.bgColor === '#EF9F27'))
|
||||
check('选色后色板收起', pal.hidden === true)
|
||||
check('有色轮自定义按钮', !!findByAct(nh.h, 'wheel'))
|
||||
|
||||
// v1.0.7:自定义调色(色轮)也必须自动收起面板
|
||||
paletteBtn.fire('click', { target: paletteBtn })
|
||||
check('再次展开色板(自定义调色前)', pal.hidden === false)
|
||||
const wheelBtn = findByAct(nh.h, 'wheel')
|
||||
wheelBtn.fire('click', { target: wheelBtn })
|
||||
check('点色轮打开取色器时色板自动收起', pal.hidden === true)
|
||||
const colorInput = findByAct(nh.h, 'color')
|
||||
check('有隐藏的原生取色 input', !!colorInput && colorInput.tagName === 'INPUT')
|
||||
paletteBtn.fire('click', { target: paletteBtn })
|
||||
nh.h.__updates.length = 0
|
||||
colorInput.value = '#C0392B'
|
||||
colorInput.fire('change', { target: colorInput })
|
||||
check('自定义色写回 bgColor', nh.h.__updates.some((u) => u.patch.bgColor === '#C0392B'))
|
||||
check('自定义色确认后色板保持收起', pal.hidden === true)
|
||||
|
||||
// ---- 单击选中 / 双击编辑状态机 ----
|
||||
const ta = findByClass(nh.h, 'iwb-sticky-body')
|
||||
check('正文默认只读(单击穿透给节点选中/拖动)', ta.readOnly === true && ta.getAttribute('readonly') !== null)
|
||||
const injectedCss = (findById(r.head, 'iwb-sticky-style') || {}).textContent || ''
|
||||
check('根容器 flex:1 撑满宿主(修拖动后漏底)', /\.iwb-sticky-node\{[^}]*flex:1 1 auto/.test(injectedCss))
|
||||
check('纸片圆角对齐宿主节点(node-radius - 1px 边框)',
|
||||
/\.iwb-sticky-node\{[^}]*border-radius:calc\(var\(--iwb-node-radius, 14px\) - 1px\)/.test(injectedCss))
|
||||
const rootNode = findByClass(nh.h, 'iwb-sticky-node')
|
||||
const dblEv = { target: ta, stopPropagation() {} }
|
||||
rootNode.fire('dblclick', dblEv)
|
||||
check('双击正文进入编辑(解除 readonly)', ta.readOnly === false && ta.className.indexOf('iwb-sticky-editing') >= 0)
|
||||
check('双击后 textarea 获得焦点', r.document.activeElement === ta)
|
||||
// 编辑态下 pointerdown 冒泡被拦(不拖节点)
|
||||
let downStopped = false
|
||||
ta.fire('pointerdown', { target: ta, stopPropagation() { downStopped = true } })
|
||||
check('编辑态 pointerdown 不冒泡给宿主', downStopped)
|
||||
// 失焦退出编辑、恢复只读
|
||||
ta.fire('blur')
|
||||
check('失焦退出编辑(恢复 readonly)', ta.readOnly === true && ta.className.indexOf('iwb-sticky-editing') < 0)
|
||||
|
||||
// 多行文本写回(编辑态)
|
||||
ta.fire('dblclick', { target: ta, stopPropagation() {} })
|
||||
ta.value = '第一行\n第二行\n第三行'
|
||||
ta.fire('input', { target: ta })
|
||||
check('多行文本写回 data.text', nh.h.__updates.some((u) => u.patch.text === '第一行\n第二行\n第三行'))
|
||||
|
||||
// 幂等同步:编辑中不覆盖正在输入的 textarea
|
||||
const active = ta
|
||||
r.document.activeElement = active
|
||||
nh.node.data.text = '外部改的值'
|
||||
r.nodeApi.render(nh.node, nh.props, nh.h)
|
||||
check('编辑中的 textarea 不被外部数据覆盖', ta.value === '第一行\n第二行\n第三行')
|
||||
ta.fire('blur') // 退出编辑态
|
||||
r.document.activeElement = null
|
||||
nh.node.data.text = '外部改的值'
|
||||
r.nodeApi.render(nh.node, nh.props, nh.h)
|
||||
check('非编辑态 textarea 跟随数据更新', ta.value === '外部改的值')
|
||||
|
||||
// 深/浅背景自动取文字色(运行时算,不写死)
|
||||
const st = nh.h.__sticky
|
||||
check('浅色背景取深色文字', st.root.style.color === '#1c2333')
|
||||
nh.node.data.bgColor = '#1F3350'
|
||||
r.nodeApi.render(nh.node, nh.props, nh.h)
|
||||
check('深色背景取白色文字', st.root.style.color === '#ffffff')
|
||||
|
||||
// 面板插入便利贴走 createNode(null,null)
|
||||
const panelHost = makeNode('div')
|
||||
r.panelApi.mount(panelHost, r.ctx)
|
||||
const addBtn = findByClass(panelHost, 'iwb-sticky-add')
|
||||
addBtn.fire('click', { target: addBtn })
|
||||
check('插入便利贴调 canvas.createNode', r.createCalls.length === 1)
|
||||
check('createNode 类型 = plugin:sticky:sticky', r.createCalls[0] && r.createCalls[0].type === 'plugin:sticky:sticky')
|
||||
check('createNode 坐标 null/null(宿主找空位)', r.createCalls[0] && r.createCalls[0].x === null && r.createCalls[0].y === null)
|
||||
check('插入带默认样式数据', r.createCalls[0] && r.createCalls[0].data.fontSize === 14 && r.createCalls[0].data.bgColor === '#FCE8B0')
|
||||
|
||||
console.log('\n' + (failed ? '✗ ' + failed + ' 项失败' : '✓ 全部通过'))
|
||||
process.exit(failed ? 1 : 0)
|
||||
+85
-9
@@ -1,6 +1,6 @@
|
||||
# 风格库(style-source)
|
||||
|
||||
资源库面板里的 AI 绘画风格浏览器。310 个风格、12 个分类,点到哪个风格就能把**预览图**插进画布(`ref` 节点)或把**提示词**插进画布(`prompt` 节点)。
|
||||
资源库面板里的 AI 绘画风格浏览器。367 个风格、12 个分类,点到哪个风格就能把**预览图**插进画布(`ref` 节点)、把**提示词**插进画布(`prompt` 节点),或者插一个**样式节点**(带变量表单、能继续连线的插件节点)。
|
||||
|
||||
风格数据来自开源项目 [style-source](https://github.com/malongan/style-source),插件直连它的 GitHub Pages 静态资源,无后端、无 Key。
|
||||
|
||||
@@ -9,8 +9,9 @@
|
||||
| 声明 | 用途 |
|
||||
|---|---|
|
||||
| `panels` | 注册「风格库」标签页到资源库面板 |
|
||||
| `canvas` | `getNodes` / `getSelectedNode`(算插入坐标) |
|
||||
| `canvasWrite` | `createImageNode`(插参考图)/ `createNode('prompt', …)`(插提示词) |
|
||||
| `canvas` | `getNodes` / `getSelectedNode`(算插入坐标)/ `screenToWorld`(拖拽落点) |
|
||||
| `canvasWrite` | `createImageNode`(插参考图)/ `createNode`(插提示词、插样式节点) |
|
||||
| `nodeTypes` | 注册 `style` 变体(`ctx.nodes.register`,注意 key 是 `nodes` 不是 `nodeTypes`) |
|
||||
|
||||
## 交互
|
||||
|
||||
@@ -24,6 +25,68 @@
|
||||
- **点击**:不传坐标(`createNode('prompt', null, null, …)`),交给宿主 `findSpot()` —— 从**视口中心**向外螺旋扫空位、跳过已有节点、并**避开压在画布上的浮层**(资源中心 / 插件面板 / 左右侧栏)。插件只有节点的 `x/y`,拿不到 pan/zoom 和实测高度,自己排必然插到看不见的地方或压在别的节点上(旧版就是「选中节点右侧固定 380,无避让」)。
|
||||
- **按住拖到画布上松手**:节点落在**松手点**(`screenToWorld` 换算,节点左上角对齐光标)。落点由宿主算:pan/zoom 只有它知道。拖动中光标下跟一张幽灵卡片,进入画布会提示「松手放这里」;松手点不在画布上(还在面板里)⇒ 取消。位移不足 6px 视作点击,两条路径并存、互不干扰。落点**压住已有节点或被浮层遮住**时,宿主会就近吸附到旁边的空位(`snapToFreeSpot`,20px 间隙、优先留在视口内);落在空处则**完全按松手点**,不偏移。
|
||||
|
||||
## 样式节点(v1.3.2)
|
||||
|
||||
详情页底部有三颗按钮:**样式节点**(新)· 插入参考图 · 插入提示词。三颗都支持「点一下自动找位」和「按住拖到画布松手」,原两颗的行为一个字没改。
|
||||
|
||||
样式节点与「插入提示词」的区别:后者落一个纯 `prompt` 节点,文本一落地就和风格库脱钩(认不出是哪条风格、改一个词只能删了重插);样式节点把来源和结构一起带上,随画布存档。
|
||||
|
||||
### 节点数据契约
|
||||
|
||||
```js
|
||||
{
|
||||
variant: 'style', // 宿主降级兜底:类型没注册时仍认得出是插件节点
|
||||
styleId, name, code, // 来源三件套(一张画布常有七八个样式节点,靠它分辨)
|
||||
outKind: 'prompt', // 关键标记:连线规则里等同提示词节点
|
||||
promptTpl, // 原始模板(库里模板以后更新,也不会偷偷改老画布)
|
||||
varMeta: [{ n, l, d, x }], // 变量名 / 中文标签 / 填写说明 / 是否在数据里声明过
|
||||
vars: {}, // 用户填的值
|
||||
text: '', // 派生值,恒等于 fillTpl(promptTpl, vars)
|
||||
preview, refName, // 缩略图 URL(不存 base64)
|
||||
refOn, refUrl, // 示例图作参考
|
||||
collapsed: false, // 变量区收起
|
||||
}
|
||||
```
|
||||
|
||||
### v1.3.1(2026-11-14)CSS 改为激活时注入
|
||||
|
||||
`ensureStyle()` 原本只在 `mount()`(面板)里调用 ⇒ **没打开过「风格库」面板**时,节点体是无样式的裸 DOM,
|
||||
`<img class="iwb-ssn-thumb">` 按原图尺寸铺满整个节点(真机表现:图片"跑出来了")。
|
||||
现在 setup 注册变体前注入一次,`renderStyleNode()` 里再兜一次(幂等)。
|
||||
回归用例:`tools/e2e-test-site.mjs` 第 9 段(不开面板直接进存档画布,断言缩略图宽高 ≈56px)。
|
||||
|
||||
### v1.3.2(2026-11-14)注入点再提前到脚本执行 + 缩略图内联兜底
|
||||
|
||||
1.3.1 那一版**发布链路上只传了字节、市场清单没换**(市场仍指 1.3.0 的 hash),所以用户看到的还是坏的那版。
|
||||
连带教训:只验证「本地/合成宿主通过」不够,发布后必须回读市场索引与字节(见根 README「发布到市场」末尾的验收要求)。
|
||||
|
||||
这次的改动:
|
||||
|
||||
- `ensureStyle()` 在**脚本执行时**就调一次(`CSS` 常量下面紧跟一句),不再等 setup —— 三处兜底:
|
||||
脚本执行 → setup → `renderStyleNode()`。
|
||||
- 缩略图加行内兜底(`width/height:56px`、`object-fit:cover`、`border-radius:7px`):
|
||||
样式表因为任何原因失效时,图片不会按原图尺寸把节点撑爆。样式正常时取值与 CSS 相同,零视觉差异。
|
||||
- `tools/harness.mjs` 新增闸门:宿主 stub **不调用 setup** 的情况下,`#iwb-ss-style` 必须已存在且含
|
||||
`.iwb-ssn-thumb` 规则 —— 这条会直接挡住「样式注入点又跑到 mount 里」的回退。
|
||||
|
||||
### 五条硬约束(改之前先读)
|
||||
|
||||
1. **节点上没有生成按钮。** 注册变体时不传 `run`,宿主就不会渲染那颗按钮。出图一律交给下游生图节点(它已经处理了四家渠道差异、尺寸收敛、并发与恢复)。
|
||||
2. **首行单行布局。** label 左、输入右,一行 28px。早期草稿是「label 一行 + 输入一行」= 56px/个,Vigo 那批 24 个变量就是 1344px,画布上没法看。变量**全部露出**(不折叠),靠「收起」按钮收起来。
|
||||
3. **`vars` 与 `text` 必须在同一次 `onUpdate` 里写回**,且输入走 300ms 防抖 + 失焦立刻提交。分开写会出现「界面填了新词、生图拿的旧词」;不防抖则每敲一个字符就让整张图的 `graphCacheKey` 失效、撤销历史炸掉。
|
||||
4. **端口只出不入**(`ports: { in: false, out: true }`)。宿主任务图对未知类型走兜底分支 `children.length ? children : [自己]`——一旦有人连一条边进来,它自己渲染的提示词就会被上游文本顶掉,用户填的变量全部失效。
|
||||
5. **节点体是「往 host 里画」,不是返回 vDOM。** 宿主给的 `host` 跨渲染稳定(`app.js` 的 `PluginDomBody`),插件必须做「建一次骨架 + 之后只同步值」;每次重建 DOM 的话,输入框每敲一个字就会失焦。正在编辑的输入框(`document.activeElement`)在同步时要跳过。
|
||||
|
||||
### 示例图作参考
|
||||
|
||||
勾上以后,宿主的任务图会给这个节点补一个**伪 `ref` 节点**(`id = 节点id + ':ref'`,坐标取节点自身 x/y,所以它参与「图片按 X 轴排序」):
|
||||
|
||||
- 连生图节点 → 生图节点的参考图区多一张;
|
||||
- 连组合节点 → 和别的图片节点一样被汇总,再一起传给下游;
|
||||
- 连分层节点 → `nodeRefsOf` 也会把它带出来。
|
||||
|
||||
只存 URL 不转 base64:宿主的 `refArgsOf` 对字符串直接产出 `{ type: 'url' }`,而 URL 参考图本来就是既有的正常路径(`createGenerationJobs` 的注释写着「URL 参考图也定义在 generations 的 image 字段中」)。代价是依赖 CDN 可用性。取消勾选只写 `refOn: false`,**不增删任何节点**,所以不会在画布上留孤儿。
|
||||
|
||||
## 变量:只有提示词里的 `{占位符}` 才算数
|
||||
|
||||
**判断依据只有一条**:`prompt` 里真实出现的 `{名字}`。插入时替换的就是这段文本,所以
|
||||
@@ -116,19 +179,32 @@
|
||||
|
||||
## 不需要改宿主 CSP
|
||||
|
||||
数据与图片都是公网 `https://`,宿主 `_headers` 的 `img-src … https:` / `connect-src … https:` 已经放行。对比 `ai-chat`(连本机 `http://127.0.0.1:3425`)必须单独加端口。
|
||||
数据与图片都是公网 `https://`,桌面宿主 `tauri.conf.json` 的 `img-src … https:` / `connect-src … https:` 已经放行。
|
||||
对比 `ai-chat`(连本机 `http://127.0.0.1:3425`)必须单独加端口。
|
||||
|
||||
## 测试(三层,从快到慢)
|
||||
|
||||
| 层 | 命令 | 覆盖什么 | 依赖 |
|
||||
|---|---|---|---|
|
||||
| 合成宿主 | `node tools/harness.mjs`(88 项) | 面板交互、详情页按钮顺序与同色、节点体结构、变量写入/防抖/不失焦、收起变量、截图 | 无(自带 mock 宿主) |
|
||||
| 线上数据真网 | `node tools/e2e-real.mjs`(10 项) | styles.json 真拉得到、卡片渲染、样式节点入口 | 网络 |
|
||||
| 桌面客户端端到端 | `node tools/e2e-test-site.mjs`(15 项) | **宿主新接口到底接上没有**:进画布 → 开资源库 → 点「样式节点」→ 节点体由插件渲染、示例图默认勾选、变量输入不失焦、多变量不裁切、收起生效 | 桌面客户端已装本插件(`SITE=` 换地址,`HEADED=1` 看着跑) |
|
||||
|
||||
前两支只验插件自己;**第三支才验宿主**,发布宿主改动后必跑。
|
||||
|
||||
## 发布
|
||||
|
||||
`src/index.js` 是手写单文件 IIFE,不构建,直接发布:
|
||||
`src/index.js` 是手写单文件 IIFE,不构建。发布走桌面仓的市场链路,见根 README「发布到市场」:
|
||||
|
||||
```bash
|
||||
cp src/index.js /tmp/plugin-style-source.js
|
||||
cd ../image-workbench-web
|
||||
node scripts/plugins-publish.mjs /tmp/plugin-<其余插件>.js /tmp/plugin-style-source.js --upload --version style-source=1.0.5
|
||||
npm run validate
|
||||
# 桌面仓:node scripts/sync-plugins-from-repo.js && node scripts/gen-market.js
|
||||
# 再把 market/ 上传到 NAS(market.maqiart.eu.org)
|
||||
```
|
||||
|
||||
图标:宿主 `app.js` 的 `PLUGIN_ICONS` 可加 `'style-source': 'palette'`(不加则用面板 manifest 自带的 `palette`,效果一致)。
|
||||
桌面仓同步脚本会算 SRI、生成内容寻址名 `plugin-style-source.<hash12>.js`,按白名单重建市场清单;
|
||||
改版本时同步 `package.json` 的 `version` 与 `src/index.js` 里 manifest 的 `version`。
|
||||
展示用的图标 / 描述在桌面仓 `plugins/meta.json` 里维护。
|
||||
|
||||
## 数据结构(上游 styles.json)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/style-source",
|
||||
"private": true,
|
||||
"version": "1.2.0",
|
||||
"version": "1.3.3",
|
||||
"description": "风格库:资源库面板里浏览 310 个 AI 绘画风格(12 分类 / 搜索 / 变量替换),一键把预览图插入画布 ref 节点、把提示词插入 prompt 节点",
|
||||
"ibwPlugin": {
|
||||
"id": "style-source",
|
||||
|
||||
+351
-6
@@ -138,7 +138,7 @@
|
||||
position: fixed; z-index: 2147483000; left: 0; top: 0; pointer-events: none;
|
||||
padding: 5px 10px; border-radius: 6px; font-size: 12px; line-height: 1.2;
|
||||
font-family: inherit; white-space: nowrap;
|
||||
background: rgba(22, 26, 34, .88); color: #fff;
|
||||
background: color-mix(in srgb, var(--iwb-text, #1c2333) 88%, transparent); color: var(--iwb-on-brand, #fff);
|
||||
border: 1px dashed rgba(255, 255, 255, .55);
|
||||
transform: translate(-2px, -2px);
|
||||
}
|
||||
@@ -283,21 +283,81 @@
|
||||
position: absolute; left: 50%; bottom: 46px; z-index: 20;
|
||||
transform: translateX(-50%) translateY(6px);
|
||||
max-width: 88%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
background: rgba(22, 26, 34, .9); color: #fff;
|
||||
background: color-mix(in srgb, var(--iwb-text, #1c2333) 90%, transparent); color: var(--iwb-on-brand, #fff);
|
||||
font-size: var(--fs-md, 12px); padding: 6px 12px; border-radius: 14px;
|
||||
opacity: 0; pointer-events: none; transition: opacity .18s ease, transform .18s ease;
|
||||
}
|
||||
.iwb-ss-toast.is-show { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||
|
||||
/* ─────────── 样式节点(画布内的节点体,v1.3.0 / 2026-11-14)───────────
|
||||
宿主把这一块交给插件自己画(.iwb-plugin-node-body 不含内边距),所以这里的 padding 是唯一的内边距。
|
||||
宽度以宿主节点默认宽 264 为基准:264 − 24(padding) = 240 内容宽。 */
|
||||
.iwb-ssn { display: flex; flex-direction: column; gap: 9px; padding: 10px 12px; color: var(--iwb-text, #1f2430); font-size: 12px; box-sizing: border-box; }
|
||||
.iwb-ssn-top { display: flex; align-items: flex-start; gap: 9px; }
|
||||
.iwb-ssn-thumb {
|
||||
width: 56px; height: 56px; flex: 0 0 auto; border-radius: 7px; object-fit: cover;
|
||||
background: var(--iwb-layer, #f0f1f4); border: 1px solid var(--iwb-border, #d5d9e0);
|
||||
}
|
||||
.iwb-ssn-thumb.is-empty { display: flex; align-items: center; justify-content: center; font-size: 10px; color: var(--iwb-text2, #6b7280); }
|
||||
.iwb-ssn-meta { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 4px; }
|
||||
.iwb-ssn-name { font-size: 12.5px; font-weight: 600; line-height: 1.25; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.iwb-ssn-code { font-size: 10.5px; color: var(--iwb-text2, #6b7280); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; letter-spacing: .02em; }
|
||||
/* 参考图开关:整行可点(不要求精准点那个小方框 —— 节点在画布上常被缩放) */
|
||||
.iwb-ssn-ref {
|
||||
display: flex; align-items: center; gap: 6px; margin-top: 1px; padding: 3px 6px; border-radius: 6px;
|
||||
background: var(--iwb-layer, #f0f1f4); cursor: pointer; user-select: none;
|
||||
font-size: 11px; color: var(--iwb-text2, #4d5668);
|
||||
}
|
||||
.iwb-ssn-ref input { margin: 0; flex: 0 0 auto; cursor: pointer; }
|
||||
.iwb-ssn-ref > span { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.iwb-ssn-ref > em { flex: 0 0 auto; font-style: normal; opacity: .75; font-size: 10px; }
|
||||
.iwb-ssn-ref.is-on { background: color-mix(in srgb, var(--iwb-brand, #1677ff) 14%, transparent); color: var(--iwb-brand, #1677ff); }
|
||||
.iwb-ssn-ref.is-off { opacity: .72; }
|
||||
.iwb-ssn-toggle {
|
||||
flex: 0 0 auto; width: 22px; height: 22px; padding: 0; margin: 0; border: 0; border-radius: 6px;
|
||||
background: transparent; color: var(--iwb-text2, #6b7280); cursor: pointer; line-height: 1;
|
||||
display: inline-flex; align-items: center; justify-content: center; font-size: 13px;
|
||||
}
|
||||
.iwb-ssn-toggle:hover { background: var(--iwb-layer, #f0f1f4); color: var(--iwb-text, #1f2430); }
|
||||
/* 变量行:label 左、输入右,一行 28px。
|
||||
早期草稿是「label 一行 + 输入一行」= 56px/个,Vigo 那批 24 个变量就是 1344px —— 画布上没法看。
|
||||
单行布局把同样的信息压到 32px/行(含 gap),不删任何字段。 */
|
||||
.iwb-ssn-vars { display: flex; flex-direction: column; gap: 4px; }
|
||||
.iwb-ssn-vars.is-hidden { display: none; }
|
||||
.iwb-ssn-row { display: flex; align-items: center; gap: 8px; height: 28px; }
|
||||
.iwb-ssn-row > label {
|
||||
flex: 0 0 72px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
font-size: 11.5px; color: var(--iwb-text2, #4d5668);
|
||||
}
|
||||
.iwb-ssn-row > label.is-implicit { opacity: .68; }
|
||||
.iwb-ssn-row > input {
|
||||
flex: 1 1 auto; min-width: 0; height: 26px; padding: 0 7px; box-sizing: border-box;
|
||||
border-radius: 6px; border: 1px solid var(--iwb-border, #d5d9e0);
|
||||
background: var(--iwb-bg, #fff); color: inherit; font: inherit; font-size: 11.5px;
|
||||
}
|
||||
.iwb-ssn-row > input:focus { outline: none; border-color: var(--iwb-brand, #1677ff); }
|
||||
.iwb-ssn-row > input::placeholder { color: var(--iwb-text2, #6b7280); opacity: .6; }
|
||||
.iwb-ssn-foot { display: flex; align-items: center; gap: 6px; font-size: 10.5px; color: var(--iwb-text2, #6b7280); }
|
||||
.iwb-ssn-warn { color: var(--iwb-warn, #d97706); }
|
||||
.iwb-ssn-empty { padding: 6px 2px; font-size: 11px; color: var(--iwb-text2, #6b7280); line-height: 1.6; }
|
||||
`
|
||||
|
||||
function ensureStyle() {
|
||||
const id = 'iwb-ss-style'
|
||||
if (typeof document === 'undefined' || !document.createElement) return
|
||||
if (document.getElementById(id)) return
|
||||
try {
|
||||
;(document.head || document.documentElement).appendChild(el('style', { id: id, text: CSS }))
|
||||
} catch (error) { /* 样式注入失败不影响功能,只是丑一点 */ }
|
||||
}
|
||||
|
||||
// v1.3.2(2026-11-14,同一事故的第三次):样式在**脚本执行时**就注入,不等 setup,更不等面板 mount。
|
||||
// 1.3.0 只在 mount() 里注入 —— 从存档直接进画布(面板从不 mount)时节点体是无样式裸 DOM,
|
||||
// `<img class="iwb-ssn-thumb">` 按原图尺寸铺满节点,就是用户看到的「图片都跑出来了 / 样式坏了」。
|
||||
// 1.3.1 把注入提前到 setup,但发布链路只上传了字节、清单没换(线上仍是 1.3.0),等于没修。
|
||||
// 现在三层兜底:脚本执行(这里)→ setup → renderStyleNode。
|
||||
ensureStyle()
|
||||
|
||||
// ---------------- 长提示词:节点内滚动,不让节点越拉越长 ----------------
|
||||
//
|
||||
// 宿主 renderPromptBody 用 autoGrow 把 textarea 高度直接设成 scrollHeight(无上限),
|
||||
@@ -528,6 +588,228 @@
|
||||
return prefAll().thumbOnly === true
|
||||
}
|
||||
|
||||
// ---------------- 样式节点(模块级:注册时就要拿到 render,不能藏在 mount 里)----------------
|
||||
// ---- 样式节点(v1.3.0 / 2026-11-14)----
|
||||
//
|
||||
// 和「插入提示词」的本质区别:那个落一个纯 prompt 节点,文本一落地就和风格库脱钩 ——
|
||||
// 认不出是哪条风格、改一个词只能删了重插。样式节点把这些一起带上(随画布存档):
|
||||
// styleId / name / code 来源三件套(一张画布上常有七八个样式节点,靠它分辨)
|
||||
// promptTpl 原始模板(库里模板以后更新,也不会偷偷改掉老画布)
|
||||
// varMeta / vars / text 变量结构 + 用户填的值 + 渲染结果
|
||||
// outKind = 'prompt' 宿主连线白名单据此把它当提示词节点(可连 gen / combine / batch / llm / prompt)
|
||||
// refOn / refUrl 示例图作参考,走 URL(宿主本来就支持 url 型参考图,不必转 base64)
|
||||
//
|
||||
// ⚠️ 节点上**没有生成按钮**,这是用户 2026-11-14 明确定的:样式节点只负责「把变量填进模板」,
|
||||
// 出图一律交给下游生图节点(它自己已经处理了四家渠道差异、尺寸收敛、并发与恢复)。
|
||||
const STYLE_NODE_TYPE = 'plugin:style-source:style'
|
||||
|
||||
// 节点自带模板,不能再走 varKeys(style)(那要整条 styles.json 记录)。
|
||||
// 语义与 applyVars 完全一致:只替换「用户真填了的」,留空的保留 {原样}
|
||||
// —— 替换成空串会把提示词结构弄丢,用户看不出漏了什么。
|
||||
function fillTpl(tpl, vars) {
|
||||
let text = String(tpl || '')
|
||||
const v = vars || {}
|
||||
for (const name of Object.keys(v)) {
|
||||
const val = String(v[name] == null ? '' : v[name]).trim()
|
||||
if (!val) continue
|
||||
text = text.split('{' + name + '}').join(val)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// 宿主契约:插件节点的 render(node, props, host) 是**往 host 这个真实 DOM 里画**,不是返回 vDOM。
|
||||
// host 跨渲染稳定(宿主用固定 div 承载,见 app.js 的 PluginDomBody)—— 这正是为了不重建 DOM:
|
||||
// 变量输入框一旦被重建,每敲一个字就会失焦。
|
||||
// 所以这里做「建一次骨架 + 之后只同步值」。
|
||||
function renderStyleNode(node, props, host) {
|
||||
// 兜底:万一节点体先于 setup 渲染(宿主注册表现在支持「注册后立刻重画」),
|
||||
// 这一句保证样式一定在 —— 少一次注入就是「缩略图铺满节点」那种事故。
|
||||
ensureStyle()
|
||||
let st = host.__ssn
|
||||
if (!st) {
|
||||
host.textContent = ''
|
||||
st = host.__ssn = buildStyleNodeSkeleton(host)
|
||||
}
|
||||
st.node = node
|
||||
st.props = props
|
||||
syncStyleNode(st, (node && node.data) || {})
|
||||
}
|
||||
|
||||
function buildStyleNodeSkeleton(host) {
|
||||
const thumb = el('img', { class: 'iwb-ssn-thumb', alt: '', loading: 'lazy', draggable: 'false' })
|
||||
thumb.addEventListener('error', () => { thumb.style.display = 'none' })
|
||||
thumb.addEventListener('load', () => { thumb.style.display = '' })
|
||||
// 内联兜底(v1.3.2):`.iwb-ssn-thumb` 的 56px 如果因为样式表缺失/被覆盖没生效,
|
||||
// 浏览器会按图片**原始尺寸**铺开 —— 一张 1024px 的示例图足以把节点撑爆。
|
||||
// 这里用行内样式钉死尺寸:样式表正常时两者取值相同(零视觉差异),样式表失效时至少不炸。
|
||||
thumb.style.width = '56px'
|
||||
thumb.style.height = '56px'
|
||||
thumb.style.flex = '0 0 auto'
|
||||
thumb.style.objectFit = 'cover'
|
||||
thumb.style.borderRadius = '7px'
|
||||
const nameEl = el('div', { class: 'iwb-ssn-name' })
|
||||
const codeEl = el('div', { class: 'iwb-ssn-code' })
|
||||
const refChk = el('input', { type: 'checkbox' })
|
||||
const refTxt = el('span', {})
|
||||
const refNum = el('em', {})
|
||||
const refBox = el('label', { class: 'iwb-ssn-ref' }, [refChk, refTxt, refNum])
|
||||
const toggle = el('button', { class: 'iwb-ssn-toggle', type: 'button', text: '⌃' })
|
||||
const varsBox = el('div', { class: 'iwb-ssn-vars' })
|
||||
const foot = el('div', { class: 'iwb-ssn-foot' })
|
||||
const root = el('div', { class: 'iwb-ssn' }, [
|
||||
el('div', { class: 'iwb-ssn-top' }, [
|
||||
thumb,
|
||||
el('div', { class: 'iwb-ssn-meta' }, [nameEl, codeEl, refBox]),
|
||||
toggle,
|
||||
]),
|
||||
varsBox,
|
||||
foot,
|
||||
])
|
||||
host.appendChild(root)
|
||||
|
||||
const st = { root: root, thumb: thumb, nameEl: nameEl, codeEl: codeEl, refBox: refBox, refChk: refChk, refTxt: refTxt, refNum: refNum, toggle: toggle, varsBox: varsBox, foot: foot, rows: {}, varSig: '', footSig: '', timer: null, draft: null, node: null, props: null }
|
||||
|
||||
// 收起 / 展开:写回 data.collapsed(随存档走),节点高度由宿主实测,不锁 n.h
|
||||
toggle.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
toggle.addEventListener('click', (e) => {
|
||||
e.stopPropagation(); e.preventDefault()
|
||||
if (!st.node || !st.props) return
|
||||
st.props.onUpdate(st.node.id, { collapsed: !(st.node.data && st.node.data.collapsed) })
|
||||
})
|
||||
|
||||
// 参考图开关:只切换 refOn,不增删任何节点(所以取消勾选不会在画布上留孤儿)
|
||||
refChk.addEventListener('change', () => {
|
||||
if (!st.node || !st.props) return
|
||||
const on = Boolean(refChk.checked)
|
||||
st.props.onUpdate(st.node.id, { refOn: on })
|
||||
st.refBox.classList.toggle('is-on', on)
|
||||
st.refBox.classList.toggle('is-off', !on)
|
||||
st.refTxt.textContent = on ? '示例图作参考' : '示例图不作参考'
|
||||
st.refNum.textContent = on ? '1 张' : '0'
|
||||
})
|
||||
return st
|
||||
}
|
||||
|
||||
function commitStyleVars(st) {
|
||||
if (!st.draft) return
|
||||
const vars = Object.assign({}, st.draft)
|
||||
st.draft = null
|
||||
const tpl = String((st.node.data && st.node.data.promptTpl) || '')
|
||||
// vars 与 text 必须**同一次** onUpdate 写回:分开写会出现「界面填了新词、生图拿的旧词」
|
||||
st.props.onUpdate(st.node.id, { vars: vars, text: fillTpl(tpl, vars) })
|
||||
}
|
||||
|
||||
function syncStyleNode(st, d) {
|
||||
const name = String(d.name || '')
|
||||
const nameText = name || '(未命名风格)'
|
||||
if (st.nameEl.textContent !== nameText) st.nameEl.textContent = nameText
|
||||
st.nameEl.title = nameText
|
||||
const codeText = String(d.code || d.styleId || '')
|
||||
if (st.codeEl.textContent !== codeText) st.codeEl.textContent = codeText
|
||||
st.codeEl.title = codeText
|
||||
|
||||
const preview = String(d.preview || '')
|
||||
if (st.thumb.dataset.src !== preview) {
|
||||
st.thumb.dataset.src = preview
|
||||
if (preview) { st.thumb.style.display = ''; st.thumb.style.visibility = ''; st.thumb.src = preview } else {
|
||||
// 没有预览图时**整块不占位**(display:none 而不是 visibility:hidden):
|
||||
// 留 56px 空白会让名称和编号无缘无故右移,看起来像排版错位
|
||||
st.thumb.removeAttribute('src')
|
||||
st.thumb.style.display = 'none'
|
||||
}
|
||||
}
|
||||
|
||||
const hasRef = !!String(d.refUrl || '').trim()
|
||||
const on = d.refOn === true && hasRef
|
||||
if (st.refChk.checked !== on) st.refChk.checked = on
|
||||
// 没有示例图就别让人点了还以为是开关坏了:直接禁用并说明原因
|
||||
if (st.refChk.disabled !== !hasRef) st.refChk.disabled = !hasRef
|
||||
st.refBox.classList.toggle('is-on', on)
|
||||
st.refBox.classList.toggle('is-off', !on)
|
||||
const refLabel = on ? '示例图作参考' : '示例图不作参考'
|
||||
if (st.refTxt.textContent !== refLabel) st.refTxt.textContent = refLabel
|
||||
const refCount = on ? '1 张' : '0'
|
||||
if (st.refNum.textContent !== refCount) st.refNum.textContent = refCount
|
||||
st.refBox.title = on
|
||||
? '出图时会带上这张示例图(在生图节点的参考图区能看到它)'
|
||||
: (hasRef ? '当前只输出提示词,不带这张图;勾上就会带上' : '这条风格没有示例图,无法作参考')
|
||||
|
||||
const collapsed = d.collapsed === true
|
||||
st.varsBox.classList.toggle('is-hidden', collapsed)
|
||||
const toggleText = collapsed ? '⌄' : '⌃'
|
||||
if (st.toggle.textContent !== toggleText) st.toggle.textContent = toggleText
|
||||
st.toggle.title = collapsed ? '展开变量' : '收起变量'
|
||||
|
||||
const meta = Array.isArray(d.varMeta) ? d.varMeta : []
|
||||
const sig = meta.map((m) => m.n).join('\u0000')
|
||||
if (sig !== st.varSig) {
|
||||
st.varSig = sig
|
||||
st.varsBox.textContent = ''
|
||||
st.rows = {}
|
||||
if (!meta.length) {
|
||||
st.varsBox.appendChild(el('div', { class: 'iwb-ssn-empty', text: '这条风格的提示词没有变量,直接连到生图节点即可。' }))
|
||||
} else {
|
||||
for (const m of meta) st.varsBox.appendChild(buildVarRow(st, m))
|
||||
}
|
||||
}
|
||||
|
||||
// 值同步:正在编辑的那个输入框不覆盖(否则光标跳到末尾,等于打断输入)
|
||||
const vars = d.vars || {}
|
||||
for (const m of meta) {
|
||||
const input = st.rows[m.n]
|
||||
if (!input) continue
|
||||
if (input === document.activeElement) continue
|
||||
const cur = String(vars[m.n] == null ? '' : vars[m.n])
|
||||
if (input.value !== cur) input.value = cur
|
||||
}
|
||||
|
||||
const total = meta.length
|
||||
const left = meta.filter((m) => !String(vars[m.n] == null ? '' : vars[m.n]).trim()).length
|
||||
const footText = !total ? '无变量' : (left ? '还有 ' + left + ' 个变量没填(留空的保留 {原样})' : '变量已填完 · 连到生图节点即可出图')
|
||||
const footSig = footText + '|' + (left ? 'warn' : 'ok')
|
||||
if (st.footSig !== footSig) {
|
||||
st.footSig = footSig
|
||||
st.foot.textContent = ''
|
||||
st.foot.appendChild(el('span', { class: left ? 'iwb-ssn-warn' : '', text: footText }))
|
||||
}
|
||||
}
|
||||
|
||||
function buildVarRow(st, m) {
|
||||
const label = el('label', { text: String(m.l || m.n), title: String(m.l || m.n) + (m.d ? ':' + m.d : '') })
|
||||
if (!m.x) label.classList.add('is-implicit') // 数据里没声明过的变量:标签就是占位符名,弱化一点
|
||||
const input = el('input', {
|
||||
type: 'text',
|
||||
placeholder: String(m.d || ('{' + m.n + '}')),
|
||||
spellcheck: 'false',
|
||||
autocomplete: 'off',
|
||||
title: String(m.d || ('留空则保留 {' + m.n + '}')),
|
||||
})
|
||||
input.value = ''
|
||||
// 画布上:点输入框是「编辑」,不能顺带拖动节点
|
||||
input.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
input.addEventListener('input', () => {
|
||||
if (!st.draft) st.draft = Object.assign({}, (st.node && st.node.data && st.node.data.vars) || {})
|
||||
st.draft[m.n] = input.value
|
||||
if (st.timer) global.clearTimeout(st.timer)
|
||||
// 300ms 防抖:每敲一个字符就 onUpdate,会让整张图的 graphCacheKey 失效十几次、撤销历史也炸掉
|
||||
st.timer = global.setTimeout(() => { st.timer = null; commitStyleVars(st) }, 300)
|
||||
})
|
||||
input.addEventListener('blur', () => {
|
||||
if (st.timer) { global.clearTimeout(st.timer); st.timer = null }
|
||||
commitStyleVars(st)
|
||||
})
|
||||
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); input.blur() } })
|
||||
st.rows[m.n] = input
|
||||
return el('div', { class: 'iwb-ssn-row' }, [label, input])
|
||||
}
|
||||
|
||||
// 插件卸载 / 节点体被 LOD 替换时清掉定时器(宿主会在 host 卸载时调这里)
|
||||
renderStyleNode.dispose = function (host) {
|
||||
const st = host && host.__ssn
|
||||
if (st && st.timer) global.clearTimeout(st.timer)
|
||||
if (host) host.__ssn = null
|
||||
}
|
||||
|
||||
// ---------------- 面板实例 ----------------
|
||||
// 每个 mount 容器一个实例:独立 DOM 引用 + 独立 ResizeObserver,数据走 CACHE 共享。
|
||||
|
||||
@@ -669,6 +951,40 @@
|
||||
toast((left ? '已插入提示词(还有 ' + left + ' 个变量没填)' : '已插入提示词') + tail)
|
||||
}
|
||||
|
||||
|
||||
function insertStyleNode(style, at) {
|
||||
const api = ctx.canvas
|
||||
if (!api || typeof api.createNode !== 'function') { toast('当前宿主不支持插入节点(缺 canvasWrite 能力)'); return }
|
||||
const vars = Object.assign({}, CACHE.vars[style.id] || {})
|
||||
const thumb = thumbOf(style)
|
||||
const meta = varKeys(style).map((it) => ({ n: it.name, l: it.label, d: it.desc || '', x: it.declared ? 1 : 0 }))
|
||||
const data = {
|
||||
variant: 'style', // 宿主的降级兜底:类型没注册时仍认得出这是插件节点
|
||||
styleId: String(style.id || ''),
|
||||
name: String(style.name || ''),
|
||||
code: String(style.code || ''),
|
||||
outKind: 'prompt', // 关键标记:让它在连线规则里等同提示词节点
|
||||
promptTpl: String(style.prompt || ''),
|
||||
varMeta: meta,
|
||||
vars: vars,
|
||||
text: fillTpl(style.prompt, vars).trim(),
|
||||
preview: String(thumb || ''),
|
||||
refName: String(style.code || style.id || 'style') + '.png',
|
||||
// 默认勾选:风格库的示例图本来就是这条风格的视觉基准,带上出图更贴。
|
||||
// 只想要文字时在节点上取消勾选即可 —— 一次点击,不产生/不残留任何节点。
|
||||
refOn: Boolean(thumb),
|
||||
refUrl: String(thumb || ''),
|
||||
collapsed: false,
|
||||
}
|
||||
const dropAt = (at && Number.isFinite(at.x) && Number.isFinite(at.y)) ? { x: at.x, y: at.y } : null
|
||||
const id = dropAt
|
||||
? api.createNode(STYLE_NODE_TYPE, dropAt.x, dropAt.y, data)
|
||||
: api.createNode(STYLE_NODE_TYPE, null, null, data)
|
||||
if (!id) { toast('插入失败:样式节点类型未注册(宿主版本较旧?)'); return }
|
||||
const left = meta.filter((m) => !String(vars[m.n] || '').trim()).length
|
||||
toast(left ? '已插入样式节点(还有 ' + left + ' 个变量没填)' : '已插入样式节点')
|
||||
}
|
||||
|
||||
// ---- 拖拽插入:按住按钮 → 拖到画布上松手 → 节点落在松手位置 ----
|
||||
//
|
||||
// 为什么要有第二套交互:点击插入只能由宿主 findSpot 猜位置(视口中心、避开已有节点与浮层),
|
||||
@@ -946,23 +1262,30 @@
|
||||
]))
|
||||
}
|
||||
|
||||
const style0 = style
|
||||
// 新增的第三颗(2026-11-14,用户要求「新增一个插入节点的按钮」,不动原来两颗的行为)
|
||||
ui.btnStyle = el('button', {
|
||||
class: 'iwb-ss-btn', text: '样式节点',
|
||||
title: '插入样式节点:带缩略图、变量表单、示例图开关,连到生图节点即可出图(节点本身不带生成按钮)。也可按住拖到画布上指定位置',
|
||||
onClick: () => { if (ui.justDragged) return; insertStyleNode(style0) },
|
||||
})
|
||||
ui.btnRef = el('button', {
|
||||
class: 'iwb-ss-btn', text: '插入参考图',
|
||||
title: '点击:自动找位置插入参考图;按住拖到画布上松手:放在你指定的位置',
|
||||
onClick: () => { if (ui.justDragged) return; insertImage(style) },
|
||||
})
|
||||
const style0 = style
|
||||
ui.btnPrompt = el('button', {
|
||||
class: 'iwb-ss-btn is-key', text: '插入提示词',
|
||||
title: '点击:自动找位置插入提示词;按住拖到画布上松手:放在你指定的位置。内容按「最大高度」截断显示,节点内可滚动,全文用气泡「放大编辑」⌘E 查看',
|
||||
onClick: () => { if (ui.justDragged) return; insertPrompt(style0) },
|
||||
})
|
||||
attachDragInsert(ui.btnStyle, '样式节点', (at) => insertStyleNode(style0, at))
|
||||
attachDragInsert(ui.btnRef, '参考图', (at) => insertImage(style0, at))
|
||||
attachDragInsert(ui.btnPrompt, '提示词', (at) => insertPrompt(style0, at))
|
||||
|
||||
ui.detail.appendChild(head)
|
||||
ui.detail.appendChild(bodyEl)
|
||||
ui.detail.appendChild(el('div', { class: 'iwb-ss-dfoot' }, [ui.btnRef, ui.btnPrompt]))
|
||||
ui.detail.appendChild(el('div', { class: 'iwb-ss-dfoot' }, [ui.btnStyle, ui.btnRef, ui.btnPrompt]))
|
||||
}
|
||||
|
||||
function renderAll() {
|
||||
@@ -1061,9 +1384,9 @@
|
||||
global.IWBPluginHost.register({
|
||||
id: 'style-source',
|
||||
name: '风格库',
|
||||
version: '1.2.0',
|
||||
version: '1.3.3',
|
||||
apiVersion: 1,
|
||||
capabilities: ['panels', 'canvas', 'canvasWrite'],
|
||||
capabilities: ['panels', 'canvas', 'canvasWrite', 'nodeTypes'],
|
||||
settings: {
|
||||
dataUrl: {
|
||||
type: 'text',
|
||||
@@ -1090,6 +1413,28 @@
|
||||
mount: (host) => mount(host, ctx),
|
||||
})
|
||||
|
||||
// 样式节点变体(v1.3.0)。注意能力名是 nodeTypes、但挂在 ctx 上的 key 是 `nodes`
|
||||
// (plugin-host.js 的 CAPABILITY_API_KEYS:nodeTypes → 'nodes'),写成 ctx.nodeTypes 会静默失效。
|
||||
// 不传 run ⇒ 节点上不会出现「运行」按钮(用户明确要求:出图交给下游生图节点)。
|
||||
//
|
||||
// v1.3.1(2026-11-14,用户报障「图片都跑出来了」):CSS 原先进在 `mount()` 里 ——
|
||||
// 只有打开过「风格库」面板才会注入。但从存档打开画布时,节点体先渲染、面板根本不 mount ⇒
|
||||
// 节点里的 `<img class="iwb-ssn-thumb">` 拿不到 56px 约束,按原图尺寸铺满整个节点。
|
||||
// 现在在注册变体前就把样式注入(mount 里那次是幂等兜底)。
|
||||
ensureStyle()
|
||||
if (ctx.nodes && typeof ctx.nodes.register === 'function') {
|
||||
ctx.nodes.register({
|
||||
id: 'style',
|
||||
title: '样式节点',
|
||||
defaults: {},
|
||||
// 只出不入:宿主任务图的兜底分支是 `children.length ? children : [自己]`,
|
||||
// 一旦被连了入边,样式节点自己渲染的提示词就会被上游文本顶掉,用户填的变量全部失效。
|
||||
ports: { in: false, out: true },
|
||||
height: 360,
|
||||
render: renderStyleNode,
|
||||
})
|
||||
}
|
||||
|
||||
return {}
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
@@ -64,7 +64,7 @@ async function main() {
|
||||
|
||||
await page.goto(`http://127.0.0.1:${port}/`)
|
||||
await page.evaluate(() => {
|
||||
window.__calls = { panels: [], images: [], nodes: [] }
|
||||
window.__calls = { panels: [], images: [], nodes: [], variants: [] }
|
||||
window.__nodes = [{ id: 'n1', type: 'prompt', x: 100, y: 100, data: { text: 'x' } }]
|
||||
window.__sel = { id: 'n1', type: 'prompt', name: 'x' }
|
||||
window.IWBPluginHost = { register(m, s) { window.__m = m; window.__s = s } }
|
||||
@@ -77,6 +77,8 @@ async function main() {
|
||||
settings: { get: (k) => (window.__m.settings[k] || {}).default },
|
||||
storage: null,
|
||||
ui: { registerPanel: (p) => window.__calls.panels.push(p) },
|
||||
// v1.3.0:样式节点变体(宿主能力名 nodeTypes → ctx.nodes)
|
||||
nodes: { register: (v) => { window.__calls.variants.push(v); return true } },
|
||||
canvas: {
|
||||
getNodes: () => window.__nodes,
|
||||
getSelectedNode: () => window.__sel,
|
||||
@@ -99,7 +101,8 @@ async function main() {
|
||||
check('真实网络拉到数据并渲染卡片', Boolean(gotData), 'cards=' + gotData)
|
||||
|
||||
const status = await page.locator('#h .iwb-ss-status').innerText().catch(() => '')
|
||||
check('总数显示 310', /310/.test(status), status.replace(/\n/g, ' '))
|
||||
// 数量随上游数据增长会变(310 → 367);这里只要求「显示的是三位数总量」
|
||||
check('总数显示三位数风格条数', /\b[1-9]\d{2}\b/.test(status), status.replace(/\n/g, ' '))
|
||||
|
||||
// 真实缩略图必须真的解码出来
|
||||
const decoded = await poll(async () => {
|
||||
@@ -114,12 +117,34 @@ async function main() {
|
||||
// 真实 webp → dataURL
|
||||
await page.locator('#h .iwb-ss-card').first().click()
|
||||
await page.waitForTimeout(300)
|
||||
await page.locator('#h .iwb-ss-dfoot .iwb-ss-btn').first().click()
|
||||
await page.locator('#h .iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '插入参考图' }).click()
|
||||
const img = await poll(() => page.evaluate(() => window.__calls.images[0] || null), 30000)
|
||||
check('真实图插入画布(createImageNode 被调用)', Boolean(img))
|
||||
check('dataURL 是真实内容而非空图', Boolean(img) && String(img.dataUrl).length > 5000,
|
||||
img ? 'len=' + String(img.dataUrl).length + ' head=' + String(img.dataUrl).slice(0, 22) : '')
|
||||
|
||||
// v1.3.0:样式节点(真实数据 + 真实模板)
|
||||
const styleCall = await page.evaluate(async () => {
|
||||
const v = window.__calls.variants[0]
|
||||
const btn = [...document.querySelectorAll('#h .iwb-ss-dfoot .iwb-ss-btn')].find((b) => b.textContent === '样式节点')
|
||||
if (!btn) return { noBtn: true }
|
||||
window.__calls.nodes.length = 0
|
||||
btn.click()
|
||||
await new Promise((r) => setTimeout(r, 60))
|
||||
return { hasRender: typeof v.render === 'function', ports: v.ports, call: window.__calls.nodes[0] || null }
|
||||
})
|
||||
check('详情页有「样式节点」按钮,且变体已注册(render + 只出不入)',
|
||||
!styleCall.noBtn && styleCall.hasRender === true && styleCall.ports.in === false && styleCall.ports.out === true,
|
||||
JSON.stringify({ noBtn: styleCall.noBtn, hasRender: styleCall.hasRender, ports: styleCall.ports }))
|
||||
check('样式节点落的是 plugin:style-source:style,数据带 outKind/promptTpl/varMeta',
|
||||
Boolean(styleCall.call) && styleCall.call.t === 'plugin:style-source:style' &&
|
||||
styleCall.call.d.outKind === 'prompt' && typeof styleCall.call.d.promptTpl === 'string' &&
|
||||
Array.isArray(styleCall.call.d.varMeta),
|
||||
styleCall.call ? 't=' + styleCall.call.t + ' varMeta=' + (styleCall.call.d.varMeta || []).length : '未调用')
|
||||
check('未填变量时 text 原样保留 {占位符}(不是被替换成空串)',
|
||||
Boolean(styleCall.call) && (styleCall.call.d.varMeta.length === 0 || /\{[^{}\n]{1,40}\}/.test(String(styleCall.call.d.text))),
|
||||
styleCall.call ? 'text=' + String(styleCall.call.d.text).slice(0, 48) : '未调用')
|
||||
|
||||
check('无 GitHub 资源请求失败', netFail.length === 0, netFail.slice(0, 2).join(' | '))
|
||||
check('无页面 JS 异常', errors.length === 0, errors.slice(0, 2).join(' | '))
|
||||
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
// 真机验收:**测试站上「宿主新接口 + 本插件」端到端**跑通(harness / e2e-real 都覆盖不到的那一层)。
|
||||
//
|
||||
// 为什么单独一支:
|
||||
// - `tools/harness.mjs` 跑在合成宿主里,验不了「宿主的 PluginDomBody / 声明式参考图」是否真的接上;
|
||||
// - `tools/e2e-real.mjs` 验的是「线上真网 + 插件面板」,不去点画布、不落节点。
|
||||
// 这支脚本在**真的 test 站**里:双击进工作台 → 开资源库 → 点风格 → 点「样式节点」→ 检查节点体与输入体验。
|
||||
//
|
||||
// 用法:
|
||||
// node tools/e2e-test-site.mjs # 默认 https://test.image-workbench-web.pages.dev/
|
||||
// SITE=https://xxx.pages.dev/ node tools/e2e-test-site.mjs
|
||||
// HEADED=1 node tools/e2e-test-site.mjs # 看着它跑
|
||||
//
|
||||
// 前置:宿主已部署含「插件节点体 + 声明式参考图」的版本,且 style-source 已在 KV 清单里。
|
||||
// 全程只读:不动线上数据,浏览器用一次性 profile(跑完即弃)。
|
||||
|
||||
import { createRequire } from 'node:module'
|
||||
import path from 'node:path'
|
||||
import fs from 'node:fs'
|
||||
|
||||
const HERE = path.dirname(new URL(import.meta.url).pathname)
|
||||
let chromium = null
|
||||
for (const base of [path.resolve(HERE, '../..'), path.resolve(HERE, '../../../image-workbench-web'), process.cwd()]) {
|
||||
const pkg = path.join(base, 'package.json')
|
||||
if (!fs.existsSync(pkg)) continue
|
||||
try { chromium = createRequire(pkg)('playwright').chromium; break } catch { /* 换下一个 */ }
|
||||
}
|
||||
if (!chromium) {
|
||||
console.error('找不到 playwright:请在插件仓根目录或宿主仓(image-workbench-web)里跑')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const SITE = process.env.SITE || 'https://test.image-workbench-web.pages.dev/'
|
||||
let failed = 0
|
||||
const check = (name, ok, detail) => {
|
||||
if (!ok) failed++
|
||||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||||
}
|
||||
const shot = (name) => page.screenshot({ path: path.join(HERE, 'shot-testsite-' + name + '.png') }).catch(() => {})
|
||||
|
||||
const proxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy
|
||||
const browser = await chromium.launch({
|
||||
headless: process.env.HEADED !== '1',
|
||||
...(proxy ? { proxy: { server: proxy } } : {}),
|
||||
})
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } })
|
||||
const errors = []
|
||||
page.on('pageerror', (e) => errors.push(String(e)))
|
||||
|
||||
await page.goto(SITE, { waitUntil: 'domcontentloaded' })
|
||||
await page.waitForTimeout(1200)
|
||||
// 启停状态只落 localStorage['iwb_plugins'](真机同款键)
|
||||
await page.evaluate(() => {
|
||||
localStorage.setItem('iwb_plugins', JSON.stringify({ 'style-source': { enabled: true, settings: {}, data: {} } }))
|
||||
})
|
||||
await page.reload({ waitUntil: 'domcontentloaded' })
|
||||
await page.waitForTimeout(4000)
|
||||
|
||||
// ── 1. 宿主版本:三处新接口的特征串(压缩后函数名会变,只能查字符串) ──────────
|
||||
const host = await page.evaluate(async () => {
|
||||
const src = await (await fetch('/app.js', { cache: 'no-store' })).text()
|
||||
const ver = await (await fetch('/version.json', { cache: 'no-store' })).json().catch(() => ({}))
|
||||
return {
|
||||
pluginBody: src.includes('iwb-plugin-node-body'),
|
||||
selfRef: src.includes('style-ref.png'),
|
||||
combineTag: src.includes('iwb-combine-src-tag'),
|
||||
version: ver.version || '',
|
||||
len: src.length,
|
||||
}
|
||||
})
|
||||
check('测试站 app.js 含插件节点体 + 声明式参考图 + 组合来源标签', host.pluginBody && host.selfRef && host.combineTag,
|
||||
JSON.stringify({ version: host.version, len: host.len }))
|
||||
|
||||
// ── 2. 插件已启用并激活 ───────────────────────────────────────────────────
|
||||
const list = await page.evaluate(() => {
|
||||
const h = window.IWBPluginHost
|
||||
if (!h) return { noHost: true }
|
||||
const l = typeof h.list === 'function' ? h.list() : []
|
||||
return { list: l.map((p) => ({ id: p.id, version: p.version, enabled: p.enabled, active: p.active, error: p.error })) }
|
||||
})
|
||||
const me = (list.list || []).find((p) => p.id === 'style-source')
|
||||
check('style-source 已启用并激活', Boolean(me && me.active), JSON.stringify(me))
|
||||
|
||||
// ── 3. 进工作台(首页卡片是「双击打开」,单击只是选中) ──────────────────────
|
||||
await page.locator('.iwb-home-card').first().dblclick({ timeout: 8000 })
|
||||
await page.waitForTimeout(3000)
|
||||
const entered = await page.evaluate(() => ({ cards: document.querySelectorAll('.iwb-home-card').length }))
|
||||
check('双击首页卡片进入画布', entered.cards === 0, JSON.stringify(entered))
|
||||
|
||||
// ── 4. 资源库 → 风格库 tab(N 是宿主「开关资源库」的快捷键) ──────────────────
|
||||
await page.evaluate(() => { const a = document.activeElement; if (a && a.blur) a.blur() })
|
||||
await page.keyboard.press('n')
|
||||
await page.waitForTimeout(1200)
|
||||
const tabs = await page.evaluate(() => [...document.querySelectorAll('.iwb-res-tab')].map((b) => (b.textContent || '').trim()))
|
||||
await page.evaluate(() => {
|
||||
const hit = [...document.querySelectorAll('.iwb-res-tab')].find((b) => /风格库/.test(b.textContent || ''))
|
||||
if (hit) hit.click()
|
||||
})
|
||||
check('资源库里有「风格库」tab', tabs.includes('风格库'), JSON.stringify(tabs))
|
||||
|
||||
// 风格数据是直连 GitHub Pages 拉的,首次没缓存时快时慢 ⇒ 轮询,别写死等待
|
||||
await page.waitForFunction(() => document.querySelectorAll('.iwb-ss-card').length > 0, null, { timeout: 30000 }).catch(() => {})
|
||||
await page.waitForTimeout(300)
|
||||
const cards = await page.locator('.iwb-ss-card').count()
|
||||
check('风格库渲染出卡片', cards > 0, String(cards))
|
||||
|
||||
// ── 5. 详情页底部三颗按钮:同行、均分、「样式节点」在最左(不是替换掉原来两颗) ──
|
||||
await page.locator('.iwb-ss-card').first().click()
|
||||
await page.waitForTimeout(900)
|
||||
const footInfo = await page.evaluate(() => {
|
||||
const btns = [...document.querySelectorAll('.iwb-ss-dfoot .iwb-ss-btn')]
|
||||
return { labels: btns.map((b) => (b.textContent || '').trim()), tops: btns.map((b) => Math.round(b.getBoundingClientRect().top)) }
|
||||
})
|
||||
check('详情页底部三颗按钮同行,「样式节点」在最左',
|
||||
footInfo.labels.length === 3 && footInfo.labels[0] === '样式节点' && new Set(footInfo.tops).size <= 1,
|
||||
JSON.stringify(footInfo))
|
||||
|
||||
// ── 6. 点「样式节点」→ 节点落地,节点体由插件渲染 ─────────────────────────────
|
||||
await page.locator('.iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '样式节点' }).first().click()
|
||||
await page.waitForTimeout(1600)
|
||||
await page.keyboard.press('Escape')
|
||||
await page.waitForTimeout(400)
|
||||
await page.keyboard.press('f')
|
||||
await page.waitForTimeout(700)
|
||||
await shot('node')
|
||||
|
||||
const node1 = await page.evaluate(() => {
|
||||
const b = document.querySelector('.iwb-plugin-node-body')
|
||||
if (!b) return { bodies: 0 }
|
||||
const rows = [...b.querySelectorAll('.iwb-ssn-row')]
|
||||
return {
|
||||
bodies: document.querySelectorAll('.iwb-plugin-node-body').length,
|
||||
hasRoot: Boolean(b.querySelector('.iwb-ssn')),
|
||||
name: (b.querySelector('.iwb-ssn-name') || {}).textContent || '',
|
||||
code: (b.querySelector('.iwb-ssn-code') || {}).textContent || '',
|
||||
rows: rows.length,
|
||||
refChecked: b.querySelector('.iwb-ssn-ref input') ? b.querySelector('.iwb-ssn-ref input').checked : null,
|
||||
hasRunBtn: [...b.querySelectorAll('button')].some((x) => /运行|生成/.test(x.textContent)),
|
||||
foot: (b.querySelector('.iwb-ssn-foot') || {}).textContent || '',
|
||||
}
|
||||
})
|
||||
check('样式节点落地且节点体由插件渲染(.iwb-ssn 存在)', node1.hasRoot === true, JSON.stringify(node1).slice(0, 300))
|
||||
check('节点体有名称/编号/变量行,示例图默认勾选,且没有生成按钮',
|
||||
Boolean(node1.name) && Boolean(node1.code) && node1.refChecked === true && node1.hasRunBtn === false,
|
||||
JSON.stringify(node1).slice(0, 300))
|
||||
|
||||
// ── 7. 变量输入不失焦、值不被重渲染覆盖(PluginDomBody 固定容器生效) ─────────
|
||||
const typing = await page.evaluate(async () => {
|
||||
const b = document.querySelector('.iwb-plugin-node-body .iwb-ssn')
|
||||
const input = b && b.querySelector('.iwb-ssn-row input')
|
||||
if (!input) return { noBody: true }
|
||||
input.focus()
|
||||
input.value = '真机测试值'
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
await new Promise((r) => setTimeout(r, 700))
|
||||
const b2 = document.querySelector('.iwb-plugin-node-body .iwb-ssn')
|
||||
const input2 = b2.querySelector('.iwb-ssn-row input')
|
||||
return { sameInput: input === input2, kept: input2.value, focusKept: document.activeElement === input2 }
|
||||
})
|
||||
check('变量输入不失焦、值不被重渲染覆盖',
|
||||
typing.sameInput === true && typing.kept === '真机测试值' && typing.focusKept === true, JSON.stringify(typing))
|
||||
|
||||
// ── 8. 变量多的样式:全部露出、不裁切、单行 28px、收起/展开生效 ──────────────
|
||||
// 上一步把焦点留在了变量输入框里;宿主的快捷键在 INPUT 上直接 return ⇒ 先 blur,否则按 n 只会打出一个字母
|
||||
await page.evaluate(() => { const a = document.activeElement; if (a && a.blur) a.blur() })
|
||||
await page.keyboard.press('n')
|
||||
await page.waitForTimeout(1200)
|
||||
await page.evaluate(() => {
|
||||
const hit = [...document.querySelectorAll('.iwb-res-tab')].find((b) => /风格库/.test(b.textContent || ''))
|
||||
if (hit) hit.click()
|
||||
})
|
||||
await page.waitForFunction(() => document.querySelectorAll('.iwb-ss-card').length > 0, null, { timeout: 30000 }).catch(() => {})
|
||||
|
||||
let picked = null
|
||||
const total = await page.locator('.iwb-ss-card').count()
|
||||
for (let i = 0; i < Math.min(total, 30); i++) {
|
||||
await page.locator('.iwb-ss-card').nth(i).click()
|
||||
await page.waitForTimeout(380)
|
||||
const info = await page.evaluate(() => ({
|
||||
n: document.querySelectorAll('.iwb-ss-dbody .iwb-ss-var').length,
|
||||
title: (document.querySelector('.iwb-ss-dtitle') || {}).textContent || '',
|
||||
}))
|
||||
if (info.n >= 3) { picked = { idx: i, ...info }; break }
|
||||
}
|
||||
check('能找到一个变量 ≥3 的样式(用于压力验证)', Boolean(picked), JSON.stringify(picked))
|
||||
|
||||
if (picked) {
|
||||
await page.locator('.iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '样式节点' }).first().click()
|
||||
await page.waitForTimeout(1600)
|
||||
await page.keyboard.press('Escape')
|
||||
await page.waitForTimeout(400)
|
||||
await page.keyboard.press('f')
|
||||
await page.waitForTimeout(700)
|
||||
await shot('multivar')
|
||||
|
||||
const multi = await page.evaluate(() => {
|
||||
const all = [...document.querySelectorAll('.iwb-plugin-node-body')]
|
||||
const b = all[all.length - 1]
|
||||
if (!b) return { noBody: true }
|
||||
const rows = [...b.querySelectorAll('.iwb-ssn-row')]
|
||||
return {
|
||||
bodies: all.length,
|
||||
rows: rows.length,
|
||||
labels: rows.map((x) => ((x.querySelector('label') || {}).textContent || '')).filter(Boolean),
|
||||
rowH: rows.length ? Math.round(rows[0].getBoundingClientRect().height) : 0,
|
||||
hiddenRows: rows.filter((x) => x.getBoundingClientRect().height < 8).length,
|
||||
scrollH: b.scrollHeight,
|
||||
clientH: b.clientHeight,
|
||||
}
|
||||
})
|
||||
check('变量多的样式:所有变量行都露出、无零高行', multi.rows >= 3 && multi.hiddenRows === 0, JSON.stringify(multi).slice(0, 320))
|
||||
check('节点体没有裁切(scrollHeight ≈ clientHeight)', Math.abs(multi.scrollH - multi.clientH) <= 2,
|
||||
JSON.stringify({ s: multi.scrollH, c: multi.clientH }))
|
||||
check('变量单行高度 28px 量级', multi.rowH >= 24 && multi.rowH <= 32, String(multi.rowH))
|
||||
|
||||
const collapsed = await page.evaluate(async () => {
|
||||
const all = [...document.querySelectorAll('.iwb-plugin-node-body')]
|
||||
const b = all[all.length - 1]
|
||||
const btn = b && b.querySelector('.iwb-ssn-toggle')
|
||||
if (!btn) return { noBtn: true }
|
||||
const before = Math.round(b.querySelector('.iwb-ssn-vars').getBoundingClientRect().height)
|
||||
btn.click()
|
||||
await new Promise((r) => setTimeout(r, 500))
|
||||
const box = b.querySelector('.iwb-ssn-vars')
|
||||
return { before, after: Math.round(box.getBoundingClientRect().height), hidden: box.classList.contains('is-hidden'), tip: btn.title }
|
||||
})
|
||||
check('「收起变量」生效(变量区收起,按钮变成「展开变量」)',
|
||||
collapsed.hidden === true && collapsed.after === 0 && collapsed.tip === '展开变量', JSON.stringify(collapsed))
|
||||
await shot('collapsed')
|
||||
}
|
||||
|
||||
// ── 9. 冷启动:**一次都没打开过「风格库」面板**,节点体也必须是有样式的 ──────────────
|
||||
// v1.3.1 修的事故:CSS 原先进在 mount() 里,从存档打开画布时面板不 mount ⇒ `<img class="iwb-ssn-thumb">`
|
||||
// 拿不到 56px 约束,按原图尺寸铺满整个节点(用户原话「图片都跑出来了」)。
|
||||
{
|
||||
const COLD_NODE = {
|
||||
id: 'cold1', type: 'plugin:style-source:style', x: 260, y: 200, w: 300, h: 380,
|
||||
data: {
|
||||
variant: 'style', styleId: 'cold-style', name: '冷启动样式', code: 'ST9999', outKind: 'prompt',
|
||||
promptTpl: '一张{主体}的图', varMeta: [{ key: '主体', label: '主体' }], vars: { 主体: '手表' },
|
||||
text: '一张手表的图', preview: 'https://example.invalid/cold.png', refName: 'ST9999.png',
|
||||
refOn: true, refUrl: 'https://example.invalid/cold.png', collapsed: false,
|
||||
},
|
||||
}
|
||||
const ws = { workspaces: [{ id: 'w1', name: '冷启动', nodes: [COLD_NODE], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
|
||||
const ctx2 = await browser.newContext({ viewport: { width: 1400, height: 900 } })
|
||||
const p2 = await ctx2.newPage()
|
||||
await p2.addInitScript(({ ws, board }) => {
|
||||
localStorage.clear()
|
||||
localStorage.setItem('iwb_plugins', JSON.stringify({ 'style-source': { enabled: true, settings: {}, data: {} } }))
|
||||
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
|
||||
localStorage.setItem('iwb_ws_active', 'w1')
|
||||
localStorage.setItem('iwb_ws_w1', JSON.stringify(board))
|
||||
}, { ws, board: ws.workspaces[0] })
|
||||
await p2.goto(SITE, { waitUntil: 'domcontentloaded' })
|
||||
await p2.waitForTimeout(1500)
|
||||
await p2.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick().catch(() => {})
|
||||
await p2.waitForFunction(() => Boolean(document.querySelector('.iwb-plugin-node-body')), null, { timeout: 20000 }).catch(() => {})
|
||||
const cold = await p2.evaluate(() => {
|
||||
const th = document.querySelector('.iwb-ssn-thumb')
|
||||
const body = document.querySelector('.iwb-plugin-node-body')
|
||||
const node = document.querySelector('.iwb-node')
|
||||
return {
|
||||
hasBody: Boolean(body),
|
||||
hasStyle: Boolean(document.getElementById('iwb-ss-style')),
|
||||
thumbW: th ? Math.round(th.getBoundingClientRect().width) : 0,
|
||||
thumbH: th ? Math.round(th.getBoundingClientRect().height) : 0,
|
||||
nodeW: node ? Math.round(node.getBoundingClientRect().width) : 0,
|
||||
}
|
||||
})
|
||||
check('冷启动(没开过风格库):节点体成立 + 样式已注入', cold.hasBody && cold.hasStyle, JSON.stringify(cold))
|
||||
check('冷启动:缩略图被 CSS 约束在 56px(不是按原图铺满节点)',
|
||||
cold.thumbW >= 40 && cold.thumbW <= 62 && cold.thumbH >= 40 && cold.thumbH <= 62,
|
||||
JSON.stringify({ w: cold.thumbW, h: cold.thumbH, nodeW: cold.nodeW }))
|
||||
await p2.screenshot({ path: path.join(HERE, 'shot-testsite-coldstart.png') }).catch(() => {})
|
||||
await ctx2.close()
|
||||
}
|
||||
|
||||
check('全程无页面 JS 异常', errors.length === 0, errors.slice(0, 3).join(' | '))
|
||||
|
||||
await browser.close()
|
||||
console.log('')
|
||||
console.log(failed === 0 ? '全部通过' : failed + ' 项失败')
|
||||
process.exit(failed === 0 ? 0 : 1)
|
||||
@@ -134,7 +134,7 @@ async function main() {
|
||||
|
||||
// ---- 合成宿主 ----
|
||||
await page.evaluate(() => {
|
||||
window.__calls = { nodes: [], images: [], panels: [], manifests: [], setups: 0 }
|
||||
window.__calls = { nodes: [], images: [], panels: [], manifests: [], setups: 0, variants: [] }
|
||||
window.__nodes = [
|
||||
{ id: 'n_prompt', type: 'prompt', x: 100, y: 120, data: { text: '原有提示词' } },
|
||||
{ id: 'n_ref', type: 'ref', x: 520, y: 120, data: { name: '参考图' } },
|
||||
@@ -182,10 +182,22 @@ async function main() {
|
||||
check('manifest id/version 与 package.json 一致',
|
||||
manifest.id === 'style-source' && manifest.version === pkgVersion,
|
||||
JSON.stringify({ id: manifest.id, manifest: manifest.version, pkg: pkgVersion }))
|
||||
check('capabilities 含 panels+canvas+canvasWrite',
|
||||
['panels', 'canvas', 'canvasWrite'].every((c) => manifest.caps.includes(c)), manifest.caps.join(','))
|
||||
check('capabilities 含 panels+canvas+canvasWrite+nodeTypes',
|
||||
['panels', 'canvas', 'canvasWrite', 'nodeTypes'].every((c) => manifest.caps.includes(c)), manifest.caps.join(','))
|
||||
check('settings 暴露 dataUrl', manifest.hasDataUrl)
|
||||
|
||||
// v1.3.2 回归闸门:样式表必须在**脚本执行时**就已注入 —— 不依赖 setup,更不依赖面板 mount。
|
||||
// 反面教材(2026-11-14,连续两次报障):1.3.0 只在 mount() 里注入,从存档直接进画布时面板
|
||||
// 从不 mount ⇒ 节点体是无样式裸 DOM,`<img class="iwb-ssn-thumb">` 按原图尺寸铺满整个节点,
|
||||
// 用户看到的就是「图片都跑出来了」「样式全坏了」。上面的宿主 stub 刻意**不调用 setup**,
|
||||
// 所以这条 check 通过 = 注入点足够早。
|
||||
const bootStyle = await page.evaluate(() => {
|
||||
const s = document.getElementById('iwb-ss-style')
|
||||
return { exists: Boolean(s), hasThumbRule: s ? s.textContent.indexOf('.iwb-ssn-thumb') >= 0 : false, len: s ? s.textContent.length : 0 }
|
||||
})
|
||||
check('样式表在脚本执行时就已注入(不开面板、不跑 setup 也在)',
|
||||
bootStyle.exists && bootStyle.hasThumbRule, JSON.stringify(bootStyle))
|
||||
|
||||
// ---- 建面板(窄:320) ----
|
||||
const mounted = await page.evaluate(() => {
|
||||
const ctx = {
|
||||
@@ -193,6 +205,9 @@ async function main() {
|
||||
settings: { get: (k) => (window.__manifest.settings[k] || {}).default },
|
||||
storage: null,
|
||||
ui: { registerPanel: (p) => { window.__calls.panels.push(p) } },
|
||||
// v1.3.0:样式节点变体注册。宿主的能力名是 nodeTypes,但挂在 ctx 上的 key 是 `nodes`
|
||||
//(plugin-host.js 的 CAPABILITY_API_KEYS),这里如实复刻,写错 key 插件那边会静默跳过
|
||||
nodes: { register: (v) => { window.__calls.variants.push(v); return true } },
|
||||
canvas: {
|
||||
getNodes: () => window.__nodes,
|
||||
getSelectedNode: () => window.__sel,
|
||||
@@ -369,7 +384,9 @@ async function main() {
|
||||
check('已填变量不再残留占位符', varResult.hasVars && !varResult.stillHasPlaceholder)
|
||||
|
||||
// ---- 插提示词 ----
|
||||
await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').nth(1).click()
|
||||
// v1.3.0 起 footer 有三颗(样式节点 / 插入参考图 / 插入提示词),按下标取会随顺序飘 —— 改用文案定位
|
||||
const btnPromptSel = page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '插入提示词' })
|
||||
await btnPromptSel.click()
|
||||
await page.waitForTimeout(120)
|
||||
const promptCall = await page.evaluate(() => window.__calls.nodes[0] || null)
|
||||
check('插入提示词调用 createNode', Boolean(promptCall) && promptCall.type === 'prompt', promptCall ? 'type=' + promptCall.type : '未调用')
|
||||
@@ -391,7 +408,7 @@ async function main() {
|
||||
document.body.appendChild(cv)
|
||||
window.__calls.nodes.length = 0
|
||||
})
|
||||
const btnBox = await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').nth(1).boundingBox()
|
||||
const btnBox = await btnPromptSel.boundingBox()
|
||||
const dropX = 700
|
||||
const dropY = 300
|
||||
await page.mouse.move(btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2)
|
||||
@@ -429,8 +446,12 @@ async function main() {
|
||||
await page.evaluate(() => { const cv = document.getElementById('fakeCanvas'); if (cv) cv.remove(); window.__calls.nodes.length = 0 })
|
||||
|
||||
// ---- 插参考图(blob → dataURL) ----
|
||||
await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').first().click()
|
||||
const imgCall = await poll(() => page.evaluate(() => window.__calls.images[0] || null), 8000)
|
||||
// 拖拽用例松手时会设 justDragged 抑制 400ms 内的 click(防「松手回到按钮上又插一次」),
|
||||
// 这里必须等过那个窗口,否则 click 被吞、偶发「未调用 createImageNode」(实测 3 次里 1 次)。
|
||||
await page.waitForTimeout(460)
|
||||
await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '插入参考图' }).click()
|
||||
// 15000 而不是 8000:这条要等一次真实 fetch(blob → FileReader → dataURL),慢机器上 8s 会偶发超时
|
||||
const imgCall = await poll(() => page.evaluate(() => window.__calls.images[0] || null), 15000)
|
||||
check('插入参考图调用 createImageNode', Boolean(imgCall))
|
||||
check('传入的是 data: URL(宿主只认这个)', Boolean(imgCall) && /^data:image\//.test(String(imgCall.dataUrl)), imgCall ? String(imgCall.dataUrl).slice(0, 24) + '…' : '')
|
||||
check('节点名带风格编号', Boolean(imgCall) && /^ST\d+_/.test(String(imgCall.name)), imgCall ? imgCall.name : '')
|
||||
@@ -754,6 +775,189 @@ async function main() {
|
||||
console.log('· 截图:' + shotNarrow)
|
||||
console.log('· 截图:' + shotVars)
|
||||
|
||||
// ---- 样式节点(v1.3.0 / 2026-11-14)----
|
||||
// 用户要求:样式节点只负责「把变量填进模板」,节点上不放生成按钮;能连生图 / 组合 / 批量 / 做事二次编辑。
|
||||
// 插件侧这一半要验的是:变体参数、节点体结构、变量写回语义、参考图开关、以及「重渲染不重建 DOM」。
|
||||
const variant = await page.evaluate(() => {
|
||||
const v = (window.__calls.variants || [])[0]
|
||||
if (!v) return null
|
||||
return {
|
||||
id: v.id, title: v.title, ports: v.ports, height: v.height,
|
||||
hasRun: typeof v.run === 'function', hasRender: typeof v.render === 'function',
|
||||
hasDispose: typeof v.render === 'function' && typeof v.render.dispose === 'function',
|
||||
}
|
||||
})
|
||||
check('注册 style 变体:只出不入端口、无 run(节点上不会有生成按钮)、带 render',
|
||||
Boolean(variant) && variant.id === 'style' && variant.ports && variant.ports.in === false &&
|
||||
variant.ports.out === true && !variant.hasRun && variant.hasRender,
|
||||
JSON.stringify(variant))
|
||||
|
||||
// 建一个和宿主同构的容器(宿主给的是 .iwb-node-body.iwb-plugin-node-body,内部由插件自己画)
|
||||
const nodeBody = await page.evaluate(() => {
|
||||
const v = (window.__calls.variants || [])[0]
|
||||
if (!v || typeof v.render !== 'function') return { built: false }
|
||||
const host = document.createElement('div')
|
||||
host.className = 'iwb-node-body iwb-plugin-node-body'
|
||||
host.id = 'ssnHost'
|
||||
// 独立浮到 hostA 右侧拍留档图,避免被面板遮住(hostA 宽 980,视口 1280)
|
||||
host.style.cssText = 'width:264px;background:#fff;position:fixed;left:1000px;top:20px;z-index:9999'
|
||||
document.getElementById('stage').appendChild(host)
|
||||
window.__ssnHost = host
|
||||
window.__updates = []
|
||||
window.__ssnProps = { nodes: [], edges: [], editingBody: false, setEditingBody: () => {}, onUpdate: (id, patch) => window.__updates.push({ id: id, patch: patch }) }
|
||||
const node = {
|
||||
id: 'n_style1', type: 'plugin:style-source:style', x: 0, y: 0, data: {
|
||||
variant: 'style', styleId: 'st1', name: 'Vigo 银调夜景', code: 'VIGO-08', outKind: 'prompt',
|
||||
promptTpl: 'a {角色} in {场景}, {留空变量}',
|
||||
varMeta: [
|
||||
{ n: '角色', l: '角色', d: '如:银发少女', x: 1 },
|
||||
{ n: '场景', l: '场景', d: '', x: 1 },
|
||||
{ n: '留空变量', l: '留空变量', d: '', x: 0 },
|
||||
],
|
||||
vars: { 角色: '银发少女' }, text: 'a 银发少女 in {场景}, {留空变量}',
|
||||
preview: 'https://malongan.github.io/style-source/previews/probe.webp',
|
||||
refOn: true, refUrl: 'https://example.com/s.png', refName: 'style.png', collapsed: false,
|
||||
},
|
||||
}
|
||||
window.__ssnNode = node
|
||||
v.render(node, window.__ssnProps, host)
|
||||
const q = (s) => host.querySelector(s)
|
||||
const rows = [...host.querySelectorAll('.iwb-ssn-row')]
|
||||
return {
|
||||
built: true,
|
||||
name: q('.iwb-ssn-name') ? q('.iwb-ssn-name').textContent : '',
|
||||
code: q('.iwb-ssn-code') ? q('.iwb-ssn-code').textContent : '',
|
||||
rowCount: rows.length,
|
||||
labels: rows.map((r) => r.querySelector('label').textContent),
|
||||
implicit: rows.map((r) => r.querySelector('label').className),
|
||||
placeholders: rows.map((r) => r.querySelector('input').placeholder),
|
||||
values: rows.map((r) => r.querySelector('input').value),
|
||||
refChecked: q('.iwb-ssn-ref input') ? q('.iwb-ssn-ref input').checked : null,
|
||||
refText: q('.iwb-ssn-ref span') ? q('.iwb-ssn-ref span').textContent : '',
|
||||
foot: q('.iwb-ssn-foot') ? q('.iwb-ssn-foot').textContent : '',
|
||||
hasRunBtn: [...host.querySelectorAll('button')].some((b) => /运行|生成/.test(b.textContent)),
|
||||
thumbShown: (() => { const t = q('.iwb-ssn-thumb'); return Boolean(t) && t.style.display !== 'none' && t.getBoundingClientRect().width > 20 })(),
|
||||
rowH: rows.length ? Math.round(rows[0].getBoundingClientRect().height) : 0,
|
||||
}
|
||||
})
|
||||
check('样式节点体:名称 / 编号 / 变量行齐备,变量全部露出(不折叠)',
|
||||
nodeBody.built && nodeBody.name === 'Vigo 银调夜景' && nodeBody.code === 'VIGO-08' && nodeBody.rowCount === 3,
|
||||
JSON.stringify(nodeBody))
|
||||
check('变量行是单行布局(28px 级),不是「label 一行 + 输入一行」的 56px',
|
||||
nodeBody.built && nodeBody.rowH > 20 && nodeBody.rowH <= 32, 'rowH=' + nodeBody.rowH)
|
||||
check('样式节点上没有「运行 / 生成」按钮(出图交给下游生图节点)',
|
||||
nodeBody.built && nodeBody.hasRunBtn === false, 'hasRunBtn=' + nodeBody.hasRunBtn)
|
||||
check('未填变量用 {原样} 当 placeholder(不是空白框),已填的值回填,未声明的变量标签弱化',
|
||||
nodeBody.built && nodeBody.placeholders[1] === '{场景}' && nodeBody.placeholders[2] === '{留空变量}' &&
|
||||
nodeBody.values[0] === '银发少女' && nodeBody.values[1] === '' && /is-implicit/.test(nodeBody.implicit[2]),
|
||||
JSON.stringify({ ph: nodeBody.placeholders, val: nodeBody.values, cls: nodeBody.implicit }))
|
||||
check('缩略图占 56px 方块并显示(无预览图时整块不占位,名称不会无缘无故右移)',
|
||||
nodeBody.built && nodeBody.thumbShown === true, 'thumbShown=' + nodeBody.thumbShown)
|
||||
check('默认勾选「示例图作参考」,文案写明会带上这张图',
|
||||
nodeBody.built && nodeBody.refChecked === true && nodeBody.refText === '示例图作参考',
|
||||
JSON.stringify({ checked: nodeBody.refChecked, text: nodeBody.refText }))
|
||||
// 留档:节点体实际长什么样(3 个变量 + 参考图开关 + 底栏提示)
|
||||
await page.locator('#ssnHost').screenshot({ path: path.resolve(HERE, 'shot-style-node.png') }).catch(() => {})
|
||||
console.log('· 截图:' + path.resolve(HERE, 'shot-style-node.png'))
|
||||
|
||||
const varCommit = await page.evaluate(async () => {
|
||||
const host = window.__ssnHost
|
||||
const inputs = [...host.querySelectorAll('.iwb-ssn-row input')]
|
||||
window.__updates.length = 0
|
||||
inputs[1].value = '霓虹街头'
|
||||
inputs[1].dispatchEvent(new Event('input', { bubbles: true }))
|
||||
const duringDebounce = window.__updates.length
|
||||
await new Promise((r) => setTimeout(r, 420))
|
||||
const last = window.__updates[window.__updates.length - 1]
|
||||
return {
|
||||
duringDebounce: duringDebounce,
|
||||
count: window.__updates.length,
|
||||
vars: last && last.patch.vars,
|
||||
text: last && last.patch.text,
|
||||
sameCall: Boolean(last && last.patch && last.patch.vars && typeof last.patch.text === 'string'),
|
||||
}
|
||||
})
|
||||
check('变量输入 300ms 防抖后才提交(不是每敲一个字就刷一次图缓存与撤销历史)',
|
||||
varCommit.duringDebounce === 0 && varCommit.count >= 1, JSON.stringify(varCommit))
|
||||
check('vars 与 text 在同一次 onUpdate 写回;新值已替换、留空的仍保留 {原样}',
|
||||
varCommit.sameCall && varCommit.vars['场景'] === '霓虹街头' &&
|
||||
String(varCommit.text).includes('霓虹街头') && String(varCommit.text).includes('{留空变量}'),
|
||||
JSON.stringify({ vars: varCommit.vars, text: varCommit.text }))
|
||||
|
||||
const refToggle = await page.evaluate(() => {
|
||||
const host = window.__ssnHost
|
||||
const chk = host.querySelector('.iwb-ssn-ref input')
|
||||
window.__updates.length = 0
|
||||
chk.checked = false
|
||||
chk.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
const off = window.__updates[0]
|
||||
chk.checked = true
|
||||
chk.dispatchEvent(new Event('change', { bubbles: true }))
|
||||
const on = window.__updates[1]
|
||||
return {
|
||||
offPatch: off && off.patch, onPatch: on && on.patch,
|
||||
label: host.querySelector('.iwb-ssn-ref span').textContent,
|
||||
tone: host.querySelector('.iwb-ssn-ref').className,
|
||||
}
|
||||
})
|
||||
check('参考图开关只改 refOn 一个字段(不增删节点 ⇒ 取消勾选不会在画布上留孤儿)',
|
||||
refToggle.offPatch && refToggle.offPatch.refOn === false && Object.keys(refToggle.offPatch).length === 1 &&
|
||||
refToggle.onPatch && refToggle.onPatch.refOn === true,
|
||||
JSON.stringify(refToggle))
|
||||
|
||||
// 关键回归:宿主 onUpdate 之后会再调一次 render。若插件每次重建 DOM,输入框就会失焦
|
||||
//(表现是「敲一个字光标就跳走」)。这里直接对比渲染前后是不是同一个 input 元素,
|
||||
// 并把「用户正在输入、还没提交」的值设成和数据里不同的字符串 —— 渲染后必须原样保留。
|
||||
const rerender = await page.evaluate(() => {
|
||||
const host = window.__ssnHost
|
||||
const v = window.__calls.variants[0]
|
||||
const input = host.querySelectorAll('.iwb-ssn-row input')[1]
|
||||
input.focus()
|
||||
input.value = '正在输入中'
|
||||
const node = JSON.parse(JSON.stringify(window.__ssnNode))
|
||||
node.data.vars = Object.assign({}, node.data.vars, { 场景: '霓虹街头' })
|
||||
v.render(node, window.__ssnProps, host)
|
||||
const after = host.querySelectorAll('.iwb-ssn-row input')[1]
|
||||
return {
|
||||
sameEl: input === after,
|
||||
keptTyping: after.value,
|
||||
rows: host.querySelectorAll('.iwb-ssn-row').length,
|
||||
focusKept: document.activeElement === after,
|
||||
}
|
||||
})
|
||||
check('二次渲染复用同一批 DOM:输入框没被重建,正在编辑的值不被 data 覆盖(不失焦不跳字)',
|
||||
rerender.sameEl && rerender.rows === 3 && rerender.keptTyping === '正在输入中' && rerender.focusKept,
|
||||
JSON.stringify(rerender))
|
||||
|
||||
const collapse = await page.evaluate(() => {
|
||||
const host = window.__ssnHost
|
||||
const btn = host.querySelector('.iwb-ssn-toggle')
|
||||
window.__updates.length = 0
|
||||
btn.click()
|
||||
return { patch: window.__updates[0] && window.__updates[0].patch, text: btn.textContent }
|
||||
})
|
||||
check('收起变量只写回 collapsed,不动节点高度(高度由宿主实测,写 h 会把自动高度锁死)',
|
||||
collapse.patch && collapse.patch.collapsed === true && !('h' in collapse.patch),
|
||||
JSON.stringify(collapse))
|
||||
|
||||
const footBtns = await page.evaluate(() => {
|
||||
const btns = [...document.querySelectorAll('#hostA .iwb-ss-dfoot .iwb-ss-btn')]
|
||||
return {
|
||||
texts: btns.map((b) => b.textContent),
|
||||
widths: btns.map((b) => Math.round(b.getBoundingClientRect().width)),
|
||||
clipped: btns.filter((b) => b.scrollWidth > b.clientWidth + 1).length,
|
||||
rows: new Set(btns.map((b) => Math.round(b.getBoundingClientRect().top))).size,
|
||||
}
|
||||
})
|
||||
check('详情页底部三颗按钮(新增「样式节点」,原「参考图 / 提示词」保持原名)单行均分',
|
||||
footBtns.texts.length === 3 && footBtns.texts[0] === '样式节点' &&
|
||||
footBtns.texts[1] === '插入参考图' && footBtns.texts[2] === '插入提示词' &&
|
||||
footBtns.rows === 1 && footBtns.clipped === 0 &&
|
||||
Math.max(...footBtns.widths) - Math.min(...footBtns.widths) <= 2,
|
||||
JSON.stringify(footBtns))
|
||||
|
||||
await page.evaluate(() => { if (window.__ssnHost) { window.__ssnHost.remove(); window.__ssnHost = null } })
|
||||
|
||||
check('无页面 JS 异常', errors.length === 0, errors.slice(0, 2).join(' | '))
|
||||
|
||||
await finish()
|
||||
|
||||
+10
-12
@@ -83,29 +83,27 @@
|
||||
> 注意:默认值只对**没保存过设置**的环境生效;已存过 `ratioPct=85` 的旧记录会继续沿用 85,需要手动改成 80。
|
||||
|
||||
## 发布
|
||||
本仓只产出 `src/index.js`(手写单文件 IIFE)。发布走桌面仓的市场链路,见根 README「发布到市场」:
|
||||
|
||||
```bash
|
||||
cd /Users/qiqi/open/github/image-workbench-web
|
||||
cp /Users/qiqi/open/github/iwb-plugins/white-bg-800/src/index.js /tmp/plugin-white-bg-800.js
|
||||
# ⚠️ 必须把所有插件文件一起传入:发布器用「传入的文件」重建 plugins/index.json,不做合并。
|
||||
# 只传自己 → 别的插件会从清单里消失(image-annotate 已实测踩到)。
|
||||
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
|
||||
cp /Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js /tmp/plugin-image-annotate.js
|
||||
cp /Users/qiqi/open/github/iwb-plugins/blank-canvas/src/index.js /tmp/plugin-blank-canvas.js
|
||||
node scripts/plugins-publish.mjs /tmp/plugin-white-bg-800.js /tmp/plugin-xianyi-cutout.js \
|
||||
/tmp/plugin-image-annotate.js /tmp/plugin-blank-canvas.js \
|
||||
--version white-bg-800=1.2.0 # 默认 dry-run,检查 diff 后再加 --upload
|
||||
npm run validate
|
||||
# 桌面仓:node scripts/sync-plugins-from-repo.js && node scripts/gen-market.js
|
||||
# 再把 market/ 上传到 NAS(market.maqiart.eu.org)
|
||||
```
|
||||
|
||||
桌面仓的同步脚本按白名单**一次重建全部插件清单**(不用逐个传文件),改版本时同步
|
||||
`package.json` 的 `version` 与 `src/index.js` 里 manifest 的 `version`。
|
||||
|
||||
## 验证(开发用)
|
||||
- `tools/harness.mjs`:本地 mock 端到端 —— 合成宿主 + `addScriptTag` 加载插件源码本体,在真实 Chromium 里验证
|
||||
manifest / 注册 / `appliesTo` / 白底与透明底 / `fitRect` 居中 / 夹取 / 命名 / 写回 / 错误提示,
|
||||
以及**格式归一化、jpeg 体积、500KB 自动降质、PNG 超限报错、透明底+jpeg 防黑底、双版本双节点与部分成功**。需要 Playwright
|
||||
(可从宿主仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定),不进 CI。
|
||||
(可从桌面仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定),不进 CI。
|
||||
|
||||
```bash
|
||||
node white-bg-800/tools/harness.mjs
|
||||
```
|
||||
- `tools/e2e-site.mjs`:带 CSP 的真实站点端到端(真 KV + SRI + 漂浮菜单 → 新建节点),透明底等设置类用例由 harness 覆盖。
|
||||
- `tools/e2e-site.mjs`:真实桌面客户端的端到端(市场安装 + SRI + 漂浮菜单 → 新建节点),透明底等设置类用例由 harness 覆盖。
|
||||
|
||||
> harness 里的 mock `ctx.log` 必须是**函数**(真实宿主如此),早先写成对象导致凡是走 `ctx.log` 的分支全炸。
|
||||
> 另外几何断言在有损格式下要留 ±4px 容差(jpeg 边缘振铃),精确几何用 `format=png` 的用例测。
|
||||
@@ -8,6 +8,8 @@ POST {apiUrl}/rmbg?crop=true|false # 默认 http://localhost:30092
|
||||
Content-Type: application/octet-stream # 原始图片字节;无 token、无 JSON
|
||||
→ 返回原始 PNG 字节
|
||||
```
|
||||
> 桌面宿主 CSP 的 `connect-src` 放行了 `127.0.0.1:30092` / `localhost:30092`,所以这个本机地址可用;
|
||||
> 改到其它端口需改宿主 `src-tauri/tauri.conf.json` 的 CSP 并重新打包客户端。
|
||||
比原扩展多做的:**补齐了超时**(`AbortController` + 可配 `timeoutMs`,原版没有任何超时)。
|
||||
|
||||
## 入口
|
||||
@@ -17,14 +19,16 @@ Content-Type: application/octet-stream # 原始图片字节;无 token、无 JS
|
||||
## 设置
|
||||
| 键 | 说明 |
|
||||
|---|---|
|
||||
| `apiUrl` | 本地服务地址。**CSP 仅放行 `127.0.0.1` / `localhost` 的 30092 端口** |
|
||||
| `apiUrl` | 本地服务地址。**桌面宿主 CSP 仅放行 `127.0.0.1` / `localhost` 的 30092 端口** |
|
||||
| `crop` | 抠图后裁掉多余透明像素(对应接口 `crop` 参数) |
|
||||
| `timeoutMs` | 超时毫秒(默认 120000) |
|
||||
|
||||
## 发布
|
||||
本仓只产出 `src/index.js`(手写单文件 IIFE)。发布走桌面仓的市场链路,见根 README「发布到市场」:
|
||||
|
||||
```bash
|
||||
cd /Users/qiqi/open/github/image-workbench-web
|
||||
# 两个发布器现在都会写 SRI integrity(.mjs 默认 dry-run,--upload 才写 KV)
|
||||
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
|
||||
node scripts/plugins-publish.mjs /tmp/plugin-xianyi-cutout.js --upload --version xianyi-cutout=1.0.1
|
||||
npm run validate
|
||||
# 桌面仓:同步 → 生市场 → 上传 market/ 到 NAS(market.maqiart.eu.org)
|
||||
```
|
||||
|
||||
改版本时同步 `package.json` 的 `version` 与 `src/index.js` manifest 的 `version`。
|
||||
Reference in new issue
Block a user