Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f095157a02 | ||
|
|
918be6627e | ||
|
|
9ceaa7d699 | ||
|
|
70613a4112 | ||
|
|
f47f85dfa7 | ||
|
|
d83a3816fe | ||
|
|
aacb75c297 | ||
|
|
8dfc376ae0 | ||
|
|
c2bf0d3f9d | ||
|
|
2d587a2559 | ||
|
|
9649ae0398 | ||
|
|
c2ac777547 | ||
|
|
23cba0ccf3 | ||
|
|
6e6bc3389d | ||
|
|
27a0ad9952 | ||
|
|
4d353cb911 | ||
|
|
135823494b | ||
|
|
8a851ad941 | ||
|
|
3fd5fcf9ec | ||
|
|
2917fcef56 | ||
|
|
ce56d7bc21 | ||
|
|
c4aa9a60c9 | ||
|
|
bde4abc29c | ||
|
|
607af65b04 | ||
|
|
9384b7857c | ||
|
|
f57bc240d7 | ||
|
|
b8d19e6eda | ||
|
|
e1d4f90374 | ||
|
|
e20dda594b | ||
|
|
e614fca7a3 |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
* text=auto
|
||||
*.js text eol=lf
|
||||
*.css text eol=lf
|
||||
*.json text eol=lf
|
||||
*.md text eol=lf
|
||||
*.mjs text eol=lf
|
||||
*.sh text eol=lf
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
# IWB 插件避坑总索引(2026-11-26)
|
||||
|
||||
> 每个插件目录下的 `PITFALLS.md` 是**该插件专属**的硬约束;本文件只放跨插件共性。
|
||||
> 这些文件只留在源仓,不会被打进插件 zip(`sync-plugins-from-repo` / `gen-market` 只取 manifest/main/style/assets)。
|
||||
|
||||
## 跨插件共性
|
||||
|
||||
1. **插件样式在宿主之后加载**:同优先级会覆盖宿主;需要宿主兜底的规则(如选中态)必须用更高优先级,不能假设插件 CSS 会赢。
|
||||
2. **用户动作失败必须可见**:`settings.set` / 写盘失败不能 `catch {}` 静默;至少 toast/tooltip/可见状态。
|
||||
3. **版本三处一致**:`package.json`、入口 `version`、市场索引;否则客户端按版本比较不会更新。
|
||||
4. **旧客户端 fallback**:新增宿主能力(如 `saveNodeImage`、原生菜单)必须有旧路径;不能假设所有用户已升级。
|
||||
5. **原生 webview 永远在 DOM 之上**:任何浮层要么用原生菜单,要么 park 网页,要么放在不重叠区域;`z-index` 无效。
|
||||
6. **SPA 地址**:不要只依赖页面加载事件;宿主轮询 `canvas_webview_state`,插件只读 `st.pageUrl`。
|
||||
7. **发版前跑本插件 harness/测试**,再 `sync-plugins-from-repo`,最后 `gen-market` + 上传;插件文档不打包。
|
||||
|
||||
## 插件文档
|
||||
|
||||
- [browser](browser/PITFALLS.md):原生菜单/SPA 地址/收藏目标组
|
||||
- [image-annotate](image-annotate/PITFALLS.md):覆盖保存事务/桌面 cache 引用
|
||||
- [gallery](gallery/PITFALLS.md):选中态/勾选点/补存
|
||||
- [album](album/PITFALLS.md):宫格 hover 只缩放/不位移
|
||||
@@ -369,7 +369,7 @@
|
||||
var sel = selectedNode()
|
||||
if (!sel) { warn('请先在画布选中一个节点'); return }
|
||||
var img = null
|
||||
try { img = await ctx.canvas.getNodeImage(sel.id) } catch (error) { img = null }
|
||||
try { img = await ctx.canvas.getNodeImage(sel.id, { max: 2048 }) } catch (error) { img = null }
|
||||
var imgUrl = img && (img.dataUrl || img.url)
|
||||
if (!imgUrl) { warn('选中的节点没有可发送的图片'); return }
|
||||
content = [
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# album 插件避坑事项
|
||||
|
||||
> 维护:改宫格 hover / 尺寸后先读本文件。
|
||||
> 版本:1.1.4(2026-11-26)
|
||||
|
||||
## 1. 网格 hover 只做 scale,不位移
|
||||
|
||||
- 宫格是固定正方形网格;hover 用 `translateY` 会让相邻格的 hover 判定抖动;
|
||||
- 当前方案:`scale(1.08)` + 双层深阴影 + 2px 品牌描边(`outline` 内缩,不改 border 宽度,图片不会被挤动);
|
||||
- 所有过渡走 `--iwb-motion-hover/ease-hover`,并支持 `prefers-reduced-motion`。
|
||||
|
||||
## 2. `{__file}` 的 fs 授权会随重启失效
|
||||
|
||||
- 相册“只引用不复制字节”依赖 Tauri fs scope;这个 scope 是**运行时**的,重启就没了。
|
||||
- 症状:相册宫格还能看到旧缩略图(插件文件缓存命中),但组合节点/参考图显示感叹号;只有本次会话新导入的图正常。
|
||||
- 宿主修复:`grant_paths` 把路径持久化到 `file-grants.json`,启动恢复;并在读画布后扫描所有 `__file` 再 grant 一次(兼容旧数据)。
|
||||
- 插件侧不要假设 `ctx.images.dataUrl(src)` 永久可读;失败时按“失联”展示,并提供重新定位。
|
||||
- **重选文件夹必须按归一化路径就地更新**:旧实现直接 `items.push`,坏格留在前面、重复项排到后面/下一页,用户看到的就是“重选也不出缩略图”。Windows 路径大小写不敏感,比较前统一斜杠并 toLowerCase。
|
||||
- 重选时清 `st.missing`、删旧缩略图缓存、把 key 加入 `forceThumbs`,强制从原图重做;`<img onerror>` 也要能绕过坏缓存重读一次。
|
||||
|
||||
## 3. 不要把路径写成 `#` 或相对 URL
|
||||
|
||||
- 相册只接收本地图片路径;远程 URL 会在我这边加载失败;
|
||||
- 文件夹导入后路径要保留绝对路径,不能只存文件名。
|
||||
|
||||
## 4. 版本与市场
|
||||
|
||||
- 改 `styles.css` 必须同时 bump `package.json` + 入口 `version`(若入口有),否则市场按版本比较不会更新;
|
||||
- 本文件不打包,避免增大 zip。
|
||||
|
||||
## 5. 最小回归清单
|
||||
|
||||
- [ ] 宫格 hover 只缩放,相邻格不抖
|
||||
- [ ] 深色/浅色主题下描边都可见
|
||||
- [ ] 选中态(1px)与 hover(2px)叠加不冲突
|
||||
- [ ] 减少动效偏好下无缩放
|
||||
|
||||
## 6. 缩略图两个坑会互相伪装(1.1.6)
|
||||
|
||||
- **`applyThumb` 里不能判 `img.isConnected`**:命中内存缓存那条分支是在 `btn.appendChild(img)` **之前**调用的,
|
||||
此刻元素必然「未连接」⇒ 直接 return ⇒ `src` 永远赋不上。症状极具误导性:
|
||||
**导入后整片空白,切走画布再回来却正常**(换宿主后内存缓存为空,走的是异步分支,那时元素已连接)。
|
||||
磁盘缓存其实一直是好的,所以看日志/看缓存文件都会得出「缩略图读到了」的错误结论。
|
||||
- 正确做法:同步分支直接 `img.src = url`;存活判断只放在**异步回调**里(等图期间宫格可能已被重建丢掉)。
|
||||
- 回归测试:`image-workbench-desktop/tests/iwb-album-thumbs.spec.js`(断言重建后每格都有 src)。
|
||||
- **JPEG 没有 alpha**:`canvas.toDataURL('image/jpeg')` 会把透明像素编码成**纯黑** `rgba(0,0,0,255)`,
|
||||
抠图/透明 PNG 在宫格里就是一格格黑方块。含透明像素必须走 PNG(隔点采样 alpha 通道判定),
|
||||
不含透明的照片仍走 JPEG(省体积)。
|
||||
- **改编码策略必须换缓存名**:文件名里带版本代号(`t2-`),且读缓存时两种后缀都试、
|
||||
写成功后再删旧版本与另一格式 —— 否则用户升级后仍旧命中旧的黑底 JPEG,修复等于没发。
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/album",
|
||||
"private": true,
|
||||
"version": "1.1.2",
|
||||
"version": "1.2.5",
|
||||
"description": "相册:一个节点装多张本地图(只引用不复制),宫格自适应分页,一图一任务 / 批量两种模式批量生图",
|
||||
"ibwPlugin": {
|
||||
"id": "album",
|
||||
|
||||
+384
-47
@@ -66,10 +66,32 @@
|
||||
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(/^.*[\\/]/, '')
|
||||
// Windows 路径大小写不敏感;重选同一文件夹时 dialog 可能回不同大小写,必须按平台归一化后再去重
|
||||
const WIN = typeof navigator !== 'undefined' && /Windows/i.test(String(navigator.userAgent || ''))
|
||||
const normPath = (p) => { const s = String(p || '').replace(/\\/g, '/'); return WIN ? s.toLowerCase() : s }
|
||||
const str = (v) => (v == null ? '' : String(v))
|
||||
|
||||
// ── 缩略图(插件私有缓存,几十 KB/张,不碰画布存储)────────────
|
||||
const thumbNameOf = (key) => 't-' + hash32(key) + '.jpg'
|
||||
// 编码代号(1.1.6):
|
||||
// · 1.1.5 及以前一律 JPEG —— 而 JPEG 没有 alpha,canvas 的透明像素编码后是**纯黑**
|
||||
// (Chromium 实测 rgba(0,0,0,255))⇒ 抠图/透明 PNG 在相册里是一格格黑方块。
|
||||
// · 现在「含 alpha 走 PNG,否则 JPEG 0.85」;代号进文件名,旧黑底缓存自然不再命中。
|
||||
const THUMB_REV = '2'
|
||||
const thumbBase = (key) => 't' + THUMB_REV + '-' + hash32(key)
|
||||
// 宿主文件白名单只认 jpg/jpeg/png/webp,后缀必须与实际字节一致(读回时按文件头嗅探 mime)
|
||||
const thumbNameOf = (key, ext) => thumbBase(key) + '.' + (ext === 'png' ? 'png' : 'jpg')
|
||||
const thumbNames = (key) => [thumbNameOf(key, 'png'), thumbNameOf(key, 'jpg')]
|
||||
// 1.1.5 及以前的缓存名(永远是 JPEG),写新图时顺手清掉,别让黑底缩略图在磁盘里越积越多
|
||||
const oldThumbName = (key) => 't-' + hash32(key) + '.jpg'
|
||||
// keepExt:刚写成功的那一份不能删(png/jpg 只留一个),其余变体清掉
|
||||
function dropThumbFile (ctx, key, keepExt) {
|
||||
if (!ctx || !ctx.files || !key) return
|
||||
const keep = keepExt ? thumbNameOf(key, keepExt) : ''
|
||||
for (const n of thumbNames(key).concat([oldThumbName(key)])) {
|
||||
if (keep && n === keep) continue
|
||||
try { const p = ctx.files.remove(n); if (p && typeof p.catch === 'function') p.catch(() => {}) } catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
// 缩略图缓存键(1.1.0 修「串味」):旧实现是 `fileRefOf(src) || it.name`,一旦固化(src 变成
|
||||
// {__blob})或从别处导入,路径就没了 ⇒ 键退化成纯文件名 ⇒ 不同目录下的 1.png 共用同一张缩略图。
|
||||
@@ -90,6 +112,9 @@
|
||||
return 'n:' + str(n)
|
||||
}
|
||||
|
||||
// 返回 { url, ext };失败返回 null。
|
||||
// alpha 判定:缩放后隔 4 个像素采样 alpha 通道(256² 画布全读也就 256KB 一次性缓冲)。
|
||||
// 只有确实含透明像素才付 PNG 的体积代价 —— 照片仍走 JPEG,缓存总量不会膨胀。
|
||||
function makeThumb (dataUrl) {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
@@ -103,12 +128,18 @@
|
||||
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('') }
|
||||
let alpha = false
|
||||
try {
|
||||
const d = c2.getImageData(0, 0, w, h).data
|
||||
for (let i = 3; i < d.length; i += 16) { if (d[i] < 250) { alpha = true; break } }
|
||||
} catch (e) { /* 读不出像素就按不透明处理(IMG 被污染时 JPEG 也不会更糟) */ }
|
||||
if (alpha) resolve({ url: cv.toDataURL('image/png'), ext: 'png' })
|
||||
else resolve({ url: cv.toDataURL('image/jpeg', THUMB_Q), ext: 'jpg' })
|
||||
} catch (e) { resolve(null) }
|
||||
}
|
||||
img.onerror = () => resolve('')
|
||||
img.onerror = () => resolve(null)
|
||||
img.src = dataUrl
|
||||
} catch (e) { resolve('') }
|
||||
} catch (e) { resolve(null) }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -143,6 +174,7 @@
|
||||
const st = {
|
||||
nodeId: node.id,
|
||||
thumbs: new Map(), // key → dataURL(内存缓存)
|
||||
forceThumbs: new Set(), // 需要绕过旧缩略图缓存、重新读原图的 key(重选文件夹/缩略图损坏)
|
||||
pending: new Map(), // key → Promise(并发去重:格子挂载和预生成会同时要同一张)
|
||||
missing: new Set(), // 失联文件的 key
|
||||
busy: '',
|
||||
@@ -152,7 +184,19 @@
|
||||
}
|
||||
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('一图一任务'))
|
||||
const modeLabel = el('label', { className: 'iwb-album-toggle' }, track, document.createTextNode('单图任务'))
|
||||
// v1.2.0:文件夹监控开关(桌面端才有路径能力)
|
||||
const fTrack = el('span', { className: 'iwb-album-track' }, el('i', null))
|
||||
const folderLabel = el('label', { className: 'iwb-album-toggle iwb-album-folder-toggle' }, fTrack, document.createTextNode('文件夹监控'))
|
||||
folderLabel.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
folderLabel.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
const cur = st.node || node
|
||||
const d = (cur && cur.data) || {}
|
||||
const next = d.sourceMode === 'folder' ? 'mixed' : 'folder'
|
||||
update(st.props || props, cur, { sourceMode: next })
|
||||
if (next === 'folder' && !folderOf(cur)) pickFolderForMonitor(ctx, st)
|
||||
})
|
||||
modeLabel.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
modeLabel.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
@@ -167,18 +211,25 @@
|
||||
// 一键清空(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)
|
||||
bar.appendChild(modeLabel); bar.appendChild(folderLabel); 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: '把引用复制进画布存储(删源文件/分享画布前用)' }, '固化')
|
||||
// v1.2.0:文件夹模式专用(手动刷新,不做自动监听)
|
||||
const btnPaste = el('button', { className: 'iwb-album-btn', title: '从剪贴板粘贴图片(截图 / 网页复制 / 访达复制文件都行)' }, '粘贴')
|
||||
const btnRefresh = el('button', { className: 'iwb-album-btn', title: '重新读取文件夹:新增的加入、消失的移除(尊重忽略名单)' }, '刷新')
|
||||
const btnReload = el('button', { className: 'iwb-album-btn', title: '清空忽略名单并整本重新读取(会重置勾选)' }, '全部重载')
|
||||
const folderNote = el('div', { className: 'iwb-album-foldernote' }, '文件夹监控:只读该目录第一层 · 最多 500 张 · 拖拽 / 粘贴 / 添加已隐藏')
|
||||
const folderMsg = el('div', { className: 'iwb-album-foldermsg' })
|
||||
const folderPath = el('div', { className: 'iwb-album-folderpath' })
|
||||
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 tools = el('div', { className: 'iwb-album-tools' }, [btnAdd, btnDir, btnPaste, btnSettle, btnRefresh, btnReload, seg])
|
||||
|
||||
const hint = el('div', { className: 'iwb-album-hint' })
|
||||
const grid = el('div', { className: 'iwb-album-grid' })
|
||||
@@ -193,9 +244,9 @@
|
||||
// 现在只看大图走「点击放大镜 → 宿主全屏预览(props.onPreview)」,点图片外或 Esc 自动退出。
|
||||
|
||||
host.textContent = ''
|
||||
const root = el('div', { className: 'iwb-album' }, [bar, tools, hint, grid, empty, pager, onepage])
|
||||
const root = el('div', { className: 'iwb-album' }, [bar, folderNote, folderMsg, tools, hint, grid, empty, pager, onepage, folderPath])
|
||||
host.appendChild(root)
|
||||
Object.assign(st, { root, bar, track, count, btnClear, btnAdd, btnDir, btnSettle, segs, grid, empty, pager, onepage, hint })
|
||||
Object.assign(st, { root, bar, track, count, btnClear, btnAdd, btnDir, btnPaste, btnSettle, segs, grid, empty, pager, onepage, hint, modeLabel, folderLabel, fTrack, btnRefresh, btnReload, folderNote, folderMsg, folderPath })
|
||||
|
||||
// 按钮绑定(用闭包里的当前 node/props:每次 sync 会更新 st.node/st.props)
|
||||
btnAdd.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
@@ -204,6 +255,12 @@
|
||||
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) })
|
||||
btnPaste.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
btnPaste.addEventListener('click', (e) => { e.stopPropagation(); pasteFromClipboard(ctx, st) })
|
||||
btnRefresh.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
btnRefresh.addEventListener('click', (e) => { e.stopPropagation(); refreshFolder(ctx, st) })
|
||||
btnReload.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
btnReload.addEventListener('click', (e) => { e.stopPropagation(); reloadFolder(ctx, st) })
|
||||
btnClear.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||||
btnClear.addEventListener('click', (e) => { e.stopPropagation(); clearAll(ctx, st) })
|
||||
|
||||
@@ -211,12 +268,104 @@
|
||||
host.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation() })
|
||||
host.addEventListener('drop', (e) => {
|
||||
e.preventDefault(); e.stopPropagation()
|
||||
if (isFolderMode(st.node)) return // 文件夹模式禁止其它来源,避免混源
|
||||
const files = Array.from((e.dataTransfer && e.dataTransfer.files) || [])
|
||||
if (files.length) importDropped(ctx, st, files)
|
||||
})
|
||||
return st
|
||||
}
|
||||
|
||||
// ── 文件夹模式(v1.2.0)──────────────────────────────────
|
||||
// 只做手动刷新:不做文件监听(用户已确认,避免性能开销)。
|
||||
// 宿主 listImages 的硬上限:只递归 1 层、最多 500 张。超限必须中止,
|
||||
// 否则一次性渲染/引用几百张会把界面拖死(用户明确要求“超了要阻止执行”)。
|
||||
const FOLDER_MAX = 500
|
||||
function isFolderMode (node) { return ((node && node.data) || {}).sourceMode === 'folder' }
|
||||
function folderOf (node) { const f = ((node && node.data) || {}).folder; return (f && typeof f.path === 'string') ? f.path : '' }
|
||||
function skipOf (node) { const v = ((node && node.data) || {}).folderSkip; return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [] }
|
||||
// 文件夹模式的提示统一走 folderMsg:原来的 st.hint 会被 sync 的“批量模式提示”逻辑隐藏,
|
||||
// 结果就是用户看不到任何原因(实测:选了目录仍显示 0 张且无提示)。
|
||||
function setFolderMsg (st, text) {
|
||||
if (!st || !st.folderMsg) return
|
||||
st.folderMsg.textContent = text || ''
|
||||
st.folderMsg.style.display = text ? '' : 'none'
|
||||
}
|
||||
|
||||
async function pickFolderForMonitor (ctx, st) {
|
||||
try {
|
||||
const picked = await ctx.images.pick({ multiple: false, directory: true })
|
||||
const dir = (picked && picked[0]) || ''
|
||||
if (!dir) return
|
||||
update(st.props, st.node, { folder: { path: dir } }, true)
|
||||
// 本地先合并一次:宿主 re-render 前 st.node 还是旧的,refreshFolder 会读不到目录
|
||||
try {
|
||||
const cur = st.node || {}
|
||||
st.node = Object.assign({}, cur, { data: Object.assign({}, cur.data || {}, { folder: { path: dir } }) })
|
||||
} catch (e) { /* ignore */ }
|
||||
st.sig = ''
|
||||
sync(ctx, st, st.node, st.props)
|
||||
await refreshFolder(ctx, st, dir)
|
||||
} catch (e) { /* 用户取消 */ }
|
||||
}
|
||||
|
||||
// 刷新 = 增量 diff:按文件名排序、尊重忽略名单、保留勾选与当前页
|
||||
async function refreshFolder (ctx, st, dirOverride) {
|
||||
if (st.busy) return
|
||||
const node = st.node
|
||||
const dir = dirOverride || folderOf(node)
|
||||
if (!dir) { setFolderMsg(st, '尚未选择文件夹'); return }
|
||||
st.busy = '刷新…'; st.sig = ''; sync(ctx, st, node, st.props)
|
||||
let files = []
|
||||
try { files = await ctx.images.listImages(dir) } catch (e) { files = [] }
|
||||
st.busy = ''
|
||||
if (files && files.length >= FOLDER_MAX) {
|
||||
st.sig = ''; sync(ctx, st, node, st.props)
|
||||
setFolderMsg(st, '该文件夹图片达到 ' + FOLDER_MAX + ' 张上限,已中止刷新(未改动现有条目)。请拆分目录或只放需要的图。')
|
||||
return
|
||||
}
|
||||
if (!files || !files.length) {
|
||||
st.sig = ''; sync(ctx, st, node, st.props)
|
||||
setFolderMsg(st, '该目录第一层没有图片,或目录不可用(未改动现有条目)')
|
||||
return
|
||||
}
|
||||
setFolderMsg(st, '')
|
||||
const skip = new Set(skipOf(node).map((x) => normPath(x)))
|
||||
const want = files.filter((f) => !skip.has(normPath(f))).sort((a, b) => normPath(a).localeCompare(normPath(b)))
|
||||
const items = itemsOf(node).slice()
|
||||
const byPath = new Map()
|
||||
for (const it of items) { const p0 = fileRefOf(it && it.src); if (p0) byPath.set(normPath(p0), it) }
|
||||
const next = []
|
||||
for (const f of want) {
|
||||
const hit = byPath.get(normPath(f))
|
||||
if (hit) { next.push(hit); continue }
|
||||
const ref = await ctx.images.reference(f)
|
||||
if (ref && ref.ok) next.push({ src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
|
||||
}
|
||||
const capNow = (st.cap && st.cap.capacity) || 20
|
||||
const pageNow = Math.max(0, Number(((node && node.data) || {}).page) || 0)
|
||||
const pagesNow = Math.max(1, Math.ceil(next.length / capNow))
|
||||
update(st.props, node, { items: next, page: Math.min(pageNow, pagesNow - 1) }, true)
|
||||
st.checkedMissing = false
|
||||
st.sig = ''
|
||||
sync(ctx, st, node, st.props)
|
||||
}
|
||||
|
||||
// 全部重载 = 清空忽略名单 + 整本重读(会重置勾选与页码)
|
||||
async function reloadFolder (ctx, st) {
|
||||
const node = st.node
|
||||
const dir = folderOf(node)
|
||||
if (!dir) return
|
||||
if (typeof confirm === 'function' && !confirm('将清空忽略名单并重新读取文件夹,确定?')) return
|
||||
const files = await ctx.images.listImages(dir).catch(() => [])
|
||||
if (files && files.length >= FOLDER_MAX) { setFolderMsg(st, '该文件夹图片达到 ' + FOLDER_MAX + ' 张上限,已中止重载(未改动现有条目)'); return }
|
||||
if (!files || !files.length) { setFolderMsg(st, '文件夹不可用,未改动现有条目'); return }
|
||||
update(st.props, node, { folderSkip: [], items: [], page: 0 }, true)
|
||||
st.checkedMissing = false
|
||||
st.sig = ''
|
||||
sync(ctx, st, node, st.props)
|
||||
await refreshFolder(ctx, st)
|
||||
}
|
||||
|
||||
// ── 同步(宿主每次重渲染都会调用;必须可增量)──────────────────
|
||||
function sync (ctx, st, node, props) {
|
||||
st.node = node; st.props = props
|
||||
@@ -248,10 +397,30 @@
|
||||
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'
|
||||
// v1.2.0:按模式切换可见控件(不适用的一律隐藏,不置灰)
|
||||
const folderMode = isFolderMode(node)
|
||||
const fileCount = items.filter((it) => fileRefOf(it && it.src)).length
|
||||
st.btnSettle.textContent = fileCount ? ('固化 ' + fileCount) : '固化'
|
||||
st.btnSettle.style.display = (!folderMode && fileCount) ? '' : 'none'
|
||||
st.btnAdd.style.display = folderMode ? 'none' : ''
|
||||
// v1.2.3:粘贴按钮只在混合模式显示;没有剪贴板能力(网页端/无 Rust 桥)时也隐藏
|
||||
const canPaste = !folderMode && !!(window.IWBNativeClipboard && typeof window.IWBNativeClipboard.readImage === 'function')
|
||||
st.btnPaste.style.display = canPaste ? '' : 'none'
|
||||
st.btnRefresh.style.display = folderMode ? '' : 'none'
|
||||
st.btnReload.style.display = folderMode ? '' : 'none'
|
||||
st.btnDir.textContent = folderMode ? '更换文件夹' : '文件夹'
|
||||
st.folderNote.style.display = folderMode ? '' : 'none'
|
||||
st.folderLabel.classList.toggle('on', folderMode)
|
||||
if (st.fTrack) st.fTrack.className = 'iwb-album-track' + (folderMode ? ' on' : '')
|
||||
st.folderPath.style.display = folderMode ? '' : 'none'
|
||||
if (!folderMode && !st.folderMsg.textContent) st.folderMsg.style.display = 'none'
|
||||
if (folderMode) {
|
||||
const dir = folderOf(node)
|
||||
const skipped = skipOf(node).length
|
||||
st.folderPath.textContent = '文件夹:' + (dir || '(未选择)') + (skipped ? (' · 已忽略 ' + skipped + ' 张') : '')
|
||||
}
|
||||
// 「文件夹」只在能做路径引用的宿主里有意义(桌面端)。旧写法 `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'
|
||||
@@ -312,7 +481,7 @@
|
||||
} 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) {
|
||||
if (to - from < cap.capacity && !isFolderMode(st.node)) {
|
||||
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)
|
||||
@@ -354,13 +523,38 @@
|
||||
title: (it && it.name ? it.name : ('图 ' + (index + 1))) + (missing ? '(文件已不在原位置:点一下重新定位)' : ''),
|
||||
})
|
||||
const img = el('img', { alt: '', draggable: 'false' })
|
||||
// 缩略图缓存可能来自旧路径/旧版本,dataURL 本身坏了也会命中;onerror 时绕过缓存重读原图一次。
|
||||
let thumbRetried = false
|
||||
const applyThumb = (url) => {
|
||||
if (!url) return
|
||||
img.onerror = () => {
|
||||
if (thumbRetried) return
|
||||
thumbRetried = true
|
||||
st.thumbs.delete(key)
|
||||
if (st.forceThumbs) st.forceThumbs.add(key)
|
||||
dropThumbFile(ctx, key)
|
||||
loadThumb(ctx, st, it, key, true).then((next) => { if (next) applyThumb(next) })
|
||||
}
|
||||
img.src = url
|
||||
}
|
||||
const cached = st.thumbs.get(key)
|
||||
if (cached) img.src = cached
|
||||
// ⚠ 命中内存缓存时 img **还没** appendChild(本函数末尾才挂),所以这里不能判存活:
|
||||
// 1.1.5 把「存活判断」提进了 applyThumb,于是同步分支永远 isConnected === false ⇒ 直接 return,
|
||||
// 每次「导入 / 翻页 / 切密度 / 拖拽排序」引发宫格重建后,内存里已有的缩略图全都赋不上 src,
|
||||
// 格子一片空白(切走再切回来才正常 —— 那时内存缓存是空的,走异步分支)。
|
||||
// 存活判断只对异步回来的那一支有意义:那时格子可能已被下一次重建丢掉。
|
||||
if (cached) applyThumb(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 })
|
||||
// 异步分支才判存活(等图期间宫格可能已被下一次重建丢掉,旧 img 不该再赋值)
|
||||
else loadThumb(ctx, st, it, key).then((u) => { if (u && img.isConnected) applyThumb(u) })
|
||||
btn.appendChild(img)
|
||||
btn.appendChild(el('span', { className: 'iwb-album-idx' }, String(index + 1)))
|
||||
// v1.2.0:来源徽标(左下角)。让“是否已固化”可见,避免用户靠按钮有无去猜。
|
||||
const srcState = missing ? '丢失'
|
||||
: (path ? '引用'
|
||||
: ((typeof src === 'string' && /^https?:/i.test(src)) ? '网络' : '已固化'))
|
||||
btn.appendChild(el('span', { className: 'iwb-album-src' + (missing ? ' is-missing' : '') }, srcState))
|
||||
// 批次角标(右上角那个「1」)已删除:顶栏「N 张 → M 个任务」已经说清楚,角标是重复信息,
|
||||
// 还会和删除按钮抢同一个角。位置让给了 ×。
|
||||
const del = el('span', { className: 'iwb-album-del', title: '移除(不删除磁盘上的原文件)' }, '×')
|
||||
@@ -368,13 +562,25 @@
|
||||
del.addEventListener('click', (e) => {
|
||||
e.stopPropagation()
|
||||
const items = itemsOf(st.node).slice()
|
||||
const removed = items[index]
|
||||
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)
|
||||
const patch = { items: items, page: Math.min(pageNow, pagesNow - 1) }
|
||||
// v1.2.0:文件夹模式下手动删除要记进忽略名单,否则下次刷新又回来
|
||||
const rmPath = fileRefOf(removed && removed.src)
|
||||
if (isFolderMode(st.node) && rmPath) {
|
||||
const skip = skipOf(st.node).slice()
|
||||
if (skip.indexOf(rmPath) < 0) skip.push(rmPath)
|
||||
patch.folderSkip = skip.slice(-500)
|
||||
}
|
||||
// v1.2.0:清掉该条目的缩略图文件(原来只删条目,ctx.files 里会越积越多)
|
||||
try { dropThumbFile(ctx, thumbKeyOf(removed)) } catch (e) { /* ignore */ }
|
||||
st.thumbs.delete(thumbKeyOf(removed))
|
||||
update(st.props, st.node, patch, true)
|
||||
})
|
||||
btn.appendChild(del)
|
||||
// 放大镜(右下角):点开插件自带的全屏查看器,可 ← → 切换整本相册(1.1.2)。
|
||||
@@ -442,37 +648,61 @@
|
||||
// ── 缩略图取用:内存 → 插件文件 → 现做 ───────────────────
|
||||
// 并发去重(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)
|
||||
async function loadThumb (ctx, st, it, key, force) {
|
||||
const forced = !!force || !!(st.forceThumbs && st.forceThumbs.has(key))
|
||||
if (!forced && 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 (flight && !forced) return flight
|
||||
const p = loadThumbInner(ctx, st, it, key, forced).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)
|
||||
async function loadThumbInner (ctx, st, it, key, force) {
|
||||
if (!force && st.thumbs.has(key)) return st.thumbs.get(key)
|
||||
// 读缓存要试两个后缀:同一个 key 可能存成 png(含透明)或 jpg(照片)。
|
||||
// 先 png 不会误命中 —— 透明图只可能存 png,照片只可能存 jpg。
|
||||
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 }
|
||||
if (!force && ctx.files) {
|
||||
for (const name of thumbNames(key)) {
|
||||
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 = ''
|
||||
// v1.2.4(图片策略 v2):先让**宿主原生**出 320 小图 —— 不再把整幅原图读成 dataURL
|
||||
// 再在 webview 里 canvas 缩放(那是 WebKit 上每次 21MB 的整幅解码,一夹 100 张就是 GB 级)。
|
||||
const src = it && it.src
|
||||
try {
|
||||
if (fileRefOf(src)) dataUrl = await ctx.images.dataUrl(src)
|
||||
else if (typeof src === 'string') dataUrl = src
|
||||
if (ctx.images && typeof ctx.images.thumb === 'function') {
|
||||
const u = await ctx.images.thumb(src, { max: 320 })
|
||||
if (u && typeof u === 'string' && u.length < 512 * 1024) {
|
||||
st.thumbs.set(key, u)
|
||||
if (st.forceThumbs) st.forceThumbs.delete(key)
|
||||
// 不再往 plugin-data 另存一份:宿主已在 thumbs/ 里按 hash 落了 tier,重复存等于两份
|
||||
return u
|
||||
}
|
||||
}
|
||||
} catch (e) { /* 回退到本地缩放 */ }
|
||||
let dataUrl = ''
|
||||
try {
|
||||
if (typeof src === 'string' && src.indexOf('data:') === 0) 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)
|
||||
const made = await makeThumb(dataUrl)
|
||||
if (!made || !made.url) return ''
|
||||
st.thumbs.set(key, made.url)
|
||||
if (st.forceThumbs) st.forceThumbs.delete(key)
|
||||
// 内存里已经有一张就够本会话用了;写盘失败(配额满)不影响显示
|
||||
try { if (ctx.files) await ctx.files.put(name, thumb) } catch (e) { /* ignore */ }
|
||||
return thumb
|
||||
try {
|
||||
if (ctx.files) {
|
||||
const put = await ctx.files.put(thumbNameOf(key, made.ext), made.url)
|
||||
// 写成功才清旧:换格式留下的另一份、以及 1.1.5 的黑底 JPEG。
|
||||
// 写失败(如 64MB 配额满)就先都留着,别把唯一一份也删了。
|
||||
if (!put || put.ok !== false) dropThumbFile(ctx, key, made.ext)
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
return made.url
|
||||
}
|
||||
|
||||
// ── 看大图:插件自带全屏查看器(1.1.2 起支持 ← → 切换)──────────
|
||||
@@ -524,7 +754,11 @@
|
||||
const flight = pending.get(key)
|
||||
if (flight) return flight
|
||||
if (!ctx.images || typeof ctx.images.dataUrl !== 'function') return Promise.resolve('')
|
||||
const p = Promise.resolve(ctx.images.dataUrl(it && it.src)).then((u) => {
|
||||
// v1.2.4:大图也只取 2048 长边的预览(原生缩放),避免整幅解码 4K 原图
|
||||
const ask = (ctx.images && typeof ctx.images.preview === 'function')
|
||||
? Promise.resolve(ctx.images.preview(it && it.src, { max: 2048 })).then((r) => (r && r.dataUrl) || '')
|
||||
: Promise.resolve(ctx.images.dataUrl(it && it.src))
|
||||
const p = ask.then((u) => {
|
||||
pending.delete(key)
|
||||
if (!u) return ''
|
||||
cache.set(key, u)
|
||||
@@ -645,7 +879,8 @@
|
||||
function clearAll (ctx, st) {
|
||||
const items = itemsOf(st.node)
|
||||
if (!items.length) return
|
||||
st.thumbs.clear(); st.pending.clear(); st.missing.clear()
|
||||
for (const it of items) { try { dropThumbFile(ctx, thumbKeyOf(it)) } catch (e) { /* ignore */ } }
|
||||
st.thumbs.clear(); st.pending.clear(); st.missing.clear(); if (st.forceThumbs) st.forceThumbs.clear()
|
||||
st.checkedMissing = false // 清空后再导入要重新做一次失联检测
|
||||
closeViewer(st) // 正在看大图时清空 ⇒ 先把浮层收掉(别留个没有数据的空查看器)
|
||||
update(st.props, st.node, { items: [], page: 0, pageRange: null }, true)
|
||||
@@ -670,13 +905,20 @@
|
||||
for (const dir of picked) {
|
||||
try { const got = await ctx.images.listImages(dir); for (const f of (got || [])) paths.push(f) } catch (e) { /* 单个目录失败不阻断 */ }
|
||||
}
|
||||
if (paths.length >= FOLDER_MAX) {
|
||||
st.busy = ''
|
||||
st.hint.textContent = '该文件夹图片达到 ' + FOLDER_MAX + ' 张上限,已中止导入(未添加任何图)'
|
||||
st.hint.style.display = ''
|
||||
st.sig = ''; sync(ctx, st, st.node, st.props)
|
||||
return
|
||||
}
|
||||
} 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'
|
||||
@@ -696,7 +938,33 @@
|
||||
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 })
|
||||
const nextSrc = { __file: ref.item.path }
|
||||
// 重选同一文件夹:按归一化路径就地更新,不追加重复项(旧实现会让坏格一直留在前面,
|
||||
// 新加的重复项排到后面/下一页,看起来就是「重新选择也不出缩略图」)。
|
||||
let at = -1
|
||||
for (let k = 0; k < items.length; k++) {
|
||||
const p0 = fileRefOf(items[k] && items[k].src)
|
||||
if (p0 && normPath(p0) === normPath(ref.item.path)) { at = k; break }
|
||||
}
|
||||
if (at >= 0) {
|
||||
const old = items[at]
|
||||
const oldKey = thumbKeyOf(old)
|
||||
items[at] = Object.assign({}, old, { src: nextSrc, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
|
||||
st.missing.delete(fileRefOf(old && old.src))
|
||||
st.missing.delete(ref.item.path)
|
||||
st.thumbs.delete(oldKey)
|
||||
if (st.forceThumbs) st.forceThumbs.add(oldKey)
|
||||
dropThumbFile(ctx, oldKey)
|
||||
// 路径大小写/分隔符不同 ⇒ 新 key 也要清掉旧缓存并强制重读
|
||||
const newKey = thumbKeyOf(items[at])
|
||||
if (newKey !== oldKey) {
|
||||
st.thumbs.delete(newKey)
|
||||
if (st.forceThumbs) st.forceThumbs.add(newKey)
|
||||
dropThumbFile(ctx, newKey)
|
||||
}
|
||||
} else {
|
||||
items.push({ src: nextSrc, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
|
||||
}
|
||||
}
|
||||
st.busy = ''
|
||||
st.checkedMissing = false // 新图要重新做一次失联检测(否则清空后再导入,检测永远不再跑)
|
||||
@@ -716,8 +984,10 @@
|
||||
}
|
||||
st.busy = ''
|
||||
st.btnAdd.textContent = '+ 添加图片'
|
||||
st.sig = ''
|
||||
sync(ctx, st, st.node, st.props)
|
||||
// 预生成只是「提前把缩略图做进缓存」:格子自己的 loadThumb 早在上面那次 sync 里就发起了,
|
||||
// pending 表已把同一张合成一个 Promise。这里**不再**置空 sig 强制整块重建 ——
|
||||
// 1.1.5 每次导入末尾都会多建一遍全部格子(500 张导入 = 白建 500 个 DOM),是肉眼可见的卡顿;
|
||||
// 而它当年还掩盖了缩略图赋值的问题(重建恰好把所有格子都变成「命中缓存 → 空白」)。
|
||||
}
|
||||
|
||||
async function importDropped (ctx, st, files) {
|
||||
@@ -737,12 +1007,12 @@
|
||||
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)
|
||||
const made = await makeThumb(dataUrl)
|
||||
// 键必须和 cellOf / loadThumb 完全一致(thumbKeyOf),否则写进缓存也命中不到
|
||||
if (thumb) {
|
||||
if (made && made.url) {
|
||||
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.thumbs.set(key, made.url)
|
||||
try { if (ctx.files) await ctx.files.put(thumbNameOf(key, made.ext), made.url) } catch (e) { /* ignore */ }
|
||||
}
|
||||
}
|
||||
st.busy = ''
|
||||
@@ -752,14 +1022,80 @@
|
||||
sync(ctx, st, st.node, st.props)
|
||||
}
|
||||
|
||||
// ── 粘贴(v1.2.3)──────────────────────────────────────
|
||||
// 走宿主已有的 IWBNativeClipboard(桌面端 = Rust arboard,能读截图 / 网页复制 / 访达复制文件)。
|
||||
// 插件与宿主同窗口,直接取全局即可,不需要新增宿主 API;网页端回落 navigator.clipboard.read()。
|
||||
function fileToDataUrl (file) {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
const r = new FileReader()
|
||||
r.onload = () => resolve(String(r.result || ''))
|
||||
r.onerror = () => resolve('')
|
||||
r.readAsDataURL(file)
|
||||
} catch (e) { resolve('') }
|
||||
})
|
||||
}
|
||||
async function readClipboardFile () {
|
||||
const C = (typeof window !== 'undefined') ? window.IWBNativeClipboard : null
|
||||
if (C && typeof C.readImage === 'function') {
|
||||
try { const f = await C.readImage(); if (f) return { file: f, reason: '' } } catch (e) { /* 落到下面的文案 */ }
|
||||
const why = (typeof C.lastReason === 'function') ? String(C.lastReason() || '') : ''
|
||||
return { file: null, reason: why }
|
||||
}
|
||||
// 网页端兜底:navigator.clipboard.read()(需要权限,失败就按“没有图片”处理)
|
||||
try {
|
||||
const nav = window.navigator
|
||||
if (nav && nav.clipboard && typeof nav.clipboard.read === 'function') {
|
||||
const items = await nav.clipboard.read()
|
||||
for (const it of (items || [])) {
|
||||
const type = (it.types || []).find((t) => /^image\//i.test(t))
|
||||
if (!type) continue
|
||||
const blob = await it.getType(type)
|
||||
return { file: new File([blob], 'clipboard-' + Date.now() + '.png', { type: blob.type || type }), reason: '' }
|
||||
}
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
return { file: null, reason: '' }
|
||||
}
|
||||
async function pasteFromClipboard (ctx, st) {
|
||||
if (st.busy) return
|
||||
st.busy = '粘贴…'; st.sig = ''; sync(ctx, st, st.node, st.props)
|
||||
const got = await readClipboardFile()
|
||||
st.busy = ''
|
||||
if (!got.file) {
|
||||
setFolderMsg(st, '剪贴板里没有图片' + (got.reason ? '(' + got.reason + ')' : '(截图或 ⌘C 复制图片后再试)'))
|
||||
st.sig = ''; sync(ctx, st, st.node, st.props)
|
||||
return
|
||||
}
|
||||
const dataUrl = await fileToDataUrl(got.file)
|
||||
if (!dataUrl) { setFolderMsg(st, '读取剪贴板图片失败'); st.sig = ''; sync(ctx, st, st.node, st.props); return }
|
||||
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 || !(res.ref || res.data)) { setFolderMsg(st, '粘贴失败:图片没能写入画布存储'); st.sig = ''; sync(ctx, st, st.node, st.props); return }
|
||||
const items = itemsOf(st.node).slice()
|
||||
items.push({ src: res.ref || res.data, name: got.file.name || ('粘贴 ' + (items.length + 1)), size: got.file.size || 0, on: true })
|
||||
// 缩略图:与「添加图片」同一条链路
|
||||
const made = await makeThumb(dataUrl)
|
||||
if (made && made.url) {
|
||||
const key = thumbKeyOf(items[items.length - 1])
|
||||
st.thumbs.set(key, made.url)
|
||||
try { if (ctx.files) await ctx.files.put(thumbNameOf(key, made.ext), made.url) } catch (e) { /* ignore */ }
|
||||
}
|
||||
setFolderMsg(st, '')
|
||||
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
|
||||
let skipped = 0
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const it = items[i]
|
||||
const path = fileRefOf(it && it.src)
|
||||
if (!path) continue
|
||||
if (!path) { skipped++; 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) })
|
||||
@@ -770,6 +1106,7 @@
|
||||
update(st.props, st.node, { items }, true)
|
||||
st.sig = ''
|
||||
sync(ctx, st, st.node, st.props)
|
||||
if (skipped) { st.hint.textContent = '已跳过 ' + skipped + ' 张(已固化或非本地引用)'; st.hint.style.display = '' }
|
||||
}
|
||||
|
||||
async function checkMissing (ctx, st, items) {
|
||||
@@ -812,7 +1149,7 @@
|
||||
global.IWBPluginHost.register({
|
||||
id: 'album',
|
||||
name: '相册',
|
||||
version: '1.1.2',
|
||||
version: '1.2.5',
|
||||
apiVersion: 1,
|
||||
capabilities: ['nodeTypes', 'images', 'files'],
|
||||
settings: {
|
||||
|
||||
+14
-1
@@ -29,8 +29,21 @@
|
||||
竖图撑到 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 { 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; transition: border-color var(--iwb-motion-hover, .15s) var(--iwb-ease-hover, ease-out); }
|
||||
/* 1.1.4(用户:1.06 太不明显):放大到 1.08 + 更深的投影 + 2px 品牌描边。
|
||||
网格内**不做位移**(translateY 会让相邻格的 hover 判定抖动);描边用 outline 而不是加粗 border,
|
||||
避免图片内容被 1px 的 border 变化挤动。z-index 走宿主层级 token(插件禁止裸值),
|
||||
且被 .iwb-album-grid 的 overflow:hidden 限制在节点内。 */
|
||||
.iwb-album-cell:hover { outline: 2px solid var(--iwb-hover-border, var(--iwb-brand)); outline-offset: -2px; border-color: var(--iwb-hover-border, var(--iwb-brand)); z-index: var(--iwb-z-ctx, 90); }
|
||||
@media (prefers-reduced-motion: reduce) { .iwb-album-cell { transition: none; } .iwb-album-cell:hover { transform: none; } }
|
||||
.iwb-album-cell img { width: 100%; height: 100%; object-fit: cover; display: block; -webkit-user-drag: none; }
|
||||
/* v1.2.0:来源徽标 + 文件夹模式说明/路径 */
|
||||
.iwb-album-src { position: absolute; left: var(--iwb-space-4); bottom: var(--iwb-space-4); padding: 0 var(--iwb-space-4); border-radius: var(--iwb-radius-chip); font-size: var(--iwb-font-xs); line-height: 1.2; background: color-mix(in srgb, var(--iwb-text) 62%, transparent); color: var(--iwb-bg); pointer-events: none; }
|
||||
.iwb-album-src.is-missing { background: color-mix(in srgb, var(--iwb-danger, #d33) 78%, transparent); color: var(--iwb-bg); }
|
||||
.iwb-album-foldernote { font-size: var(--iwb-font-2xs); color: var(--iwb-text2); padding: 0 var(--iwb-space-2); }
|
||||
.iwb-album-foldermsg { font-size: var(--iwb-font-2xs); color: var(--iwb-warning, #b45309); padding: 0 var(--iwb-space-2); }
|
||||
.iwb-album-folderpath { font-size: var(--iwb-font-2xs); color: var(--iwb-text2); padding: var(--iwb-space-2); word-break: break-all; opacity: .9; }
|
||||
|
||||
.iwb-album-cell.off img { opacity: .38; }
|
||||
/* 选中线 2px → 1px(用户:太粗)。1px 在浅底上仍分得清「选中」与「描边」。 */
|
||||
.iwb-album-cell.sel { outline: 1px solid var(--iwb-brand); outline-offset: -1px; }
|
||||
|
||||
@@ -184,7 +184,7 @@ ok('跨页拖拽用「每页容量」换算,不用「本页格子数」',
|
||||
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(网页版点了没反应)',
|
||||
ok('「文件夹」按钮不再 canReference() || true(不支持路径引用时点了没反应)',
|
||||
!/\|\| true \? '' : 'none'/.test(src))
|
||||
ok('addPaths 里没有 keep 死变量', !/const keep = \(st\.node\.data/.test(src))
|
||||
ok('缩略图请求并发去重(st.pending,否则导入 30 张要解 60 次原图)',
|
||||
|
||||
@@ -21,8 +21,7 @@ const css = readFileSync(path.join(ROOT, 'styles.css'), 'utf8')
|
||||
|
||||
let chromium = null
|
||||
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT,
|
||||
'/Users/qiqi/open/github/image-workbench-desktop',
|
||||
'/Users/qiqi/open/github/image-workbench-web', ROOT]) {
|
||||
'/Users/qiqi/open/github/image-workbench-desktop', ROOT]) {
|
||||
if (!base) continue
|
||||
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch (e) { /* 试下一个 */ }
|
||||
}
|
||||
|
||||
@@ -95,15 +95,9 @@ mock 宿主 + 真实 Chromium,覆盖:manifest / 面板注册与挂载 / 列
|
||||
|
||||
需要 Playwright(可从桌面仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定)+ 系统 `unzip`、`python3`,不进 CI。
|
||||
|
||||
**发布后必须再跑一次真机**(mock 抓不到宿主 CSS / 真实 CSP / 真实面板挂载):
|
||||
|
||||
```bash
|
||||
node batch-export/tools/e2e-site.mjs
|
||||
```
|
||||
|
||||
覆盖:市场安装加载 + SRI + 资源中心 tab 出现 + 面板挂载 + 列表 2 行 +
|
||||
**勾选框与文字同行(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)** +
|
||||
队列跑通 + 下载 ZIP + python3 校验 4 条目 / CRC / PNG·JPEG magic / UTF-8 名。
|
||||
harness 用真实 Chromium 注入宿主 CSS 变量与 CSP 约束,覆盖面板挂载、勾选框与文字同行
|
||||
(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)、队列跑通、
|
||||
下载 ZIP + python3 校验条目 / CRC / PNG·JPEG magic / UTF-8 名。发布后在客户端市场里确认版本与加载状态即可。
|
||||
|
||||
## 发布
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/batch-export",
|
||||
"private": true,
|
||||
"version": "1.2.2",
|
||||
"version": "1.2.3",
|
||||
"description": "批量出图:资源中心面板里勾选 ref 节点,串行跑(可选本机抠图)→ 白底/透明合成 → 双版本编码 → 打包 ZIP 下载;行内可单张下载 JPG/PNG",
|
||||
"ibwPlugin": {
|
||||
"id": "batch-export",
|
||||
|
||||
@@ -510,7 +510,7 @@
|
||||
global.IWBPluginHost.register({
|
||||
id: 'batch-export',
|
||||
name: '批量出图',
|
||||
version: '1.2.2',
|
||||
version: '1.2.3',
|
||||
apiVersion: 1,
|
||||
capabilities: ['panels', 'canvas'],
|
||||
settings: {
|
||||
@@ -577,7 +577,7 @@
|
||||
|
||||
async function makeSrcThumb(nodeId) {
|
||||
if (!ctx.canvas || typeof ctx.canvas.getNodeImage !== 'function') return null
|
||||
var image = await ctx.canvas.getNodeImage(nodeId)
|
||||
var image = await ctx.canvas.getNodeImage(nodeId, { max: 64 }) // v: 缩略预览只要 64px,别整幅解码
|
||||
var src = image && (image.dataUrl || image.url)
|
||||
if (!src) return null
|
||||
var img = await loadImageEl(src)
|
||||
|
||||
@@ -1,282 +0,0 @@
|
||||
// 真实站点端到端(开发用,不进 CI)—— batch-export「批量出图」。
|
||||
//
|
||||
// 为什么需要它:harness.mjs 用的是 mock 宿主,面板样式与真实宿主 CSS 变量、真实 CSP、真实
|
||||
// 画布桥都不会被执行到。发布后跑一遍这个脚本,能抓到 mock 里永远绿的问题 ——
|
||||
// 例如 `.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行、把标签挤到面板最右(1.0.0 首次发布即中招)。
|
||||
//
|
||||
// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)+ 真实资源中心面板挂载。
|
||||
//
|
||||
// 运行(需要 Playwright + python3):
|
||||
// node batch-export/tools/e2e-site.mjs # 默认测试站
|
||||
// IWB_BASE_URL=https://iwb.maqiart.eu.org node batch-export/tools/e2e-site.mjs # 正式站
|
||||
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
|
||||
import { createRequire } from 'node:module'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { readFileSync, existsSync, statSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/batch-export/tools
|
||||
const REPO = path.resolve(HERE, '../..') // <repo>
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
|
||||
let chromium = null
|
||||
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
|
||||
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
|
||||
}
|
||||
if (!chromium) {
|
||||
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
|
||||
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node batch-export/tools/e2e-site.mjs')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
|
||||
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'batch-export/package.json'), 'utf8')).version
|
||||
const ZIP_OUT = path.join(os.tmpdir(), 'iwb-batch-e2e.zip')
|
||||
|
||||
let failed = 0
|
||||
const check = (name, ok, detail) => {
|
||||
if (!ok) failed++
|
||||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||||
}
|
||||
|
||||
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
|
||||
const browser = await chromium.launch()
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
|
||||
const consoleErrors = []
|
||||
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
|
||||
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
|
||||
|
||||
// 造两张 200×120 的参考图(非正方形,等比缩放/居中被真正练到)
|
||||
await page.goto('about:blank')
|
||||
const PNG = await page.evaluate(() => {
|
||||
const c = document.createElement('canvas')
|
||||
c.width = 200; c.height = 120
|
||||
const x = c.getContext('2d')
|
||||
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 200, 120)
|
||||
return c.toDataURL('image/png')
|
||||
})
|
||||
|
||||
// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled
|
||||
await page.addInitScript((d) => {
|
||||
localStorage.clear()
|
||||
localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], canvas: {} }))
|
||||
const ws = {
|
||||
workspaces: [{
|
||||
id: 'w1', name: 'W',
|
||||
nodes: [
|
||||
{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: '菜单A.png', localName: null } },
|
||||
{ id: 'r2', type: 'ref', x: 460, y: 140, data: { url: '', data: d.png, name: '菜单B.png', localName: null } },
|
||||
],
|
||||
edges: [], groups: [],
|
||||
}],
|
||||
activeId: 'w1', rev: 1,
|
||||
}
|
||||
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
|
||||
localStorage.setItem('iwb_ws_active', ws.activeId)
|
||||
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
|
||||
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
|
||||
localStorage.setItem('iwb_plugins', JSON.stringify({ 'batch-export': { enabled: true, settings: {}, data: {} } }))
|
||||
}, { png: PNG })
|
||||
|
||||
// ---------- 1) 站点可达 ----------
|
||||
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
|
||||
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
|
||||
|
||||
// ---------- 2) 真实 KV 加载 + 启用 ----------
|
||||
await page.waitForFunction(() => window.IWBPluginHost && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
|
||||
await page.waitForFunction(() => window.IWBPluginHost.list().some((x) => x.id === 'batch-export'), null, { timeout: 20000 })
|
||||
const info = await page.evaluate(() => {
|
||||
const p = window.IWBPluginHost.list().find((x) => x.id === 'batch-export')
|
||||
return p ? { version: p.version, enabled: p.enabled, active: p.active, capabilities: p.capabilities, error: p.error } : null
|
||||
})
|
||||
check('从真实 KV 加载并启用(active)', Boolean(info && info.active && info.enabled && !info.error), JSON.stringify(info))
|
||||
check('线上版本 = batch-export/package.json(' + WANT_VERSION + ')', Boolean(info && info.version === WANT_VERSION), info && info.version)
|
||||
|
||||
// ---------- 3) 面板 tab ----------
|
||||
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
|
||||
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
|
||||
check('画布打开、2 个 ref 节点', (await page.locator('.iwb-node[data-node-id^="r"]').count()) === 2)
|
||||
await page.locator('button[title^="资源中心"]').first().click()
|
||||
const tab = page.locator('.iwb-res-tab', { hasText: '批量出图' })
|
||||
check('资源中心出现「批量出图」tab', (await tab.count()) >= 1)
|
||||
await tab.first().click()
|
||||
await page.waitForTimeout(1200)
|
||||
const mounted = await page.locator('.iwb-full-panel-plugin').count()
|
||||
check('面板已挂载(真实宿主容器)', mounted >= 1)
|
||||
// 宿主 .iwb-full-main 是 flex 行容器,只给图库/节点组容器 width:100%;插件容器不撑满就会按内容收缩
|
||||
const widthInfo = await page.evaluate(() => {
|
||||
const main = document.querySelector('.iwb-full-main')
|
||||
const box = document.querySelector('.iwb-bx')
|
||||
return {
|
||||
main: main ? Math.round(main.clientWidth) : 0,
|
||||
box: box ? Math.round(box.clientWidth) : 0,
|
||||
}
|
||||
})
|
||||
check('面板撑满内容区宽度(不按内容收缩)',
|
||||
widthInfo.main > 0 && widthInfo.box >= widthInfo.main - 2, JSON.stringify(widthInfo))
|
||||
const rows = await page.locator('.iwb-bx-item').count()
|
||||
check('面板列出 2 个 ref 节点', rows === 2, 'rows=' + rows)
|
||||
|
||||
// 1.0.0 首发的真实 bug:checkbox 被 .iwb-bx-f input{width:100%} 撑满整行,标签被挤到最右
|
||||
const chk = await page.evaluate(() => {
|
||||
const lab = document.querySelector('.iwb-bx-rowchk')
|
||||
if (!lab) return null
|
||||
const input = lab.querySelector('input[type=checkbox]')
|
||||
const span = lab.querySelector('span')
|
||||
if (!input || !span) return null
|
||||
const a = input.getBoundingClientRect()
|
||||
const b = span.getBoundingClientRect()
|
||||
return { gap: Math.round(b.left - a.right), sameLine: Math.abs(a.top - b.top) < 12, inputW: Math.round(a.width) }
|
||||
})
|
||||
check('「走本地鲜艺抠图」勾选框与文字同行且紧邻', Boolean(chk && chk.sameLine && chk.gap >= 0 && chk.gap <= 12 && chk.inputW <= 24), JSON.stringify(chk))
|
||||
const cutLabel = await page.evaluate(() => {
|
||||
const s = document.querySelector('.iwb-bx-rowchk span')
|
||||
return s ? s.textContent.trim() : ''
|
||||
})
|
||||
check('抠图开关文案写明「本地鲜艺抠图」+ 端口', /鲜艺/.test(cutLabel) && /30092/.test(cutLabel), cutLabel)
|
||||
|
||||
// 1.1.0:配置区与列表之间要有明显的隔断(灰底小节头),操作按钮归到列表区
|
||||
const sec = await page.evaluate(() => {
|
||||
const s = document.querySelector('.iwb-bx-sec')
|
||||
if (!s) return null
|
||||
const bar = document.querySelector('.iwb-bx-bar')
|
||||
const a = s.getBoundingClientRect()
|
||||
const b = bar.getBoundingClientRect()
|
||||
return {
|
||||
text: (s.textContent || '').trim().slice(0, 24),
|
||||
btns: Array.from(s.querySelectorAll('button')).map((x) => x.textContent.trim()),
|
||||
bg: getComputedStyle(s).backgroundColor,
|
||||
belowConfig: a.top >= b.bottom - 1,
|
||||
}
|
||||
})
|
||||
check('隔断:「待处理节点」小节头在配置区正下方,带灰底 + 全选/清空/刷新',
|
||||
Boolean(sec && sec.belowConfig && sec.text.indexOf('待处理节点') === 0 &&
|
||||
JSON.stringify(sec.btns) === JSON.stringify(['全选', '清空', '刷新']) && sec.bg !== 'rgba(0, 0, 0, 0)'),
|
||||
JSON.stringify(sec))
|
||||
|
||||
// 1.1.0:缩略图必须**跑之前**就在(30px 显示 / 64px 源图)
|
||||
if (rows) {
|
||||
const preThumb = await page.evaluate(() => {
|
||||
const imgs = Array.from(document.querySelectorAll('.iwb-bx-item img.iwb-bx-thumb'))
|
||||
return { n: imgs.length, w: imgs[0] ? imgs[0].naturalWidth : 0, cssW: imgs[0] ? Math.round(imgs[0].getBoundingClientRect().width) : 0 }
|
||||
})
|
||||
check('列表行首常驻源图缩略图(2 张、64px 位图 / 30px 显示)',
|
||||
preThumb.n === 2 && preThumb.w === 64 && preThumb.cssW === 30, JSON.stringify(preThumb))
|
||||
|
||||
// 1.1.0 的 bug:「清空」后勾选框视觉上仍勾着(el() 用 setAttribute('checked','false'))
|
||||
await page.getByRole('button', { name: '清空', exact: true }).click()
|
||||
const cleared = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
|
||||
check('「清空」真的取消勾选', cleared.length === 2 && cleared.every((v) => v === false), JSON.stringify(cleared))
|
||||
await page.getByRole('button', { name: '全选', exact: true }).click()
|
||||
}
|
||||
|
||||
// ---------- 4) 跑队列 ----------
|
||||
if (!rows) {
|
||||
console.log('\n' + (await page.locator('.iwb-full-panel-plugin').first().innerText()))
|
||||
} else {
|
||||
await page.getByRole('button', { name: '全选', exact: true }).click()
|
||||
await page.getByRole('button', { name: '开始出图', exact: true }).click()
|
||||
await page.waitForFunction(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP')
|
||||
return b && !b.disabled
|
||||
}, null, { timeout: 120000 })
|
||||
const fails = await page.locator('.iwb-bx-item', { hasText: '失败' }).count()
|
||||
check('队列跑完、无失败项', fails === 0, 'fail=' + fails)
|
||||
|
||||
// 跑完必须「看得见图」:行内缩略图 + 一条说明产物在哪的提示条(1.0.1 之前只有一行文字,用户以为没产出)
|
||||
const thumbs = await page.locator('.iwb-bx-thumb').count()
|
||||
check('行内显示产物缩略图(2 张)', thumbs === 2, 'thumbs=' + thumbs)
|
||||
const thumbOk = thumbs ? await page.evaluate(() => {
|
||||
const im = document.querySelector('.iwb-bx-thumb')
|
||||
return { src: String(im.getAttribute('src') || '').slice(0, 5), w: im.naturalWidth, h: im.naturalHeight }
|
||||
}) : null
|
||||
check('缩略图是真解码出来的位图(800×800)', Boolean(thumbOk && thumbOk.src === 'blob:' && thumbOk.w === 800 && thumbOk.h === 800), JSON.stringify(thumbOk))
|
||||
|
||||
// ---------- 4.5) 行内单张下载(1.2.0):不依赖 ZIP,产物在内存里直接落盘 ----------
|
||||
const dlState = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-dl')).map((b) => ({
|
||||
text: b.textContent, disabled: b.disabled, title: b.title,
|
||||
})))
|
||||
check('行内下载:每行 JPG / PNG 各一个(2 行 = 4 个)',
|
||||
dlState.length === 4 && dlState[0].text === 'JPG' && dlState[1].text === 'PNG',
|
||||
JSON.stringify(dlState.map((b) => b.text)))
|
||||
check('行内下载:双版本跑完后全部可点', dlState.every((b) => b.disabled === false), JSON.stringify(dlState.map((b) => b.disabled)))
|
||||
const [jpgDl] = await Promise.all([
|
||||
page.waitForEvent('download', { timeout: 30000 }),
|
||||
page.locator('.iwb-bx-item').first().locator('.iwb-bx-dl').first().click(),
|
||||
])
|
||||
check('行内下载:点 JPG 直接下载单张(不必先导出 ZIP)',
|
||||
/\.jpg$/.test(jpgDl.suggestedFilename()), jpgDl.suggestedFilename())
|
||||
const doneText = await page.locator('.iwb-bx-done').first().innerText()
|
||||
check('完成提示条说明「已生成 → 点导出 ZIP」(不写入画布)', /已生成 4 个文件/.test(doneText) && /导出 ZIP/.test(doneText) && /不写入画布/.test(doneText), doneText)
|
||||
// 1.0.2 的坑:.iwb-bx-btn-hot 与 .iwb-bx-btn 同特异性且定义在前,背景被覆盖 → 高亮没生效
|
||||
const zipBg = await page.evaluate(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP')
|
||||
return b ? getComputedStyle(b).backgroundColor : ''
|
||||
})
|
||||
check('导出按钮转为高亮(rgb(29,158,117))', zipBg === 'rgb(29, 158, 117)', zipBg)
|
||||
|
||||
// ---------- 5) 导出 ZIP 并用 python3 校验(系统 unzip 对 UTF-8 名会乱码,见 README) ----------
|
||||
const [download] = await Promise.all([
|
||||
page.waitForEvent('download', { timeout: 60000 }),
|
||||
page.getByRole('button', { name: '导出 ZIP', exact: true }).click(),
|
||||
])
|
||||
await download.saveAs(ZIP_OUT)
|
||||
check('ZIP 已下载', existsSync(ZIP_OUT), existsSync(ZIP_OUT) ? statSync(ZIP_OUT).size + ' bytes' : '缺失')
|
||||
const doneAfter = await page.locator('.iwb-bx-done').first().innerText()
|
||||
check('导出后提示条显示已下载的文件名', /已下载 batch_.*\.zip/.test(doneAfter), doneAfter)
|
||||
try {
|
||||
const report = execFileSync('python3', ['-c', `
|
||||
import zipfile, sys
|
||||
z = zipfile.ZipFile(sys.argv[1])
|
||||
assert z.testzip() is None, 'CRC 损坏'
|
||||
for i in z.infolist():
|
||||
b = z.read(i.filename)
|
||||
ext = i.filename.rsplit('.', 1)[-1]
|
||||
ok = b[:4] == b'\\x89PNG' if ext == 'png' else b[:3] == b'\\xff\\xd8\\xff'
|
||||
print('%-28s %7dB %s %s' % (i.filename, i.file_size, '格式OK' if ok else '格式BAD', 'utf8' if i.flag_bits & 0x800 else 'nomb'))
|
||||
`, ZIP_OUT], { encoding: 'utf8' })
|
||||
console.log(report.trim())
|
||||
const lines = report.trim().split('\n').filter(Boolean)
|
||||
check('ZIP 4 个条目(2 张 × 双版本)', lines.length === 4, 'entries=' + lines.length)
|
||||
check('ZIP 条目格式与 UTF-8 文件名标记正确', lines.every((l) => /格式OK/.test(l) && /utf8/.test(l)))
|
||||
check('双版本命名 <原名>_800x800.png/.jpg', lines.some((l) => /菜单A_800x800\.png/.test(l)) && lines.some((l) => /菜单A_800x800\.jpg/.test(l)))
|
||||
} catch (e) {
|
||||
check('ZIP 结构校验(python3)', false, String((e && e.stdout) || (e && e.message)).slice(0, 200))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 6) 切到「图库 / 节点组」时不得串页(1.1.0) ----------
|
||||
// 真机现象:切到「图库」后批量面板还压在图片上方 —— 宿主两端都渲染成 div 且无 key,
|
||||
// React 复用同一 DOM 节点,只清理自己管理的子节点,插件 mount 进去的根节点留在原地。
|
||||
const clickedGallery = await page.evaluate(() => {
|
||||
const t = Array.from(document.querySelectorAll('.iwb-res-tab')).find((x) => /图库/.test(x.textContent))
|
||||
if (t) t.click()
|
||||
return Boolean(t)
|
||||
})
|
||||
await page.waitForTimeout(1200)
|
||||
const gallery = await page.evaluate(() => ({
|
||||
historyMounted: document.querySelectorAll('.iwb-history-embedded').length,
|
||||
panelsInDom: document.querySelectorAll('.iwb-bx').length,
|
||||
panelInsideHistory: Boolean(document.querySelector('.iwb-history-embedded .iwb-bx')),
|
||||
}))
|
||||
check('切到「图库」:批量面板自动摘除,图库内不再混入插件 DOM',
|
||||
clickedGallery && gallery.historyMounted >= 1 && gallery.panelsInDom === 0 && gallery.panelInsideHistory === false,
|
||||
JSON.stringify(gallery))
|
||||
|
||||
await page.locator('.iwb-res-tab', { hasText: '批量出图' }).first().click()
|
||||
await page.waitForTimeout(1500)
|
||||
const backRows = await page.locator('.iwb-bx-item').count()
|
||||
const backThumbs = await page.locator('.iwb-bx-item img.iwb-bx-thumb').count()
|
||||
check('切回「批量出图」:面板自动重新挂载、列表与缩略图仍在',
|
||||
backRows === 2 && backThumbs === 2, 'rows=' + backRows + ' thumbs=' + backThumbs)
|
||||
|
||||
// ---------- 7) 无 CSP / SRI 拦截、无页面错误 ----------
|
||||
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
|
||||
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
|
||||
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
|
||||
|
||||
await browser.close()
|
||||
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
|
||||
process.exit(failed ? 1 : 0)
|
||||
@@ -16,7 +16,7 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/batch-export/tools
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||||
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
|
||||
|
||||
let chromium = null
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# browser 插件避坑事项
|
||||
|
||||
> 维护:每次修改地址栏/收藏/原生菜单后,先读本文件并跑 `node tools/harness.mjs`。
|
||||
> 版本:1.8.6(2026-11-26)
|
||||
|
||||
## 1. 原生 webview 永远盖在 DOM 上
|
||||
|
||||
- 面板/节点的网页是 Tauri 原生子 webview,`z-index` 对它是无效的。
|
||||
- 任何浮层(收藏菜单、下拉、确认框)压在网页上都会被盖住:
|
||||
- 优先用**原生菜单**(宿主的 `browser_bookmarks_menu`,OS 层渲染);
|
||||
- 如果必须用 DOM 浮层,打开时调 `IWBCanvasWebview.setSuspended(true)`,关闭再恢复;或让宿主按浮层矩形 park。
|
||||
- 不要用「整块白底提示」盖网页来弥补,用户看到的是白屏。
|
||||
|
||||
## 2. 地址不能只信 `on_page_load`
|
||||
|
||||
- 花瓣、Figma、不少后台是 SPA:`history.pushState/replaceState` 换路由,**不触发** `on_page_load`。
|
||||
- 宿主 `src/canvas-webview.js` 每 1.2s 调 `canvas_webview_state` 取 `wv.url()`,变化时才 emit `iwb-cwv-state`。
|
||||
- 插件只消费 `st.pageUrl`;如果地址栏停在域名,先查宿主轮询,不要在插件里硬读 `location`(插件没有网页上下文)。
|
||||
- 收藏、重新加载、↗ 都依赖这个 URL;地址错会连带全错。
|
||||
|
||||
## 3. 收藏:目标组判断,不是全库 exists
|
||||
|
||||
书签结构是 `groups: [{ id, name, items }]`。旧坑:
|
||||
|
||||
```js
|
||||
// 错:全库存在就跳过写入
|
||||
for (const g of groups) for (const it of g.items) if (it.url === u) exists = true
|
||||
if (!exists) groups[target].items.push(...)
|
||||
```
|
||||
|
||||
后果:在「海报」收藏一个「常用」已有的 URL,不写「海报」,却提示“已经收藏过”。
|
||||
|
||||
正确:
|
||||
|
||||
- 先确定 `target` 索引;
|
||||
- 用 `targetHas`(只看目标组),不是全库 `exists`;
|
||||
- 跨组同名也允许:在目标组补一份;
|
||||
- 写入后**回读目标组**校验,不能回读全库;
|
||||
- 提示里带组名:`已收藏到「海报」`。
|
||||
|
||||
## 4. 收藏入口的目标组
|
||||
|
||||
- 点某个文件夹打开原生菜单时,先把 `bmMode = groupId` 记下来;
|
||||
- ★「收藏当前页」用 `bmMode`;
|
||||
- 原生菜单 add 事件必须带 `groupId`(Rust ID 形如 `bm-add:<b64 group>:<b64 url>`),插件 handler 原样传入;
|
||||
- 原生菜单失败要 fallback DOM 菜单,不能静默什么都不发生。
|
||||
|
||||
## 5. 地址栏失败态
|
||||
|
||||
- 用户不要红框。加载失败只写 `title`,边框保持默认灰;
|
||||
- `aria-invalid` 只用于“输入的网址非法”,并且也要把红边改成中性色;
|
||||
- `failed` 在 `started`/`finished` 都要能清,不能只等 `finished`(部分站点不派发)。
|
||||
|
||||
## 6. 发版
|
||||
|
||||
- `package.json` 的 version、入口 `version`、市场 `index.json` 三处必须一致;
|
||||
- 先 `node tools/harness.mjs` 全过,再 `node ../image-workbench-desktop/scripts/sync-plugins-from-repo.js`;
|
||||
- 本文件是源仓文档,不会打包进 zip(`sync` / `gen-market` 只取 manifest/main/style/assets)。
|
||||
|
||||
## 7. 最小回归清单
|
||||
|
||||
- [ ] 地址栏:SPA 点进详情页,1.2s 内 URL 跟着变
|
||||
- [ ] ★:在当前组收藏,组内出现;跨组同名也写入当前组
|
||||
- [ ] 原生菜单:macOS/Windows 能弹出、点击有回传
|
||||
- [ ] 加载失败:地址栏不变红、tooltip 有原因
|
||||
- [ ] 原生菜单打开时网页不消失(或合理 park)
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/browser",
|
||||
"private": true,
|
||||
"version": "1.7.1",
|
||||
"version": "1.8.6",
|
||||
"description": "应用内浏览器:独立窗口打开网页,或在画布节点里内嵌网页(跟随画布缩放,可单独调内容缩放)",
|
||||
"ibwPlugin": {
|
||||
"id": "browser",
|
||||
|
||||
+293
-56
@@ -53,6 +53,32 @@
|
||||
'.iwb-browser-gchip{cursor:pointer;border:1px solid transparent;border-radius:6px;background:transparent;color:var(--iwb-text2,#4d5668);font-size:11px;padding:3px 8px;white-space:nowrap;font-family:inherit}' +
|
||||
'.iwb-browser-gchip:hover{background:var(--iwb-layer2,#fff);border-color:var(--iwb-border,#d5d9e0)}' +
|
||||
'.iwb-browser-gchip-on{background:var(--iwb-layer2,#fff);border-color:var(--iwb-brand,#6b7280);color:var(--iwb-text,#1c2333);font-weight:600}' +
|
||||
// 收藏夹下拉(2026-11-26):地址栏后的星标按钮 → 浏览器式分组列表
|
||||
'.iwb-cwv-bmslot{display:inline-flex;align-items:center;gap:1px;flex:0 0 auto}' +
|
||||
'.iwb-br-bmbtn,.iwb-br-bmsave{flex:0 0 auto}' +
|
||||
// 收藏夹栏:横向文件夹条(Chrome 式),只有面板模式填充
|
||||
'.iwb-br-bmbar:empty{display:none}' +
|
||||
'.iwb-br-bmbar{display:flex;align-items:center;gap:var(--iwb-space-2,2px);padding:2px var(--iwb-space-6,6px);border-bottom:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer,#f0f1f4);flex:0 0 auto;overflow-x:auto;box-sizing:border-box;min-height:27px}' +
|
||||
'.iwb-br-bmfolder{display:inline-flex;align-items:center;gap:var(--iwb-space-4,4px);border:0;border-radius:var(--iwb-radius-chip,6px);background:transparent;color:var(--iwb-text2,#4d5668);font:inherit;font-size:var(--iwb-font-xs,11px);padding:3px var(--iwb-space-6,6px);white-space:nowrap;cursor:pointer;flex:0 0 auto}' +
|
||||
'.iwb-br-bmfolder:hover{background:var(--iwb-layer2,#fff);color:var(--iwb-text,#1c2333)}' +
|
||||
'.iwb-br-bmfname{max-width:110px;overflow:hidden;text-overflow:ellipsis}' +
|
||||
'.iwb-br-bmall{margin-left:auto;border:0;border-radius:var(--iwb-radius-chip,6px);background:transparent;color:var(--iwb-text2,#4d5668);font:inherit;font-size:var(--iwb-font-md,13px);padding:2px var(--iwb-space-6,6px);cursor:pointer;flex:0 0 auto}' +
|
||||
'.iwb-br-bmall:hover{background:var(--iwb-layer2,#fff);color:var(--iwb-text,#1c2333)}' +
|
||||
'.iwb-br-bmflash{font-size:var(--iwb-font-2xs,10px);color:var(--iwb-ok,#15803d);white-space:nowrap;margin-left:var(--iwb-space-6,6px);animation:iwb-bmflash-in .16s ease-out}' +
|
||||
'@keyframes iwb-bmflash-in{from{opacity:0;transform:translateY(-2px)}to{opacity:1;transform:none}}' +
|
||||
'.iwb-browser-bmmenu{position:absolute;top:38px;left:6px;right:6px;max-height:56vh;overflow:auto;padding:4px;background:var(--iwb-bg-menu,#fff);border:1px solid var(--iwb-border,#d5d9e0);border-radius:var(--iwb-radius-panel,12px);box-shadow:var(--iwb-elevation-2,0 10px 30px rgba(0,0,0,.18));z-index:var(--iwb-z-ctx-menu,91);box-sizing:border-box}' +
|
||||
'.iwb-br-bm-head{display:flex;align-items:center;gap:8px;padding:6px 8px;border-bottom:1px solid var(--iwb-border,#d5d9e0)}' +
|
||||
'.iwb-br-bm-title{font-weight:600;font-size:13px;color:var(--iwb-text,#1c2333);margin-right:auto}' +
|
||||
'.iwb-br-bm-add{display:inline-flex;align-items:center;gap:5px;border:1px solid var(--iwb-border,#d5d9e0);border-radius:var(--iwb-radius-chip,6px);background:var(--iwb-layer,#f5f6f8);color:var(--iwb-text,#1c2333);font:inherit;font-size:12px;padding:4px 8px;cursor:pointer}' +
|
||||
'.iwb-br-bm-add:hover{border-color:var(--iwb-brand,#6b7280);background:var(--iwb-layer2,#fff)}' +
|
||||
'.iwb-br-bm-folder{display:flex;align-items:center;gap:7px;padding:7px 8px 3px;font-size:12px;font-weight:600;color:var(--iwb-text2,#4d5668)}' +
|
||||
'.iwb-br-bm-fname{flex:1 1 auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}' +
|
||||
'.iwb-br-bm-count{font-size:11px;font-weight:400;opacity:.65}' +
|
||||
'.iwb-br-bm-item{display:flex;align-items:center;gap:var(--iwb-space-8,8px);width:100%;border:0;border-radius:var(--iwb-radius-chip,6px);background:transparent;color:var(--iwb-text,#1c2333);font:inherit;font-size:var(--iwb-font-sm,12px);text-align:left;padding:var(--iwb-space-4,4px) var(--iwb-space-8,8px) var(--iwb-space-4,4px) var(--iwb-space-24,24px);cursor:pointer}' +
|
||||
'.iwb-br-bm-item:hover{background:var(--iwb-hover,#e9e9e9)}' +
|
||||
'.iwb-br-bm-itext{flex:1 1 auto;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}' +
|
||||
'.iwb-br-bm-iurl{flex:0 1 auto;max-width:40%;font-size:11px;color:var(--iwb-text2,#4d5668);opacity:.65;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}' +
|
||||
'.iwb-br-bm-empty{padding:14px 8px;text-align:center;font-size:12px;color:var(--iwb-text2,#4d5668);opacity:.75}' +
|
||||
// ── 设置页:书签管理器(type:'custom')─────────────────────────────
|
||||
'.iwb-bm-set{display:flex;flex-direction:column;gap:10px;margin-top:10px;max-width:720px;font-size:13px;color:var(--iwb-text,#1c2333)}' +
|
||||
'.iwb-bm-groups{display:flex;align-items:center;gap:6px;flex-wrap:wrap}' +
|
||||
@@ -94,13 +120,13 @@
|
||||
'.iwb-cwv-btn:disabled{opacity:.26;cursor:default}' +
|
||||
'.iwb-cwv-url{flex:1 1 auto;min-width:40px;height:26px;padding:0 8px;border-radius:6px;border:1px solid var(--iwb-border,#d5d9e0);background:var(--iwb-layer2,#fff);color:var(--iwb-text,#1c2333);font-size:12px;font-family:inherit;box-sizing:border-box;outline:none}' +
|
||||
'.iwb-cwv-url:focus{border-color:var(--iwb-brand,#6b7280)}' +
|
||||
'.iwb-cwv-url[aria-invalid=true]{border-color:#e5484d}' +
|
||||
'.iwb-cwv-url[aria-invalid=true]{border-color:var(--iwb-border,#d5d9e0)}' +
|
||||
'.iwb-cwv-zoom{display:flex;align-items:center;flex:0 0 auto;height:26px;border:1px solid var(--iwb-border,#d5d9e0);border-radius:6px;background:var(--iwb-layer2,#fff);overflow:hidden}' +
|
||||
'.iwb-cwv-zoom .iwb-cwv-btn{width:22px;height:24px;border-radius:0}' +
|
||||
'.iwb-cwv-zpct{width:42px;height:24px;border:0;background:transparent;color:var(--iwb-text,#1c2333);font-size:11px;font-family:inherit;text-align:center;padding:0;outline:none;font-variant-numeric:tabular-nums}' +
|
||||
'.iwb-cwv-zpct:focus{background:var(--iwb-layer,#f0f1f4)}' +
|
||||
'.iwb-cwv-sep{width:1px;height:16px;background:var(--iwb-border,#d5d9e0);flex:0 0 auto;margin:0 1px}' +
|
||||
'.iwb-cwv-stage{position:relative;flex:1 1 auto;min-height:0;background:var(--iwb-layer2,#fff)}' +
|
||||
'.iwb-cwv-stage{position:relative;flex:1 1 auto;min-height:0;background:transparent}' +
|
||||
'.iwb-cwv-anchor{position:absolute;inset:0}' +
|
||||
'.iwb-cwv-empty{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;text-align:center;padding:18px;font-size:12px;line-height:1.7;white-space:pre-line;color:var(--iwb-text2,#4d5668)}' +
|
||||
'.iwb-cwv-spin{animation:iwb-cwv-rot .9s linear infinite}' +
|
||||
@@ -163,7 +189,7 @@
|
||||
|
||||
// 把网址放到画布上:新建一个「网页」节点并带上地址(宿主 canvasWrite 能力)。
|
||||
// 宿主 createNode 认变体 id('web')—— 不在内置 NODE_TYPES 里时会自动走 addPluginNode。
|
||||
// 返回 false 表示这个宿主没提供该能力(旧客户端 / 网页版),调用方自己选退路。
|
||||
// 返回 false 表示这个宿主没提供该能力(旧客户端),调用方自己选退路。
|
||||
function toCanvasNode(ctx, raw) {
|
||||
var url = normalizeUrl(raw)
|
||||
if (!url) return false
|
||||
@@ -191,6 +217,45 @@
|
||||
// 否则每切一次就多一个监听器,且旧闭包钉住整棵已脱离文档的 DOM,GC 不掉。
|
||||
var settingsOff = null
|
||||
|
||||
// 收藏夹下拉:同一时刻只允许一个面板菜单。document 监听只装一次,
|
||||
// 避免每次切 tab 重建面板都多挂一个监听器。
|
||||
var bmDocBound = false
|
||||
var bmActiveMenu = null
|
||||
// 原生收藏夹菜单(macOS/Windows)的点击回传:宿主 emit iwb-bookmark-open/add,
|
||||
// 这里只保留一个 document 级监听,路由到当前挂载的面板(nativeBmHandler)。
|
||||
var nativeBmBound = false
|
||||
var nativeBmHandler = null
|
||||
function bindNativeBm() {
|
||||
if (nativeBmBound) return
|
||||
var T = global.__TAURI__
|
||||
if (!T || !T.event || typeof T.event.listen !== 'function') return
|
||||
nativeBmBound = true
|
||||
try {
|
||||
T.event.listen('iwb-bookmark-open', function (ev) {
|
||||
var u = ev && ev.payload && ev.payload.url
|
||||
if (u && nativeBmHandler && typeof nativeBmHandler.open === 'function') nativeBmHandler.open(u)
|
||||
}).catch(function () { /* 事件通道不可用 */ })
|
||||
T.event.listen('iwb-bookmark-add', function (ev) {
|
||||
var p = (ev && ev.payload) || {}
|
||||
if (p.url && nativeBmHandler && typeof nativeBmHandler.add === 'function') nativeBmHandler.add(p.url, p.groupId || '')
|
||||
}).catch(function () { /* 事件通道不可用 */ })
|
||||
} catch (e) { /* 旧宿主没有 event API */ }
|
||||
}
|
||||
|
||||
function bindBmDoc() {
|
||||
if (bmDocBound || !document.addEventListener) return
|
||||
bmDocBound = true
|
||||
document.addEventListener('pointerdown', function (e) {
|
||||
var c = bmActiveMenu
|
||||
if (!c) return
|
||||
if (c.menu.contains(e.target) || c.btn.contains(e.target)) return
|
||||
c.close()
|
||||
}, true)
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Escape' && bmActiveMenu) bmActiveMenu.close()
|
||||
}, true)
|
||||
}
|
||||
|
||||
// ── 书签数据层(2026-11-19 从「每行一条文本」升级为分组结构)─────────────
|
||||
// 存储:settings.bookmarks 存一段 JSON 字符串。为什么不用对象:settings 的值会
|
||||
// 被宿主整包写进 localStorage/配置文件,标量最安全;对象在某些写回路径上会被
|
||||
@@ -647,9 +712,9 @@
|
||||
setZoom(st, clampZoom(pz0 / 100), false)
|
||||
st.empty.textContent = '在上方地址栏输入网址,网页会显示在这里'
|
||||
// 面板内浏览同样要靠宿主的原生 webview 引擎(src/canvas-webview.js):
|
||||
// 没有它(网页版 / 旧客户端)就是一块白板,必须说清原因而不是干等。
|
||||
// 没有它(旧客户端 / 合成测试宿主)就是一块白板,必须说清原因而不是干等。
|
||||
var hasEngine = !!(global.IWBCanvasWebview || (global.window && global.window.IWBCanvasWebview))
|
||||
if (!invoke()) st.empty.textContent = '面板内浏览需要桌面客户端;网页版请用系统浏览器打开。'
|
||||
if (!invoke()) st.empty.textContent = '面板内浏览需要桌面客户端;请用系统浏览器打开。'
|
||||
else if (!hasEngine) st.empty.textContent = '当前客户端还没有面板内浏览能力(需要 v3.25.30 及以上)。\n请先更新客户端。'
|
||||
// 面板关掉就没了,「✕ 关闭这个网页」在面板里没有意义
|
||||
st.close.style.display = 'none'
|
||||
@@ -712,60 +777,215 @@
|
||||
remember(u)
|
||||
}
|
||||
|
||||
// 书签:分组行 + 书签行。两行都单行横向滚动,尽量不占网页的高度。
|
||||
// 只有一个分组时整条分组行不渲染(避免「全部」和组名长得一样,白占一行)。
|
||||
var bmWrap = el('div', { class: 'iwb-browser-bmwrap' })
|
||||
var groupBar = el('div', { class: 'iwb-browser-groups' })
|
||||
var strip = el('div', { class: 'iwb-browser-strip' })
|
||||
bmWrap.appendChild(groupBar)
|
||||
bmWrap.appendChild(strip)
|
||||
var panelGroup = '' // '' = 全部
|
||||
// 收藏夹栏(v3.26.95,用户要 Chrome 那样):地址栏下面一条横向文件夹栏。
|
||||
// 点文件夹 → 在该按钮下方弹出这一组的书签;最右「»」列出所有分组。
|
||||
// 原生子 webview 会盖住 DOM:菜单展开时显式让宿主 park,宿主 v3.26.93+ 也会按浮层矩形自动 park。
|
||||
host.style.position = 'relative'
|
||||
var bmBar = st.bmBar
|
||||
var bmMenu = el('div', { class: 'iwb-browser-bmmenu', role: 'menu', 'aria-label': '收藏夹' })
|
||||
bmMenu.style.display = 'none'
|
||||
host.appendChild(bmMenu)
|
||||
var saveBtn = el('button', { class: 'iwb-cwv-btn iwb-br-bmsave', type: 'button', title: '收藏当前页' })
|
||||
saveBtn.appendChild(icon('star'))
|
||||
saveBtn.addEventListener('click', function (e) { e.stopPropagation(); addCurrentBookmark() })
|
||||
;(st.bmSlot || st.bar).appendChild(saveBtn)
|
||||
var bmOpen = false
|
||||
var bmMode = ''
|
||||
var bmAnchor = null
|
||||
var bmFlash = ''
|
||||
function flashBar(text) {
|
||||
bmFlash = String(text || '')
|
||||
renderBar()
|
||||
setTimeout(function () { if (bmFlash === text) { bmFlash = ''; renderBar() } }, 2200)
|
||||
}
|
||||
|
||||
function currentData() { return bmParse(ctx.settings.get('bookmarks')) }
|
||||
|
||||
function menuHeader() {
|
||||
var head = el('div', { class: 'iwb-br-bm-head' },
|
||||
el('span', { class: 'iwb-br-bm-title', text: '收藏夹' }))
|
||||
var add = el('button', { class: 'iwb-br-bm-add', type: 'button', title: '把当前页面加入第一个分组' })
|
||||
add.appendChild(icon('star'))
|
||||
add.appendChild(document.createTextNode(' 收藏当前页'))
|
||||
add.addEventListener('click', function (e) { e.stopPropagation(); addCurrentBookmark() })
|
||||
head.appendChild(add)
|
||||
return head
|
||||
}
|
||||
|
||||
function renderMenu() {
|
||||
var data = currentData()
|
||||
bmMenu.innerHTML = ''
|
||||
bmMenu.appendChild(menuHeader())
|
||||
var total = 0
|
||||
for (var gi = 0; gi < data.groups.length; gi++) {
|
||||
var g = data.groups[gi]
|
||||
if (bmMode && g.id !== bmMode) continue
|
||||
var visible = 0
|
||||
for (var vi = 0; vi < g.items.length; vi++) if (g.items[vi].url) visible++
|
||||
// 单组模式不再重复显示同名文件夹(用户指出这一层多余);「所有书签」才用分组标题
|
||||
if (!bmMode) {
|
||||
var folder = el('div', { class: 'iwb-br-bm-folder' })
|
||||
folder.appendChild(icon('folder'))
|
||||
folder.appendChild(el('span', { class: 'iwb-br-bm-fname', text: g.name }))
|
||||
folder.appendChild(el('span', { class: 'iwb-br-bm-count', text: String(visible) }))
|
||||
bmMenu.appendChild(folder)
|
||||
}
|
||||
for (var ii = 0; ii < g.items.length; ii++) {
|
||||
(function (item) {
|
||||
if (!item.url) return
|
||||
var row = el('button', { class: 'iwb-br-bm-item', type: 'button', title: item.url })
|
||||
row.appendChild(el('span', { class: 'iwb-br-bm-itext', text: item.title || hostOf(item.url) }))
|
||||
row.appendChild(el('span', { class: 'iwb-br-bm-iurl', text: hostOf(item.url) }))
|
||||
row.addEventListener('click', function () { closeMenu(); goTo(item.url) })
|
||||
bmMenu.appendChild(row)
|
||||
total++
|
||||
})(g.items[ii])
|
||||
}
|
||||
}
|
||||
if (!total) bmMenu.appendChild(el('div', { class: 'iwb-br-bm-empty', text: '这个分组还没有书签:打开网页后点地址栏的 ★ 收藏' }))
|
||||
positionMenu()
|
||||
}
|
||||
|
||||
function positionMenu() {
|
||||
if (!bmAnchor || !host.getBoundingClientRect) return
|
||||
var hr = host.getBoundingClientRect()
|
||||
var br = bmAnchor.getBoundingClientRect()
|
||||
var hostW = hr.width || 320
|
||||
var menuW = Math.max(180, Math.min(300, hostW - 12))
|
||||
var left = Math.max(4, Math.min(br.left - hr.left, hostW - menuW - 4))
|
||||
bmMenu.style.width = menuW + 'px'
|
||||
bmMenu.style.left = left + 'px'
|
||||
bmMenu.style.right = 'auto'
|
||||
bmMenu.style.top = Math.max(30, br.bottom - hr.top + 2) + 'px'
|
||||
}
|
||||
|
||||
function closeMenu() {
|
||||
bmOpen = false
|
||||
bmMenu.style.display = 'none'
|
||||
try {
|
||||
var CW = global.IWBCanvasWebview
|
||||
if (CW && typeof CW.setSuspended === 'function') CW.setSuspended(false)
|
||||
} catch (e) { /* 老宿主没有该 API */ }
|
||||
bmActiveMenu = null
|
||||
}
|
||||
|
||||
function openMenu(mode, anchorBtn) {
|
||||
bmMode = mode || ''
|
||||
bmAnchor = anchorBtn || null
|
||||
bmOpen = true
|
||||
renderMenu()
|
||||
bmMenu.style.display = ''
|
||||
try {
|
||||
var CW = global.IWBCanvasWebview
|
||||
if (CW && typeof CW.setSuspended === 'function') CW.setSuspended(true)
|
||||
} catch (e) { /* 老宿主:菜单可能被网页盖住 */ }
|
||||
bmActiveMenu = { menu: bmMenu, btn: bmAnchor, close: closeMenu }
|
||||
}
|
||||
|
||||
// 优先用宿主原生菜单(方案 B):OS 层弹出,网页不会消失;旧宿主/网页版自动退回 DOM 菜单。
|
||||
function openBookmarks(mode, anchorBtn) {
|
||||
// 记住当前打开的组:星标收藏要落在这个组(原生菜单关闭后 bmMode 仍然有效)
|
||||
bmMode = mode || ''
|
||||
var data = currentData()
|
||||
var groups = []
|
||||
for (var gi = 0; gi < data.groups.length; gi++) {
|
||||
var g = data.groups[gi]
|
||||
var items = []
|
||||
for (var ii = 0; ii < g.items.length; ii++) {
|
||||
var it = g.items[ii]
|
||||
if (!it.url) continue
|
||||
items.push({ title: it.title || hostOf(it.url), url: it.url })
|
||||
}
|
||||
groups.push({ id: g.id, name: g.name, items: items })
|
||||
}
|
||||
var cur = normalizeUrl(st.pageUrl || st.input.value) || ''
|
||||
// 网页版 / 没有 Tauri 桥:直接走 DOM 菜单(不要先发一个注定失败的 invoke)
|
||||
var inv = invoke()
|
||||
if (!inv) { openMenu(mode, anchorBtn); return }
|
||||
var p = inv('browser_bookmarks_menu', { mode: mode || '', groups: groups, currentUrl: cur })
|
||||
p.then(function (ok) {
|
||||
if (ok === false) openMenu(mode, anchorBtn)
|
||||
}).catch(function () { openMenu(mode, anchorBtn) })
|
||||
}
|
||||
|
||||
function renderBar() {
|
||||
if (!bmBar) return
|
||||
bmBar.innerHTML = ''
|
||||
var data = currentData()
|
||||
for (var gi = 0; gi < data.groups.length; gi++) {
|
||||
(function (g) {
|
||||
var b = el('button', { class: 'iwb-br-bmfolder', type: 'button', title: g.name })
|
||||
b.appendChild(icon('folder'))
|
||||
b.appendChild(el('span', { class: 'iwb-br-bmfname', text: g.name }))
|
||||
b.addEventListener('click', function (e) {
|
||||
e.stopPropagation()
|
||||
if (bmOpen && bmMode === g.id) { closeMenu(); return }
|
||||
openBookmarks(g.id, b)
|
||||
})
|
||||
bmBar.appendChild(b)
|
||||
})(data.groups[gi])
|
||||
}
|
||||
var all = el('button', { class: 'iwb-br-bmall', type: 'button', title: '所有书签' })
|
||||
all.appendChild(document.createTextNode('»'))
|
||||
all.addEventListener('click', function (e) { e.stopPropagation(); if (bmOpen && !bmMode) closeMenu(); else openBookmarks('', all) })
|
||||
bmBar.appendChild(all)
|
||||
if (bmFlash) bmBar.appendChild(el('span', { class: 'iwb-br-bmflash', text: bmFlash }))
|
||||
}
|
||||
|
||||
function renderBookmarks() {
|
||||
var data = bmParse(ctx.settings.get('bookmarks'))
|
||||
if (panelGroup && bmGroupAt(data, panelGroup) < 0) panelGroup = ''
|
||||
groupBar.innerHTML = ''
|
||||
strip.innerHTML = ''
|
||||
renderBar()
|
||||
if (bmOpen) renderMenu()
|
||||
}
|
||||
|
||||
if (data.groups.length > 1) {
|
||||
groupBar.style.display = ''
|
||||
var all = el('button', {
|
||||
class: 'iwb-browser-gchip' + (panelGroup === '' ? ' iwb-browser-gchip-on' : ''),
|
||||
type: 'button',
|
||||
title: '显示全部分组的书签'
|
||||
}, '全部 · ' + bmItems(data, '').length)
|
||||
all.addEventListener('click', function () { panelGroup = ''; renderBookmarks() })
|
||||
groupBar.appendChild(all)
|
||||
for (var gi = 0; gi < data.groups.length; gi++) {
|
||||
(function (g) {
|
||||
var on = panelGroup === g.id
|
||||
var chip = el('button', {
|
||||
class: 'iwb-browser-gchip' + (on ? ' iwb-browser-gchip-on' : ''),
|
||||
type: 'button',
|
||||
title: g.name
|
||||
}, g.name + ' · ' + g.items.length)
|
||||
chip.addEventListener('click', function () { panelGroup = g.id; renderBookmarks() })
|
||||
groupBar.appendChild(chip)
|
||||
})(data.groups[gi])
|
||||
function addBookmarkUrl(raw, groupId) {
|
||||
var u = normalizeUrl(raw)
|
||||
if (!u) { flashTitle(saveBtn, '先打开一个网页'); return false }
|
||||
var data = currentData()
|
||||
// 收藏目标:当前打开的组(bmMode)→ 指定 groupId → 第一个组。
|
||||
// 旧实现用「全库存在」判断 + 永远进 groups[0],在「海报」里点收藏时:
|
||||
// 命中「常用」里的同名 URL ⇒ 不写入,却提示「已经收藏过」;看起来就是收藏没落地。
|
||||
var target = -1
|
||||
var want = (typeof groupId === 'string') ? groupId : (bmMode || '')
|
||||
for (var gj = 0; gj < data.groups.length; gj++) if (data.groups[gj].id === want) target = gj
|
||||
if (target < 0) target = 0
|
||||
var targetHas = false
|
||||
var otherGroup = -1
|
||||
for (var gi = 0; gi < data.groups.length; gi++) {
|
||||
for (var ii = 0; ii < data.groups[gi].items.length; ii++) {
|
||||
if (data.groups[gi].items[ii].url !== u) continue
|
||||
if (gi === target) targetHas = true
|
||||
else if (otherGroup < 0) otherGroup = gi
|
||||
}
|
||||
} else {
|
||||
groupBar.style.display = 'none'
|
||||
}
|
||||
|
||||
var list = bmItems(data, panelGroup)
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
(function (item) {
|
||||
var chip = el('button', { class: 'iwb-browser-chip', type: 'button', title: item.url, text: item.title })
|
||||
chip.addEventListener('click', function () { goTo(item.url) })
|
||||
strip.appendChild(chip)
|
||||
})(list[i])
|
||||
if (!targetHas) {
|
||||
if (!data.groups.length) data.groups.push({ id: bmId('g'), name: '收藏夹', items: [] })
|
||||
data.groups[target].items.push({ id: bmId('i'), title: hostOf(u), url: u })
|
||||
try { ctx.settings.set('bookmarks', bmStringify(data)) } catch (e) { flashBar('收藏失败:设置写入异常'); return false }
|
||||
}
|
||||
if (!list.length) {
|
||||
strip.appendChild(el('span', { class: 'iwb-browser-strip-tip', text: '这个分组还没有书签' }))
|
||||
// 必须校验「目标组」里真的有这条;只校验全库会被别的组同名条目骗过。
|
||||
var saved = currentData()
|
||||
var savedTarget = null
|
||||
for (var sk = 0; sk < saved.groups.length; sk++) {
|
||||
if (!data.groups[target] || saved.groups[sk].id !== data.groups[target].id) continue
|
||||
for (var si = 0; si < saved.groups[sk].items.length; si++) if (saved.groups[sk].items[si].url === u) savedTarget = saved.groups[sk]
|
||||
}
|
||||
if (!savedTarget) { flashBar('收藏失败:设置未写入目标分组'); return false }
|
||||
bmMode = savedTarget.id
|
||||
renderBookmarks()
|
||||
var gname = savedTarget.name || '收藏夹'
|
||||
var label = targetHas ? ('已经收藏在「' + gname + '」') : ('已收藏到「' + gname + '」' + (otherGroup >= 0 ? '(另一组也有同名)' : ''))
|
||||
flashBar(label)
|
||||
flashTitle(saveBtn, label)
|
||||
return true
|
||||
}
|
||||
function addCurrentBookmark() { return addBookmarkUrl(st.pageUrl || st.input.value, bmMode) }
|
||||
bindBmDoc()
|
||||
bindNativeBm()
|
||||
nativeBmHandler = {
|
||||
open: function (u) { var n = normalizeUrl(u); if (n) goTo(n) },
|
||||
add: function (u, g) { addBookmarkUrl(u, g) },
|
||||
}
|
||||
renderBookmarks()
|
||||
host.appendChild(bmWrap)
|
||||
settingsOff = ctx.settings.onChange(function (name) {
|
||||
if (name === 'bookmarks') renderBookmarks()
|
||||
else if (name === 'panelZoom') {
|
||||
@@ -807,11 +1027,13 @@
|
||||
close: 'M6.5 6.5l7 7M13.5 6.5l-7 7',
|
||||
external: 'M8.5 11.5 14 6M14 6h-3.4M14 6v3.4',
|
||||
minus: 'M6.5 10h7',
|
||||
plus: 'M10 6.5v7M6.5 10h7'
|
||||
plus: 'M10 6.5v7M6.5 10h7',
|
||||
star: 'M10 3.2l2.05 4.15 4.58.67-3.31 3.23.78 4.56L10 13.68l-4.1 2.15.78-4.56-3.31-3.23 4.58-.67z',
|
||||
folder: 'M3.2 6.3h4.6l1.5 2h7.5v7.2H3.2z'
|
||||
}
|
||||
var ICON_TEXT = {
|
||||
back: '←', forward: '→', reload: '⟳', stop: '■', close: '✕',
|
||||
external: '↗', minus: '−', plus: '+'
|
||||
external: '↗', minus: '−', plus: '+', star: '★', folder: '📁'
|
||||
}
|
||||
function icon(name) {
|
||||
// 测试用的极简 DOM(tools/harness.mjs)没有 SVG API:退回文字图标,
|
||||
@@ -930,7 +1152,7 @@
|
||||
st.empty.textContent = '在地址栏输入网址,网页会显示在这个节点里'
|
||||
} else if (!supported) {
|
||||
st.empty.style.display = ''
|
||||
st.empty.textContent = '画布内网页需要桌面客户端;网页版请用左侧「浏览器」面板。'
|
||||
st.empty.textContent = '画布内网页需要桌面客户端;请用左侧「浏览器」面板。'
|
||||
} else if (!engine) {
|
||||
st.empty.style.display = ''
|
||||
st.empty.textContent = '当前客户端还没有画布内网页能力(需要 v3.25.29 及以上)。\n请先更新客户端;升级前可以点上方 ↗ 用「浏览器」面板打开。'
|
||||
@@ -973,17 +1195,22 @@
|
||||
zpct.value = '100%'
|
||||
var zoomBox = el('div', { class: 'iwb-cwv-zoom' }, [zMinus, zpct, zPlus])
|
||||
var input = el('input', { class: 'iwb-cwv-url', type: 'text', placeholder: '输入网址后回车' })
|
||||
// 收藏夹按钮槽位:面板挂载时把星标按钮放进来(画布节点留空)。放在地址栏后面。
|
||||
var bmSlot = el('span', { class: 'iwb-cwv-bmslot' })
|
||||
var sep = el('div', { class: 'iwb-cwv-sep' })
|
||||
var bar = el('div', { class: 'iwb-cwv-bar' }, [back, fwd, reload, input, zoomBox, sep, open, close])
|
||||
var bar = el('div', { class: 'iwb-cwv-bar' }, [back, fwd, reload, input, bmSlot, zoomBox, sep, open, close])
|
||||
// 收藏夹栏:浏览器式横向文件夹条(只有面板模式填内容;画布节点保持为空)
|
||||
var bmBar = el('div', { class: 'iwb-br-bmbar' })
|
||||
// 锚点:宿主 canvas-webview.js 按这个 div 的屏幕矩形去摆原生 webview
|
||||
var anchor = el('div', { class: 'iwb-cwv-anchor' })
|
||||
var empty = el('div', { class: 'iwb-cwv-empty' })
|
||||
var stage = el('div', { class: 'iwb-cwv-stage' }, [anchor, empty])
|
||||
host.appendChild(bar)
|
||||
host.appendChild(bmBar)
|
||||
host.appendChild(stage)
|
||||
return {
|
||||
id: '', node: null, props: null, ctx: ctx,
|
||||
bar: bar, input: input, anchor: anchor, empty: empty, stage: stage,
|
||||
bar: bar, input: input, bmSlot: bmSlot, bmBar: bmBar, anchor: anchor, empty: empty, stage: stage,
|
||||
back: back, fwd: fwd, reload: reload, close: close, open: open,
|
||||
zMinus: zMinus, zPlus: zPlus, zpct: zpct,
|
||||
acts: [back, fwd, reload, close, open],
|
||||
@@ -1121,6 +1348,16 @@
|
||||
if (p.url) s.pageUrl = p.url
|
||||
setLoading(s, !!p.loading)
|
||||
setAddress(s, s.pageUrl)
|
||||
// 加载失败不再用整块白底提示盖住网页:地址栏描红 + tooltip 说明(v3.26.93)
|
||||
// 用户裁定(2026-11-26):加载失败不要红框,保持默认灰边;失败只写 tooltip。
|
||||
if (p.loading) s.input.removeAttribute('title')
|
||||
if (p.failed) {
|
||||
s.input.removeAttribute('aria-invalid')
|
||||
s.input.title = '网页没有加载完成:可点 ⟳ 重试,或改用系统浏览器打开'
|
||||
} else {
|
||||
s.input.removeAttribute('title')
|
||||
if (!s.input.value || normalizeUrl(s.input.value)) s.input.removeAttribute('aria-invalid')
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1133,7 +1370,7 @@
|
||||
global.IWBPluginHost.register({
|
||||
id: 'browser',
|
||||
name: '应用内浏览器',
|
||||
version: '1.7.1',
|
||||
version: '1.8.6',
|
||||
apiVersion: 1,
|
||||
// canvasWrite:面板里的「↗」用它把当前页变成画布上的网页节点(需要客户端 v3.25.30+)
|
||||
capabilities: ['panels', 'nodeTypes', 'canvasWrite'],
|
||||
|
||||
+79
-29
@@ -105,6 +105,7 @@ function runPlugin({ invokeImpl, prefs, canvas } = {}) {
|
||||
log() {},
|
||||
settings: {
|
||||
get(k) { return settings[k] },
|
||||
set(k, v) { settings[k] = v; settingsListeners.forEach(function (fn) { try { fn(k) } catch (e) { /* ignore */ } }) },
|
||||
onChange(fn) {
|
||||
settingsListeners.push(fn)
|
||||
return function () { unsubscribed++ }
|
||||
@@ -135,6 +136,7 @@ function runPlugin({ invokeImpl, prefs, canvas } = {}) {
|
||||
return {
|
||||
registered, panel, calls, doc, nodeType,
|
||||
get unsubscribed() { return unsubscribed },
|
||||
settings,
|
||||
fireSetting: (name) => settingsListeners.forEach((fn) => fn(name)),
|
||||
setSetting: (k, v) => { settings[k] = v }
|
||||
}
|
||||
@@ -152,6 +154,8 @@ const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
|
||||
// 默认:打开成功、browser_state 报「窗口未打开」
|
||||
const okInvoke = () => (name) => {
|
||||
if (name === 'browser_state') return Promise.resolve({ open: false, url: '' })
|
||||
// harness 没有原生菜单:让插件走 DOM 回退,才能断言菜单项与点击
|
||||
if (name === 'browser_bookmarks_menu') return Promise.reject(new Error('no native menu in harness'))
|
||||
return Promise.resolve(true)
|
||||
}
|
||||
|
||||
@@ -189,9 +193,15 @@ const okInvoke = () => (name) => {
|
||||
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 slot = findClass(root, 'iwb-cwv-bmslot')
|
||||
const bmBar = findClass(root, 'iwb-br-bmbar')
|
||||
const bmFolders = bmBar ? bmBar.children.filter((c) => c.className === 'iwb-br-bmfolder') : []
|
||||
check('地址栏后有收藏按钮 + 收藏夹栏', !!slot && slot.children.some((c) => String(c.className).indexOf('iwb-br-bmsave') >= 0) && bmFolders.length >= 1)
|
||||
const bmMenu = findClass(root, 'iwb-browser-bmmenu')
|
||||
bmFolders[0].fire('click', { stopPropagation() {} })
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
const bmRows = bmMenu ? bmMenu.children.filter((c) => c.className === 'iwb-br-bm-item') : []
|
||||
check('点文件夹展开该组 4 个书签', bmRows.length === 4 && bmMenu.style.display !== 'none', '实际 ' + bmRows.length)
|
||||
const closeBtn = bar.children.find((c) => c.attrs.title && c.attrs.title.indexOf('关闭这个网页') >= 0)
|
||||
check('面板隐藏「✕ 关闭这个网页」(关掉面板就等于关闭)', !!closeBtn && closeBtn.style.display === 'none')
|
||||
}
|
||||
@@ -219,16 +229,68 @@ const okInvoke = () => (name) => {
|
||||
{
|
||||
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 bmMenu = findClass(root, 'iwb-browser-bmmenu')
|
||||
const bmBar = findClass(root, 'iwb-br-bmbar')
|
||||
const folders = bmBar.children.filter((c) => c.className === 'iwb-br-bmfolder')
|
||||
folders[0].fire('click', { stopPropagation() {} })
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
const rows = bmMenu.children.filter((c) => c.className === 'iwb-br-bm-item')
|
||||
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', {})
|
||||
rows[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))
|
||||
}
|
||||
|
||||
// ---------- 地址栏 ★:必须真的写入 settings(2026-11-26 用户反馈两个入口都收藏不了) ----------
|
||||
{
|
||||
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 slot = findClass(root, 'iwb-cwv-bmslot')
|
||||
const saveBtn = slot.children.find((c) => String(c.className).indexOf('iwb-br-bmsave') >= 0)
|
||||
input.value = 'example.com'
|
||||
input.fire('keydown', { key: 'Enter' })
|
||||
saveBtn.fire('click', { stopPropagation() {} })
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
let saved = null
|
||||
try { saved = JSON.parse(r.settings.bookmarks) } catch (e) { saved = null }
|
||||
const hit = saved && saved.groups && saved.groups.some((g) => g.items.some((i) => i.url === 'https://example.com/'))
|
||||
check('★ 收藏当前页真的写进 settings.bookmarks', !!hit, saved ? JSON.stringify(saved).slice(0, 120) : String(r.settings.bookmarks))
|
||||
}
|
||||
|
||||
// ---------- 跨组同名:在「海报」里收藏必须进「海报」,不能因「常用」已有就提示已收藏 ----------
|
||||
{
|
||||
const prefs = {
|
||||
bookmarks: JSON.stringify({
|
||||
v: 2,
|
||||
groups: [
|
||||
{ id: 'g1', name: '常用', items: [{ id: 'i1', title: 'Example', url: 'https://example.com/' }] },
|
||||
{ id: 'g2', name: '海报', items: [] }
|
||||
]
|
||||
})
|
||||
}
|
||||
const r = runPlugin({ invokeImpl: okInvoke(), prefs })
|
||||
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 slot = findClass(root, 'iwb-cwv-bmslot')
|
||||
const saveBtn = slot.children.find((c) => String(c.className).indexOf('iwb-br-bmsave') >= 0)
|
||||
const bmBar = findClass(root, 'iwb-br-bmbar')
|
||||
const folders = bmBar.children.filter((c) => c.className === 'iwb-br-bmfolder')
|
||||
folders[1].fire('click', { stopPropagation() {} })
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
input.value = 'example.com'
|
||||
input.fire('keydown', { key: 'Enter' })
|
||||
saveBtn.fire('click', { stopPropagation() {} })
|
||||
await new Promise((resolve) => setTimeout(resolve, 30))
|
||||
const saved = JSON.parse(r.settings.bookmarks)
|
||||
const g2 = saved.groups.find((g) => g.id === 'g2')
|
||||
check('在「海报」收藏后,URL 真的写入「海报」组', !!g2 && g2.items.some((i) => i.url === 'https://example.com/'), JSON.stringify(saved).slice(0, 160))
|
||||
}
|
||||
|
||||
// ---------- 面板「↗」:把当前页放到画布上(canvasWrite) ----------
|
||||
{
|
||||
const created = []
|
||||
@@ -340,7 +402,7 @@ const okInvoke = () => (name) => {
|
||||
check('stringify 后再 parse 结构不丢', api.parse(api.stringify(d2)).groups[0].items.length === 2)
|
||||
}
|
||||
|
||||
// ---------- 面板:分组 chip 切换 ----------
|
||||
// ---------- 面板:收藏夹按分组显示(浏览器式下拉) ----------
|
||||
{
|
||||
const r = runPlugin()
|
||||
const twoGroups = {
|
||||
@@ -352,26 +414,14 @@ const okInvoke = () => (name) => {
|
||||
}
|
||||
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 bar = findClass(root, 'iwb-br-bmbar')
|
||||
const barFolders = bar ? bar.children.filter((c) => c.className === 'iwb-br-bmfolder') : []
|
||||
check('收藏夹栏按分组渲染文件夹(2 组)', barFolders.length === 2, '实际 ' + barFolders.length)
|
||||
const allBtn = bar.children.find((c) => c.className === 'iwb-br-bmall')
|
||||
allBtn.fire('click', { stopPropagation() {} })
|
||||
const menu = findClass(root, 'iwb-browser-bmmenu')
|
||||
const items = menu ? menu.children.filter((c) => c.className === 'iwb-br-bm-item') : []
|
||||
check('» 所有书签显示 3 条', items.length === 3, '实际 ' + items.length)
|
||||
}
|
||||
|
||||
// ---------- 画布内网页节点 ----------
|
||||
@@ -396,7 +446,7 @@ const okInvoke = () => (name) => {
|
||||
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)
|
||||
host.children.indexOf(bar) === 0 && host.children.indexOf(stage) > host.children.indexOf(bar))
|
||||
const anchor = stage && stage.children.find((c) => c.className === 'iwb-cwv-anchor')
|
||||
check('内容区有原生 webview 锚点', !!anchor)
|
||||
check('锚点带节点 id(宿主据此摆位置)', anchor && anchor.attrs['data-iwb-cwv'] === 'n1',
|
||||
@@ -504,7 +554,7 @@ const okInvoke = () => (name) => {
|
||||
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)
|
||||
check('旧客户端节点显示「需要桌面客户端」提示', /桌面客户端/.test(empty._text), empty._text)
|
||||
}
|
||||
|
||||
// ---------- 旧客户端(有 Tauri、但没有画布 webview 引擎)必须提示升级 ----------
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# gallery 插件避坑事项
|
||||
|
||||
> 维护:改选中态/缩略图/补存后先读本文件,并跑 `node tests/plugin-gallery-ux-test.js`。
|
||||
> 版本:1.7.5(2026-11-26)
|
||||
|
||||
## 1. 选中态必须有形状差异
|
||||
|
||||
- 宿主已提供 `--iwb-selection-ring/on/bg/halo`,默认跟随强调色;
|
||||
- 选中格:2px 品牌边框 + `--iwb-selection-halo` 外圈 + **勾选圆点**;勾选点必须有 DOM(`.iwb-history-check`),只写 CSS 等于没有;
|
||||
- 多选禁止用 `opacity:.82` 把整墙图压黑(深色图会变黑块);最多 0.94;
|
||||
- 插件 `img:hover` 的 `box-shadow` 会覆盖宿主选中环;宿主用高优先级 `body .iwb-history-embedded ... .iwb-history-selected:hover img` 兜住,改选择器时别降级。
|
||||
|
||||
## 2. 缩略图与选中是两层
|
||||
|
||||
- 缩略图异步加载 / 失败重试 / 对象 URL 缓存的逻辑不要和选中类名混在一起;
|
||||
- `iwb-history-managed` 是“有选中项”的全局标记,`iwb-history-selected` 是单格;两者不能互相替代。
|
||||
|
||||
## 3. 落盘状态
|
||||
|
||||
- 条目 `orig: 'ok' | 'missing' | 'off' | 'pending'` 由宿主写入;插件只展示角标/补存入口;
|
||||
- 补存用 `ctx.gallery.backfill([name])`,不要自己 fetch 远程(跨域/权限都在宿主)。
|
||||
|
||||
## 4. 发版
|
||||
|
||||
- 改 `styles.css` 时注意插件样式在宿主之后加载;宿主选中规则必须留高优先级,否则被 hover 盖掉;
|
||||
- `package.json` / 入口 version / 市场同步;本文件不打包。
|
||||
|
||||
## 5. 最小回归清单
|
||||
|
||||
- [ ] 选中 1 张 / 多选 2 张:都有勾选点,边框品牌色
|
||||
- [ ] 多选时缩略图不被压黑
|
||||
- [ ] hover 选中格:选中环不消失
|
||||
- [ ] 原图缺失角标 / 底栏补存仍工作
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/gallery",
|
||||
"private": true,
|
||||
"version": "1.7.1",
|
||||
"version": "1.9.9",
|
||||
"description": "图库:右栏图片墙(筛选/多选/预览/插入画布/下载/删除),数据由宿主 gallery 能力提供",
|
||||
"ibwPlugin": {
|
||||
"id": "gallery",
|
||||
|
||||
+296
-41
@@ -10,6 +10,8 @@
|
||||
// ② 格子「插入」补 insertK(与右键/顶部一致,尺寸档不再被忽略)。
|
||||
// ③ 插入/删除补「插入中…」状态,删除改成等宿主删完再重拉(固定 250ms 会拉到未删完的清单)。
|
||||
// 注:搜索框在 v1.6.1 已按用户意见移除,不再加回。
|
||||
// v1.7.2(2026-11-25):按用户意见去掉**图片卡片上**的「插入」按钮,卡片只保留「下载」;
|
||||
// 顶部工具栏「插入 / 下载」和右键菜单的「插入画布」保持不变。
|
||||
;(function (global) {
|
||||
'use strict'
|
||||
if (!global.IWBPluginHost) return
|
||||
@@ -92,6 +94,7 @@
|
||||
var cfg = Object.assign({}, DEF)
|
||||
var items = []
|
||||
var thumbCache = {}
|
||||
var thumbOrder = [] // 缩略图缓存的上限管理(FIFO)
|
||||
var thumbPending = {} // 进行中的缩略图请求(v1.6.9)
|
||||
var total = 0
|
||||
var limit = 100
|
||||
@@ -114,6 +117,13 @@
|
||||
var failEl = el('span', { class: 'iwb-gal-fail', text: '' })
|
||||
failEl.style.display = 'none'
|
||||
failEl.addEventListener('click', function () { retryAll() })
|
||||
// v1.7.4:「仅缩略图」统计 —— 原图没落盘时点一下批量补存(宿主把远程字节写回 images/gallery)
|
||||
var origEl = el('span', { class: 'iwb-gal-orig', text: '' })
|
||||
origEl.style.display = 'none'
|
||||
origEl.addEventListener('click', function () {
|
||||
var names = items.filter(function (x) { return x.orig && x.orig !== 'ok' }).map(function (x) { return x.name })
|
||||
if (names.length) doBackfill(names)
|
||||
})
|
||||
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')
|
||||
@@ -155,7 +165,7 @@
|
||||
// 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)
|
||||
el('div', { class: 'iwb-gal-foot-left' }, countEl, pickedEl, failEl, origEl, statusEl), tools)
|
||||
var wrap = el('div', { class: 'iwb-history-embedded' }, [head, grid, more, empty, foot, settings])
|
||||
|
||||
function setOpen (open) {
|
||||
@@ -200,6 +210,7 @@
|
||||
.then(function () { setStatus('已插入:' + it.name) })
|
||||
.catch(function () { setStatus('插入失败') })
|
||||
})
|
||||
if (it.orig && it.orig !== 'ok') item('补存原图', function () { doBackfill([it.name]) })
|
||||
item('下载', function () { doDownload([it.name]) })
|
||||
item('预览大图', function () { try { ctx.gallery.preview(it.name) } catch (err) { /* ignore */ } })
|
||||
item('复制文件名', function () {
|
||||
@@ -261,6 +272,9 @@
|
||||
failed = {}
|
||||
updateFail()
|
||||
setStatus('重试中…')
|
||||
// v1.9.6:先清掉卡片缓存 —— 失败那张的缓存只有失败占位(没有 img),
|
||||
// 不清就等于把坏卡原样拿回来,重试永远看不到图(unit 里「两张都应重新挂上 img」会红)。
|
||||
try { for (var ck in nodeCache) delete nodeCache[ck]; nodeOrder.length = 0 } catch (e6) { /* ignore */ }
|
||||
render()
|
||||
}
|
||||
function pickedNames () { return Object.keys(picked) }
|
||||
@@ -269,6 +283,9 @@
|
||||
clear(actions)
|
||||
countEl.textContent = items.length + ' / ' + total + ' 张'
|
||||
pickedEl.textContent = count() ? ('已选 ' + count()) : ''
|
||||
var missing = items.filter(function (x) { return x.orig && x.orig !== 'ok' }).length
|
||||
if (missing) { origEl.style.display = ''; origEl.textContent = missing + ' 张仅缩略图 · 补存'; origEl.title = '这些图的原图没有写进本地(只有 320px 缩略图)。点一下把远程原图补存到 images/gallery' }
|
||||
else { origEl.style.display = 'none'; origEl.textContent = '' }
|
||||
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 })
|
||||
@@ -326,36 +343,111 @@
|
||||
settings.appendChild(row('range', RANGES, '时间范围', '按生成时间筛选'))
|
||||
}
|
||||
|
||||
function renderGrid () {
|
||||
clear(grid)
|
||||
// v1.8.3:拖动停靠栏卡顿的根因是「每一帧 ResizeObserver → renderGrid → clear + 重建全部卡片」,
|
||||
// 每张卡要重建 ~10 个节点、重新挂事件、重新 paint 缩略图。改成复用节点:把缓存里的卡片
|
||||
// 直接 appendChild 到新列里(DOM 移动,不销毁),缩略图与事件全部保留。
|
||||
// ── v1.9.0 虚拟列表:200+ 张时只渲染「视口附近」的卡片 ────────────────────
|
||||
// 原来每次重排/滚动都把全部卡片建一遍(200 张 ≈ 2000+ DOM 节点),拖动停靠栏自然掉帧。
|
||||
// 现在:先用「列宽 + 宽高比」纯数学算出每张卡的列与 y 偏移,再只为可见范围建 DOM,
|
||||
// 上下用高度占位块撑住滚动条 —— 滚动位置、滚动条长度都和不虚拟化时一致。
|
||||
var layoutState = null
|
||||
var winState = { top: -1, viewH: 0 }
|
||||
var scrollBound = false
|
||||
var scrollRaf = 0
|
||||
|
||||
// 找到真正滚动的祖先(虚拟列表要按它的 scrollTop/clientHeight 算可见窗口)
|
||||
var scCache = null
|
||||
var padCache = null
|
||||
function scrollerOf () {
|
||||
if (scCache && scCache.isConnected) return scCache
|
||||
padCache = null
|
||||
var p = grid && grid.parentNode
|
||||
while (p && p.nodeType === 1) {
|
||||
var oy = ''
|
||||
try { oy = global.getComputedStyle ? global.getComputedStyle(p).overflowY : '' } catch (e) { oy = '' }
|
||||
if (p.scrollHeight > p.clientHeight + 4 && /(auto|scroll)/.test(String(oy))) { scCache = p; return p }
|
||||
p = p.parentNode
|
||||
}
|
||||
scCache = (grid && grid.parentNode) || null
|
||||
return scCache
|
||||
}
|
||||
// v1.9.3:不加滞回 —— 用户实测「拖动时列数不跟着变、停手才变」比偶尔多排一次更难受。
|
||||
// 列数切换的重排代价已由「卡片节点复用」压到很低,所以直接按宽度实时切。
|
||||
function colsFor (w, prev) {
|
||||
var gap = 6
|
||||
// 每次重排都重新量一次宽度:面板显隐/停靠栏展开时 gridW 可能是旧值,
|
||||
// 只靠 ResizeObserver 会在「变成 0 再回来」期间漏掉,导致必须拖宽度才出图。
|
||||
var liveW = availableW()
|
||||
if (liveW > 0 && Math.abs(liveW - gridW) > 1) gridW = liveW
|
||||
var tileW = Math.max(40, Number(cfg.tile) || 110)
|
||||
return Math.max(1, Math.floor((w + gap) / (tileW + gap)))
|
||||
}
|
||||
function computeLayout () {
|
||||
var gap = 6
|
||||
var liveW = usableW()
|
||||
if (liveW > 0) 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 n = colsFor(gridW, layoutState ? layoutState.n : 0)
|
||||
var colW = Math.max(40, Math.floor((gridW - gap * (n - 1)) / n))
|
||||
var cols = []
|
||||
var heights = []
|
||||
for (var c = 0; c < n; c++) { cols.push([]); heights.push(0) }
|
||||
for (var c = 0; c < n; c++) { cols.push({ list: [], h: 0 }); 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 h = Math.max(24, Math.round(colW * ratio))
|
||||
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
|
||||
cols[min].list.push({ it: it, y: heights[min], h: h })
|
||||
heights[min] += h + 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)
|
||||
var totalH = 0
|
||||
for (var c2 = 0; c2 < n; c2++) { cols[c2].h = heights[c2] ? heights[c2] - gap : 0; if (cols[c2].h > totalH) totalH = cols[c2].h }
|
||||
return { n: n, colW: colW, gap: gap, cols: cols, totalH: totalH }
|
||||
}
|
||||
|
||||
function spacer (h) {
|
||||
var d = el('div', { class: 'iwb-gal-spacer' })
|
||||
d.style.height = Math.max(0, Math.round(h)) + 'px'
|
||||
d.style.flex = '0 0 auto'
|
||||
return d
|
||||
}
|
||||
|
||||
function renderGrid (force) {
|
||||
var sc = scrollerOf()
|
||||
if (sc && !scrollBound) {
|
||||
scrollBound = true
|
||||
sc.addEventListener('scroll', function () {
|
||||
if (scrollRaf) return
|
||||
scrollRaf = global.requestAnimationFrame(function () { scrollRaf = 0; try { renderGrid() } catch (e) { /* ignore */ } })
|
||||
}, { passive: true })
|
||||
}
|
||||
if (force || !layoutState) layoutState = computeLayout()
|
||||
var L = layoutState
|
||||
var virtual = !!(sc && sc.scrollHeight > sc.clientHeight + 40)
|
||||
var top = virtual ? sc.scrollTop : 0
|
||||
var viewH = virtual ? sc.clientHeight : 100000
|
||||
// 滚动幅度不大且已有内容 ⇒ 不重建(滚动事件很密,重建一次就是几十个节点)
|
||||
if (!force && winState.top >= 0 && grid.firstChild && Math.abs(top - winState.top) < viewH * 0.6 && winState.viewH === viewH) return
|
||||
winState.top = top
|
||||
winState.viewH = viewH
|
||||
var from = Math.max(0, top - viewH * 1.2)
|
||||
var to = top + viewH * 2.4
|
||||
clear(grid)
|
||||
for (var ci = 0; ci < L.cols.length; ci++) {
|
||||
var colDef = L.cols[ci]
|
||||
var list = colDef.list
|
||||
var box = el('div', { class: 'iwb-history-col', style: 'width:' + L.colW + 'px;flex:0 0 auto' })
|
||||
var start = 0
|
||||
while (start < list.length && list[start].y + list[start].h < from) start++
|
||||
var end = start
|
||||
while (end < list.length && list[end].y <= to) end++
|
||||
var topY = start < list.length ? list[start].y : colDef.h
|
||||
if (topY > 0) box.appendChild(spacer(topY))
|
||||
for (var k = start; k < end; k++) box.appendChild(itemNode(list[k].it, k))
|
||||
var bottomY = end < list.length ? list[end].y : colDef.h
|
||||
if (bottomY < colDef.h) box.appendChild(spacer(colDef.h - bottomY))
|
||||
grid.appendChild(box)
|
||||
}
|
||||
empty.style.display = items.length ? 'none' : ''
|
||||
try { syncSelection() } catch (e) { /* ignore */ }
|
||||
clear(more)
|
||||
if (total > items.length) {
|
||||
var b = el('button', { class: 'iwb-btn iwb-btn-sm', text: '显示更多(' + (total - items.length) + ' 张)' })
|
||||
@@ -364,13 +456,37 @@
|
||||
}
|
||||
}
|
||||
|
||||
function itemNode (it) {
|
||||
// v1.9.3:卡片节点复用。列数切换时不再重建这几十张卡(重建会重新解码缩略图,实测停顿约 1 秒),
|
||||
// 只把已有节点 appendChild 到新列里(DOM 移动,图片和事件都保留)。
|
||||
var nodeCache = {}
|
||||
var nodeOrder = []
|
||||
function itemNode (it, seq) {
|
||||
var hit = nodeCache[it.name]
|
||||
// v1.9.6:失败过的卡片不复用 —— 缓存里那张只有失败占位(没有 img),
|
||||
// 复用会让「全部重试」永远无效(重试只重建 DOM,拿回的还是那张坏卡)。
|
||||
if (hit && hit.__iwbItem === it && !failed[it.name]) {
|
||||
// 复用时把上轮可能还停在 display:none 的缩略图复位(否则看起来「没图」)
|
||||
var hi = hit.querySelector('img')
|
||||
if (hi && hi.style.display === 'none' && hi.complete && hi.naturalWidth > 0) hi.style.display = ''
|
||||
// v1.9.7:卡片被淘汰时 src 被摘掉了(见下),复用时重新取一次缩略图,否则是张空白卡
|
||||
if (hi && !hi.getAttribute('src') && typeof hit.__iwbBoot === 'function') { try { hit.__iwbBoot() } catch (e5) { /* ignore */ } }
|
||||
return hit
|
||||
}
|
||||
var on = !!picked[it.name]
|
||||
var box = el('div', { class: 'iwb-history-item' + (count() ? ' iwb-history-managed' : '') + (on ? ' iwb-history-selected' : '') })
|
||||
box.setAttribute('data-name', it.name)
|
||||
// 缩略图是**异步**的(ctx.gallery.thumb 返回 Promise):先占位,拿到地址再挂 img。
|
||||
// v1.2.0:加载失败自动重试 2 次(图片还没落盘/临时不可读),仍失败才显示可点击重试的占位。
|
||||
box.title = it.name + '(单击单选 · Shift+单击多选 · 双击放大 · 拖到画布=参考图节点)'
|
||||
var holder = el('div', { class: 'iwb-history-missing', text: '加载中…' })
|
||||
var origBadge = null
|
||||
if (it.orig && it.orig !== 'ok') {
|
||||
origBadge = el('span', { class: 'iwb-gal-origbadge', text: it.orig === 'off' ? '未备份' : '仅缩略图' })
|
||||
origBadge.title = it.orig === 'off' ? '原图入库已关闭:这张只有缩略图' : '原图没有写进本地:右键可「补存原图」'
|
||||
}
|
||||
// v1.9.4:卡片先按宽高比占位 —— 否则缩略图出现的瞬间卡片从「一行字高」长成整图高,
|
||||
// 整列跟着重排,滚动时就表现为闪动。
|
||||
if (it.w && it.h) { try { box.style.aspectRatio = it.w + ' / ' + it.h } catch (e0) { /* ignore */ } }
|
||||
var holder = el('div', { class: 'iwb-history-missing', text: it.w && it.h ? '' : '加载中…' })
|
||||
box.appendChild(holder)
|
||||
var tries = 0
|
||||
function fail (text) {
|
||||
@@ -392,7 +508,12 @@
|
||||
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
|
||||
if (url && typeof url === 'string') {
|
||||
thumbCache[key] = url
|
||||
thumbOrder.push(key)
|
||||
// 上限 400:200+ 张的图库来回滚会把 objectURL 一直攒在内存里
|
||||
while (thumbOrder.length > 80) { var oldK = thumbOrder.shift(); if (oldK && oldK !== key) { try { delete thumbCache[oldK] } catch (e2) { /* ignore */ } } }
|
||||
}
|
||||
delete thumbPending[key]
|
||||
return url
|
||||
}, function (e) { delete thumbPending[key]; throw e })
|
||||
@@ -401,9 +522,11 @@
|
||||
}
|
||||
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' })
|
||||
// v1.9.1:不再因为「此刻不在文档里」直接放弃 —— 虚拟列表滚动时会先离屏再挂载,
|
||||
// 放弃会导致某些卡片永远停在「加载中…」(缩略图缓存已存,只是没人把它挂上去)。
|
||||
var img = el('img', { src: url, alt: '', loading: 'eager', decoding: 'async', draggable: 'true' })
|
||||
if (it.w && it.h) img.setAttribute('style', 'aspect-ratio:' + it.w + ' / ' + it.h)
|
||||
try { if (typeof img.decode === 'function') img.decode().catch(function () {}) } catch (e4) { /* ignore */ }
|
||||
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 }
|
||||
@@ -417,7 +540,6 @@
|
||||
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]
|
||||
@@ -431,7 +553,6 @@
|
||||
e.dataTransfer.effectAllowed = 'copy'
|
||||
} catch (err) { /* ignore */ }
|
||||
})
|
||||
img.style.display = 'none'
|
||||
box.appendChild(img)
|
||||
// v1.6.9:坏图/超时兜底 —— 某些坏字节既不触发 load 也不触发 error,700ms 后直接判定失败(可点击重试)
|
||||
setTimeout(function () {
|
||||
@@ -446,6 +567,9 @@
|
||||
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('缩略图加载失败(点击重试)') } }
|
||||
}
|
||||
// v1.8.0:缩略图按可见性懒加载(IntersectionObserver,上下预取 300px)——
|
||||
// 原来一次性对全部条目发 IPC 取缩略图,列表一长首屏就慢。
|
||||
// v1.8.1:撤销懒加载——IntersectionObserver 在停靠栏里不稳定,大量卡片停在「加载中…」
|
||||
boot()
|
||||
box.addEventListener('contextmenu', function (e) { openMenu(e, it) })
|
||||
var acts = el('div', { class: 'iwb-history-actions' })
|
||||
@@ -454,15 +578,40 @@
|
||||
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('插入失败') })
|
||||
}))
|
||||
// v1.7.2:图片卡片上只留「下载」;插入仍可从顶部工具栏或右键菜单进入。
|
||||
acts.appendChild(act('下载', '下载到本地', function () { doDownload([it.name]) }))
|
||||
box.appendChild(acts)
|
||||
// 角标/勾选最后挂:不要 z-index(插件层级闸门禁止裸值),靠 DOM 顺序盖在图片上
|
||||
if (origBadge) box.appendChild(origBadge)
|
||||
if (on) box.appendChild(el('span', { class: 'iwb-history-check', title: '已选中' }))
|
||||
box.__iwbItem = it
|
||||
box.__iwbBoot = boot
|
||||
nodeCache[it.name] = box
|
||||
nodeOrder.push(it.name)
|
||||
// v1.9.8(修 1.9.7 的回归):1.9.7 把上限压到 60 并顺手把节点从 DOM 移除,
|
||||
// 但面板在**没有滚动容器**时会整屏渲染全部卡片(实测 100+ 张)⇒ 淘汰到还在屏上的卡,
|
||||
// 正在「加载中」的那张被移出 DOM 就永远画不出来(用户实测:整墙卡在加载中)。
|
||||
// 现在的规则:① 上限放到 300;② **只淘汰已脱离文档**的卡(虚拟列表滚走的那些);
|
||||
// ③ 淘汰时显式摘 src,让解码位图尽快回收。屏上的卡永远不动。
|
||||
if (nodeOrder.length > 300) {
|
||||
var drop = nodeOrder.length - 300
|
||||
var keepOrder = []
|
||||
for (var oi = 0; oi < nodeOrder.length; oi++) {
|
||||
var on = nodeOrder[oi]
|
||||
var ob = nodeCache[on]
|
||||
if (drop > 0 && ob && !ob.isConnected) {
|
||||
try {
|
||||
var oimg = ob.querySelector('img')
|
||||
if (oimg) oimg.removeAttribute('src')
|
||||
delete nodeCache[on]
|
||||
drop--
|
||||
continue
|
||||
} catch (e3) { /* ignore */ }
|
||||
}
|
||||
keepOrder.push(on)
|
||||
}
|
||||
nodeOrder = keepOrder
|
||||
}
|
||||
return box
|
||||
}
|
||||
|
||||
@@ -472,6 +621,17 @@
|
||||
clearTimeout(statusTimer)
|
||||
if (text) statusTimer = setTimeout(function () { statusEl.textContent = '' }, 4000)
|
||||
}
|
||||
function doBackfill (names) {
|
||||
if (!ctx.gallery || typeof ctx.gallery.backfill !== 'function') { setStatus('当前宿主不支持补存原图'); return }
|
||||
setStatus('补存中…(' + names.length + ' 张)')
|
||||
Promise.resolve(ctx.gallery.backfill(names)).then(function (r) {
|
||||
var ok = (r && (r.ok || r.count)) || 0
|
||||
var failed = (r && r.failed) || []
|
||||
if (failed.length) setStatus('补存完成 ' + ok + ' 张,' + failed.length + ' 张失败(远程链接取不到)')
|
||||
else setStatus('已补存 ' + ok + ' 张原图')
|
||||
return load()
|
||||
}).catch(function () { setStatus('补存失败,可稍后重试') })
|
||||
}
|
||||
function doDownload (names) {
|
||||
setStatus('下载中…')
|
||||
return Promise.resolve(ctx.gallery.download(names)).then(function (r) {
|
||||
@@ -482,12 +642,44 @@
|
||||
}).catch(function () { setStatus('下载失败,可再点一次重试') })
|
||||
}
|
||||
|
||||
// v1.8.1:双击打开改成在 grid 上做事件委托 —— 原来监听在 <img> 上,一旦卡片被重绘替换,
|
||||
// dblclick 就永远落不到同一个元素(用户反馈「双击打不开」)。委托到容器后按 data-name 处理。
|
||||
grid.addEventListener('dblclick', function (e) {
|
||||
var node = e.target
|
||||
while (node && node !== grid && !(node.getAttribute && node.getAttribute('data-name'))) node = node.parentNode
|
||||
if (!node || node === grid) return
|
||||
var nm = node.getAttribute('data-name')
|
||||
if (!nm) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
try { ctx.gallery.preview(nm) } catch (err) { /* ignore */ }
|
||||
})
|
||||
|
||||
function pick (name, shift) {
|
||||
if (shift) { if (picked[name]) delete picked[name]; else picked[name] = 1 } else { picked = {}; picked[name] = 1 }
|
||||
render()
|
||||
// v1.8.0:选中只就地改 class/勾选角标 —— 原来整个网格重建,滚动条被顶回顶部,
|
||||
// 而且正在双击的那张 <img> 被换掉,双击因此经常打不开。
|
||||
syncSelection()
|
||||
renderHead()
|
||||
// 顺手量一次宽度:面板被拖窄后如果没有其它触发条件,列数会停在旧值上(卡片被窗口裁掉)
|
||||
try { measure() } catch (e) { /* ignore */ }
|
||||
}
|
||||
function syncSelection () {
|
||||
var managed = !!count()
|
||||
var boxes = grid.querySelectorAll('[data-name]')
|
||||
for (var i = 0; i < boxes.length; i++) {
|
||||
var b = boxes[i]
|
||||
var nm = b.getAttribute('data-name')
|
||||
var on = !!picked[nm]
|
||||
if (b.classList.contains('iwb-history-selected') !== on) b.classList.toggle('iwb-history-selected', on)
|
||||
if (b.classList.contains('iwb-history-managed') !== managed) b.classList.toggle('iwb-history-managed', managed)
|
||||
var check = b.querySelector('.iwb-history-check')
|
||||
if (on && !check) b.appendChild(el('span', { class: 'iwb-history-check', title: '已选中' }))
|
||||
else if (!on && check && check.parentNode === b) b.removeChild(check)
|
||||
}
|
||||
}
|
||||
|
||||
function render () { renderHead(); renderGrid(); global.requestAnimationFrame(function () { try { measure() } catch (e) {} }); setTimeout(function () { try { measure() } catch (e) {} }, 150) }
|
||||
function render () { var sc = scrollerOf(); var top = sc ? sc.scrollTop : 0; renderHead(); layoutState = null; winState.top = -1; renderGrid(true); if (sc) sc.scrollTop = top; global.requestAnimationFrame(function () { try { measure() } catch (e) {} }); setTimeout(function () { try { measure() } catch (e) {} }, 150) }
|
||||
|
||||
function load (force) {
|
||||
if (force) setStatus('刷新中…')
|
||||
@@ -510,6 +702,30 @@
|
||||
|
||||
// 宽度测量:列数只由「面板宽 / 图幅」决定
|
||||
// v1.6.5:面板刚挂载时 grid 宽度可能是 0,而 grid 宽度又取决于列宽 → RO 不会触发,图库一直空白。
|
||||
// v1.8.2:可用宽度按「真正滚动的容器」算,扣掉内边距和滚动条余量。
|
||||
// 原来用 wrap.clientWidth(面板全宽),右侧有滚动条/内边距时 4 列总宽会超出,最右一列被裁掉。
|
||||
function usableW () {
|
||||
var sc = scrollerOf()
|
||||
var w = 0
|
||||
if (sc) {
|
||||
// 内边距缓存:拖动时每帧 getComputedStyle 会强制样式重算(这是每帧的固定开销)
|
||||
if (!padCache) {
|
||||
var cs = null
|
||||
try { cs = global.getComputedStyle ? global.getComputedStyle(sc) : null } catch (e) { cs = null }
|
||||
padCache = { l: cs ? (parseFloat(cs.paddingLeft) || 0) : 0, r: cs ? (parseFloat(cs.paddingRight) || 0) : 0 }
|
||||
}
|
||||
w = sc.clientWidth - padCache.l - padCache.r
|
||||
}
|
||||
// v1.9.6:量不到宽度时返回 0(交回调用方用 320 的兜底值)。
|
||||
// 原来这里强制 Math.max(80, …),jsdom 里 clientWidth 恒为 0 ⇒ 面板被当成 80px ⇒ 只剩 1 列,
|
||||
// 多列布局的单元测试因此全红(真实环境不受影响,但测试不该和现实不一致)。
|
||||
if (!w || w < 80) {
|
||||
var aw = availableW()
|
||||
if (!aw) return 0
|
||||
w = aw
|
||||
}
|
||||
return Math.max(80, Math.floor(w) - 4)
|
||||
}
|
||||
function availableW () {
|
||||
// v1.6.6:优先量「会随面板拉伸的外层容器」,而不是 grid 自身
|
||||
// (grid 现在是 flex-start + 内容宽度,面板变宽它不会变宽 → RO 不触发 → 列数永不补齐)
|
||||
@@ -518,22 +734,61 @@
|
||||
if (!w) w = grid.clientWidth
|
||||
return w || 0
|
||||
}
|
||||
var renderRaf = 0
|
||||
function scheduleRender () {
|
||||
if (renderRaf) return
|
||||
renderRaf = global.requestAnimationFrame(function () { renderRaf = 0; try { layoutState = null; winState.top = -1; renderGrid(true) } catch (e) { /* ignore */ } })
|
||||
}
|
||||
var measureTimer = 0
|
||||
function measureNow () {
|
||||
padCache = null // 尺寸/样式可能变了,重新量一次内边距
|
||||
var w = usableW()
|
||||
if (w > 0 && Math.abs(w - gridW) >= 4) { gridW = w; scheduleRender() }
|
||||
}
|
||||
// 拖动中的廉价重排:列数没变就只改进已有的列宽(几条 style 写入),不重建卡片
|
||||
function quickWidth () {
|
||||
var w = usableW()
|
||||
if (!w || !layoutState) return false
|
||||
var gap = 6
|
||||
var tileW = Math.max(40, Number(cfg.tile) || 110)
|
||||
var n = colsFor(w, layoutState.n)
|
||||
if (n !== layoutState.n) return false
|
||||
var colW = Math.max(40, Math.floor((w - gap * (n - 1)) / n))
|
||||
var cols = grid.children
|
||||
for (var i = 0; i < cols.length; i++) { try { cols[i].style.width = colW + 'px' } catch (e) { /* ignore */ } }
|
||||
gridW = w
|
||||
return true
|
||||
}
|
||||
function measure () {
|
||||
var w = availableW()
|
||||
if (w > 0 && Math.abs(w - gridW) > 1) { gridW = w; renderGrid() }
|
||||
var w = usableW()
|
||||
if (!w) return
|
||||
// 列数变了立刻重排(合并到一帧;节点复用后代价很小,列数能跟着拖动实时变)
|
||||
if (layoutState && colsFor(w, 0) !== layoutState.n) {
|
||||
gridW = w
|
||||
clearTimeout(measureTimer)
|
||||
scheduleRender()
|
||||
return
|
||||
}
|
||||
// 列数不变:只改列宽,不重建卡片
|
||||
if (quickWidth()) return
|
||||
clearTimeout(measureTimer)
|
||||
measureTimer = setTimeout(measureNow, 120)
|
||||
}
|
||||
if (global.document && global.document.addEventListener) {
|
||||
global.document.addEventListener('pointerup', function () { clearTimeout(measureTimer); measureNow() }, true)
|
||||
}
|
||||
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 }
|
||||
if (gridW > 0 || tries++ > 40) { if (gridW <= 0) { gridW = Math.max(160, Number(cfg.tile) || 110) * 2; layoutState = null; winState.top = -1; renderGrid(true) } 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) })
|
||||
;[120, 400, 900].forEach(function (ms) { setTimeout(function () { try { measure(); if (gridW > 0) { layoutState = null; winState.top = -1; renderGrid(true) } } catch (e) { /* ignore */ } }, ms) })
|
||||
|
||||
// v1.3.0:自动恢复 —— 面板重新可见(切回 tab / 窗口聚焦 / 后台回来)且距上次拉取 >5s 时重拉一次,
|
||||
// 这样图床恢复、后台补图后不必手动刷新;同时保留底部「刷新」按钮做即时重试。
|
||||
@@ -562,7 +817,7 @@
|
||||
for (var i = 0; i < entries.length; i++) {
|
||||
if (entries[i].isIntersecting) {
|
||||
// v1.6.7:面板真正可见后再量一次宽度并重排(首帧可能还是 0 宽)
|
||||
try { measure(); renderGrid() } catch (e) { /* ignore */ }
|
||||
try { measure(); layoutState = null; winState.top = -1; renderGrid(true) } catch (e) { /* ignore */ }
|
||||
autoRefresh()
|
||||
}
|
||||
}
|
||||
@@ -594,7 +849,7 @@
|
||||
global.IWBPluginHost.register({
|
||||
id: 'gallery',
|
||||
name: '图库',
|
||||
version: '1.7.1',
|
||||
version: '1.9.9',
|
||||
apiVersion: 1,
|
||||
capabilities: ['panels', 'gallery'],
|
||||
data: { schemaVersion: 1, maxBytes: 65536 },
|
||||
@@ -607,4 +862,4 @@
|
||||
})
|
||||
return {}
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
+39
-3
@@ -65,18 +65,42 @@
|
||||
|
||||
/* ---- 图片墙 ---- */
|
||||
.iwb-history-grid { overscroll-behavior: contain; }
|
||||
.iwb-history-embedded .iwb-history-item { position: relative; flex: none; width: 100%; }
|
||||
.iwb-history-embedded .iwb-history-item { position: relative; flex: none; width: 100%; contain: layout style; }
|
||||
.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;
|
||||
/* 2026-12-01:卡片不再做 hover 放大/投影;只保留描边反馈,减少悬停时的合成/raster 成本。 */
|
||||
transition: border-color var(--iwb-motion-hover, .15s) var(--iwb-ease-hover, ease-out);
|
||||
}
|
||||
/* v1.7.3:卡片悬停上浮 + 阴影 + 品牌描边(与输出节点共用宿主 L2 token)。
|
||||
用 item:hover 而不是 img:hover:指针移到下载浮层按钮上时卡片仍保持浮起,不抖。 */
|
||||
.iwb-history-embedded .iwb-history-item:hover img {
|
||||
border-color: var(--iwb-hover-border, var(--iwb-brand));
|
||||
}
|
||||
/* v1.9.4:卡片按宽高比占位后,占位层要铺满卡片 —— 否则缩略图出现时仍会有一次高度跳变(滚动时表现为闪动) */
|
||||
.iwb-history-embedded .iwb-history-item .iwb-history-missing { position: absolute; inset: 0; min-height: 0; }
|
||||
.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; }
|
||||
/* v1.7.3:把「下载」做成卡片底部渐变的下载浮层(与输出节点同一套语义)。
|
||||
条本身 pointer-events:none,只有悬停后按钮可点,避免挡住卡片点击/双击预览。 */
|
||||
.iwb-history-actions {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; display: flex; justify-content: center; gap: 4px;
|
||||
padding: var(--iwb-space-16) var(--iwb-space-4) var(--iwb-space-4); border-radius: 0 0 6px 6px;
|
||||
background-image: linear-gradient(to top, rgba(0, 0, 0, .62), transparent);
|
||||
opacity: 0; transition: opacity var(--iwb-motion-hover, .15s) var(--iwb-ease-hover, ease-out);
|
||||
pointer-events: none;
|
||||
}
|
||||
.iwb-history-embedded .iwb-history-item:hover .iwb-history-actions,
|
||||
.iwb-history-embedded .iwb-history-item:focus-within .iwb-history-actions { opacity: 1; pointer-events: auto; }
|
||||
.iwb-history-actions .iwb-btn-sm { padding: 2px 8px; font-size: 11px; border: none; background: var(--iwb-panel); color: var(--iwb-text); }
|
||||
.iwb-history-actions .iwb-btn-sm:hover { background: var(--iwb-panel); color: var(--iwb-brand); }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.iwb-history-embedded .iwb-history-item img { transition: none; }
|
||||
.iwb-history-embedded .iwb-history-item:hover img { transform: none; }
|
||||
}
|
||||
.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; }
|
||||
@@ -88,3 +112,15 @@
|
||||
}
|
||||
.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; }
|
||||
/* ---- v1.7.4:原图未落盘(仅缩略图)可见化 ---- */
|
||||
.iwb-gal-orig {
|
||||
font-size: 11px; color: var(--iwb-warn); cursor: pointer; white-space: nowrap;
|
||||
text-decoration: underline dotted; text-underline-offset: 2px; flex: 0 1 auto; overflow: hidden; text-overflow: ellipsis;
|
||||
}
|
||||
.iwb-gal-orig:hover { color: var(--iwb-warn); opacity: .85; }
|
||||
.iwb-gal-origbadge {
|
||||
position: absolute; left: var(--iwb-space-4, 4px); top: var(--iwb-space-4, 4px);
|
||||
padding: 0 var(--iwb-space-4, 4px); border-radius: var(--iwb-radius-full, 999px);
|
||||
background: var(--iwb-panel); color: var(--iwb-warn); border: 1px solid var(--iwb-border);
|
||||
font-size: var(--iwb-font-2xs, 10px); line-height: 1.5; pointer-events: none;
|
||||
}
|
||||
@@ -62,7 +62,7 @@ const version = await page.evaluate(() => {
|
||||
window.__panel.mount(document.getElementById('host'))
|
||||
return window.__reg.meta.version
|
||||
})
|
||||
ok('插件版本 = 1.7.1', version === '1.7.1', version)
|
||||
ok('插件版本 = 1.7.2', version === '1.7.2', version)
|
||||
await page.waitForTimeout(700)
|
||||
|
||||
const geo = await page.evaluate(() => {
|
||||
@@ -84,10 +84,15 @@ const geo = await page.evaluate(() => {
|
||||
footH: cs(foot).height,
|
||||
count: document.querySelector('.iwb-gal-count').textContent,
|
||||
folderVisible: btns[1] && cs(btns[1]).display !== 'none',
|
||||
cardActions: Array.from(document.querySelectorAll('.iwb-history-actions')).map((a) =>
|
||||
Array.from(a.querySelectorAll('button')).map((b) => b.textContent.trim())),
|
||||
toolbarLabels: Array.from(document.querySelectorAll('.iwb-gal-actions button')).map((b) => b.textContent.trim()),
|
||||
}
|
||||
})
|
||||
console.log('几何 / 计算样式 =', JSON.stringify(geo))
|
||||
ok('三个图标都在(刷新 / 打开本地目录 / 设置)', geo.buttons === 3 && geo.folderVisible, geo.labels)
|
||||
ok('每张图卡片只剩「下载」', geo.cardActions.length > 0 && geo.cardActions.every((a) => a.join(',') === '下载'), geo.cardActions.slice(0, 3))
|
||||
ok('顶部工具栏仍保留「插入」', geo.toolbarLabels.indexOf('插入') >= 0, geo.toolbarLabels)
|
||||
ok('计数文字仍是 17 / 17 张(没动左侧信息区)', geo.count === '17 / 17 张', geo.count)
|
||||
ok('命中区真的 28×28(不是只改了源码字符串)',
|
||||
geo.btnW.every((w) => w === '28px') && geo.btnH.every((h) => h === '28px'), [geo.btnW, geo.btnH])
|
||||
|
||||
@@ -20,8 +20,8 @@ const ok = (name, cond, actual) => {
|
||||
}
|
||||
|
||||
// ---- 版本两处一致 ----
|
||||
ok('package.json version = 1.7.1', pkg.version === '1.7.1', pkg.version)
|
||||
ok('manifest.version = 1.7.1', /version:\s*'1\.7\.1'/.test(src))
|
||||
ok('package.json version = 1.7.2', pkg.version === '1.7.2', pkg.version)
|
||||
ok('manifest.version = 1.7.2', /version:\s*'1\.7\.2'/.test(src))
|
||||
|
||||
// ---- 图标尺寸:宿主 design-tokens.md §3.8 闭集 14/16/18,取最大档 ----
|
||||
ok('SVG 尺寸常量 ICON_PX = 18', /\bvar ICON_PX = 18\b/.test(src))
|
||||
@@ -60,6 +60,12 @@ ok('左侧计数 / 选中 / 状态文字字号没被顺手改掉',
|
||||
/\.iwb-gal-count\s*\{[^}]*font-size:\s*11px/.test(css) &&
|
||||
/\.iwb-gal-sel\s*\{[^}]*font-size:\s*11px/.test(css))
|
||||
|
||||
// ---- v1.7.2:图片卡片只留下载;顶部/右键插入入口不回退 ----
|
||||
ok('图片卡片上没有「插入」按钮', !/acts\.appendChild\(act\('插入'/.test(src))
|
||||
ok('图片卡片保留「下载」按钮', /acts\.appendChild\(act\('下载'/.test(src))
|
||||
ok('顶部工具栏「插入」仍在', /actions\.appendChild\(btn\('插入'/.test(src))
|
||||
ok('右键菜单「插入画布」仍在', /item\('插入画布'/.test(src))
|
||||
|
||||
// ---- 尺寸闭集(对齐宿主 plugin-scale-contract,防止放大时又引入散值)----
|
||||
const FONT = new Set([11, 12, 13, 14, 15, 17, 20, 24])
|
||||
const RADIUS = new Set([6, 8, 10, 12, 14, 999])
|
||||
@@ -78,5 +84,5 @@ for (const m of css.matchAll(/([a-z-]+)\s*:\s*([^;{}]+)/g)) {
|
||||
}
|
||||
ok('CSS 字号 / 圆角 / 间距无新增散值', stray.length === 0, stray)
|
||||
|
||||
console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过(gallery 1.7.1 底栏图标)')
|
||||
console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过(gallery 1.7.2 卡片只留下载)')
|
||||
if (failed) process.exitCode = 1
|
||||
@@ -0,0 +1,42 @@
|
||||
# image-annotate 插件避坑事项
|
||||
|
||||
> 维护:每次改“导出/覆盖保存”后读本文件,并跑 `node tools/harness.mjs`。
|
||||
> 版本:1.20.8(2026-11-26)
|
||||
|
||||
## 1. 覆盖保存必须等落盘
|
||||
|
||||
- `ctx.canvas.setNodeImage(id, dataUrl)` 旧实现只改内存就返回 true;真正的保存是异步防抖,失败时插件不知道。
|
||||
- 正确顺序:
|
||||
1. 优先调用 `ctx.canvas.saveNodeImage(id, dataUrl)`(宿主新增,返回 `{ok,error}`);
|
||||
2. 等它 resolve;
|
||||
3. `ok === false` 时把 `error` 抛给编辑器,overlay 保持打开,让用户重试;
|
||||
4. 旧宿主没有 `saveNodeImage` 才退回 `setNodeImage`(并接受旧行为)。
|
||||
- 宿主侧事务:保留旧 data → 提交新图 → `saveNow` → 读盘校验目标节点**数据相对旧值发生变化** → 失败回滚。只检查“有 data”会误判成功(磁盘上仍是旧图)。
|
||||
|
||||
## 2. 桌面端不要生成 `__cache` 引用
|
||||
|
||||
- 桌面端没有 Service Worker,`iwbCacheWrite` 恒返回 null;
|
||||
- 保存路径若把大 dataURL 换成 `{__cache}`,重载后永远读不到字节,表现就是“覆盖后图丢了”。
|
||||
- 宿主 `stripBigValueSync` 已在桌面端保留原值;插件不要自己造 cache 引用。
|
||||
|
||||
## 3. dataURL 约定
|
||||
|
||||
- `ctx.canvas.getNodeImage` 返回的 `dataUrl` 才能编辑;远程 URL 不支持标注(提示先转存本地)。
|
||||
- 导出到节点必须是 `data:`;Blob 要转 dataURL 再调 `saveNodeImage`。
|
||||
- 大图(几千像素)会让保存变慢/占空间,但**不能为了省空间丢图**;失败要可见。
|
||||
|
||||
## 4. 空改动
|
||||
|
||||
- 新旧图字节完全相同时,宿主直接返回成功,不做落盘/回滚;插件不应把它当失败。
|
||||
|
||||
## 5. 发版
|
||||
|
||||
- `package.json` 与入口 `version` 同步;改完先 `node tools/harness.mjs`,再 `sync-plugins-from-repo` 生成新 hash 并上市场;
|
||||
- 本文件不打包。
|
||||
|
||||
## 6. 最小回归清单
|
||||
|
||||
- [ ] 覆盖保存成功 → 关闭编辑器 → 刷新后图还在
|
||||
- [ ] 模拟保存失败 → 图回滚旧值 + 编辑器显示具体错误
|
||||
- [ ] 不修改直接保存 → 成功、不报错
|
||||
- [ ] 远程图节点 → 提示“先转存本地”,不崩溃
|
||||
@@ -19,7 +19,7 @@
|
||||
持有几十 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/harness.mjs` 的 CSP 段。
|
||||
|
||||
### v1.1:选区、便利版 UI、单张输出
|
||||
|
||||
@@ -66,8 +66,7 @@
|
||||
- **侧栏去重**:移除硬度/透明两条滑杆(与就地选项栏画笔/橡皮态完全重复);
|
||||
侧栏保留调色板全量 + 笔刷大小(滑杆/数字/快捷点)+ 缩放行。
|
||||
|
||||
- 测试:`node image-annotate/tools/harness.mjs`(合成宿主,发布前,79 项);
|
||||
`node image-annotate/tools/e2e-site.mjs`(桌面客户端 CSP/SRI,发布后)。
|
||||
- 测试:`node image-annotate/tools/harness.mjs`(合成宿主 + 真实 Chromium,覆盖 CSP / 图层排序 / 输出几何,发布前必跑)。
|
||||
|
||||
## v1.2.2
|
||||
|
||||
@@ -1216,11 +1215,12 @@ node scripts/gen-market.js # 生成 market/index.json
|
||||
发布后回读市场索引确认版本与哈希已更新,再在客户端市场安装验证——不能只看命令退出码。
|
||||
|
||||
## 验证(可选,开发用)
|
||||
`tools/e2e-site.mjs`:**桌面客户端**端到端(市场安装 + SRI + 漂浮菜单 → 编辑器 → 覆盖/新建),
|
||||
另含 v1.0.5 的图层顺序回归:画图形 + 粘贴截图 → 唯一高亮、点重叠区选中最上层截图、四个排序按钮逐一生效、原图始终在最底。
|
||||
`tools/harness.mjs`:合成宿主 + 真实 Chromium,覆盖 CSP 适配、图层顺序回归(画图形 + 粘贴截图 → 唯一高亮、
|
||||
点重叠区选中最上层截图、四个排序按钮逐一生效、原图始终在最底)、输出几何与编辑器命令。
|
||||
需要 Playwright(可从桌面仓 `node_modules` 或全局解析),**不进 CI**(本仓 CI 只跑 `npm run validate`,不联网、无依赖)。
|
||||
|
||||
```bash
|
||||
node image-annotate/tools/e2e-site.mjs
|
||||
node image-annotate/tools/harness.mjs
|
||||
```
|
||||
> 为什么值得留着:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在 mock 下永远绿,只有真机能抓出来。
|
||||
> 为什么必须是真 Chromium:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在纯 mock 下永远绿,
|
||||
> harness 里的合成宿主带 CSP 闸门才能抓出来。
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/image-annotate",
|
||||
"private": true,
|
||||
"version": "1.20.7",
|
||||
"version": "1.20.9",
|
||||
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
|
||||
"ibwPlugin": {
|
||||
"id": "image-annotate",
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
id: 'image-annotate',
|
||||
name: '标注 / 修图',
|
||||
version: '1.20.7',
|
||||
version: '1.20.9',
|
||||
apiVersion: 1,
|
||||
skin: 'private',
|
||||
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
|
||||
@@ -9214,7 +9214,8 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
if (!editor || typeof editor.open !== "function") {
|
||||
return Promise.reject(new Error("标注编辑器未加载"));
|
||||
}
|
||||
return Promise.resolve(ctx.canvas.getNodeImage(id)).then(function(image) {
|
||||
// v: 编辑器入口封顶 4096 长边(原生缩),避免 8K 原图整幅进 canvas
|
||||
return Promise.resolve(ctx.canvas.getNodeImage(id, { max: 4096 })).then(function(image) {
|
||||
if (!image || !image.dataUrl) {
|
||||
throw new Error(image && image.url ? "该节点是远程图片,暂不支持标注(请先转存为本地位图)" : "该节点没有可编辑的图片");
|
||||
}
|
||||
@@ -9248,10 +9249,20 @@ var __IWB_ANNOTATE_MANIFEST__ = {
|
||||
handedOff = true;
|
||||
imageToDataUrl(out).then(function(dataUrl) {
|
||||
const replaced = mode === "replace";
|
||||
const ok = replaced ? ctx.canvas.setNodeImage(id, dataUrl) : Boolean(ctx.canvas.createImageNode({ dataUrl, name: baseName(node) + "_edit.png" }));
|
||||
if (!ok) throw new Error(replaced ? "写回原节点失败" : "新建节点失败");
|
||||
settle(function() {
|
||||
resolve(mode);
|
||||
if (!replaced) {
|
||||
const newId = ctx.canvas.createImageNode({ dataUrl, name: baseName(node) + "_edit.png" });
|
||||
if (!newId) throw new Error("新建节点失败");
|
||||
settle(function() { resolve(mode); });
|
||||
return;
|
||||
}
|
||||
// v3.26.97:优先用可等待的 saveNodeImage —— 它落盘成功才返回 ok;
|
||||
// 失败会回滚旧图并带回原因,不再出现「提示写入失败但节点已被改掉」。
|
||||
const job = (ctx.canvas && typeof ctx.canvas.saveNodeImage === "function")
|
||||
? ctx.canvas.saveNodeImage(id, dataUrl)
|
||||
: Promise.resolve(ctx.canvas.setNodeImage(id, dataUrl) ? { ok: true } : { ok: false, error: "写回原节点失败" });
|
||||
return Promise.resolve(job).then(function(r) {
|
||||
if (!r || r.ok === false) throw new Error((r && r.error) || "写回原节点失败");
|
||||
settle(function() { resolve(mode); });
|
||||
});
|
||||
}).catch(function(error) {
|
||||
settle(function() {
|
||||
|
||||
@@ -1,437 +0,0 @@
|
||||
// 真实站点端到端(开发用,不进 CI)。
|
||||
//
|
||||
// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被
|
||||
// `connect-src 'self' https: …` 拦掉)在 mock 下永远绿,只有带 CSP 的真站能抓出来。
|
||||
// 它不 mock /plugins/*:走真实 KV + 浏览器 SRI 校验 + 真实画布桥。
|
||||
//
|
||||
// 运行:
|
||||
// node image-annotate/tools/e2e-site.mjs
|
||||
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-annotate/tools/e2e-site.mjs
|
||||
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
|
||||
import { createRequire } from 'node:module'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/image-annotate/tools
|
||||
const REPO = path.resolve(HERE, '../..') // <repo>
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
|
||||
let chromium = null
|
||||
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
|
||||
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
|
||||
}
|
||||
if (!chromium) {
|
||||
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
|
||||
console.error(' npm i -D playwright # 本仓或宿主仓皆可')
|
||||
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node image-annotate/tools/e2e-site.mjs')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
|
||||
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-annotate/package.json'), 'utf8')).version
|
||||
const CFG = { providers: [], canvas: {} }
|
||||
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
|
||||
|
||||
let failed = 0
|
||||
const check = (name, ok, detail) => {
|
||||
if (!ok) failed++
|
||||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||||
}
|
||||
const poll = async (fn, timeout = 25000, step = 250) => {
|
||||
const end = Date.now() + timeout
|
||||
for (;;) {
|
||||
let v
|
||||
try { v = await fn() } catch { v = false }
|
||||
if (v) return v
|
||||
if (Date.now() > end) return false
|
||||
await new Promise((r) => setTimeout(r, step))
|
||||
}
|
||||
}
|
||||
|
||||
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
|
||||
const browser = await chromium.launch()
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } })
|
||||
const consoleErrors = []
|
||||
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
|
||||
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message + ' @ ' + String(e.stack || '').split('\n').slice(1, 4).join(' | ')))
|
||||
page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
|
||||
|
||||
// 造一张真实的 96x64 PNG 作为节点图片
|
||||
await page.goto('about:blank')
|
||||
const PNG = await page.evaluate(() => {
|
||||
const c = document.createElement('canvas')
|
||||
c.width = 96; c.height = 64
|
||||
const x = c.getContext('2d')
|
||||
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 96, 64)
|
||||
x.fillStyle = '#ffffff'; x.fillRect(20, 12, 56, 40)
|
||||
return c.toDataURL('image/png')
|
||||
})
|
||||
|
||||
await page.addInitScript((d) => {
|
||||
localStorage.clear()
|
||||
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
|
||||
const ws = JSON.parse(JSON.stringify(d.ws))
|
||||
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
|
||||
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
|
||||
localStorage.setItem('iwb_ws_active', ws.activeId)
|
||||
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
|
||||
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
|
||||
localStorage.setItem('iwb_plugins', JSON.stringify({ 'image-annotate': { enabled: true, settings: {}, data: {} } }))
|
||||
}, { cfg: CFG, ws: WS, png: PNG })
|
||||
|
||||
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
|
||||
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
|
||||
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
|
||||
|
||||
// ---------- 1) 真实 KV 加载 + SRI + 启用 ----------
|
||||
const active = await poll(async () => page.evaluate(() => {
|
||||
const p = window.IWBPluginHost.list().find((x) => x.id === 'image-annotate')
|
||||
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
|
||||
}))
|
||||
check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active))
|
||||
check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
|
||||
|
||||
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
|
||||
// 文件名两种都合法:plugins-publish.mjs 产内容寻址名(.<hash12>.js,可 immutable 缓存),
|
||||
// plugins-publish.sh(带主干守卫的合规通道)产固定名(plugin-image-annotate.js,走 no-cache+ETag)。
|
||||
// 断言的关键是「必须带 integrity」,与命名策略无关。
|
||||
check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /^\/plugins\/plugin-image-annotate(\.[a-f0-9]{12})?\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
|
||||
|
||||
// ---------- 2) 打开工作区 + 节点存在 ----------
|
||||
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
|
||||
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
|
||||
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
|
||||
|
||||
// ---------- 3) 入口:节点漂浮菜单(回落右键插件命令)----------
|
||||
const openEditor = async () => {
|
||||
await page.locator('.iwb-node[data-node-id="r1"]').click()
|
||||
const btn = page.locator('.iwb-node-floatbar button[title="标注 / 修图"]')
|
||||
if (await btn.count()) { await btn.click(); return '漂浮菜单' }
|
||||
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
|
||||
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '标注 / 修图:选中节点' }).click()
|
||||
return '右键命令'
|
||||
}
|
||||
const entry = await openEditor()
|
||||
check('节点入口可触发(漂浮菜单或右键命令)', true, entry)
|
||||
|
||||
// ---------- 4) 编辑器打开(真实 CSP 下注入样式)----------
|
||||
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
|
||||
const opened = await page.evaluate(() => {
|
||||
const el = document.querySelector('#iwb-editor-overlay')
|
||||
const style = document.getElementById('iwb-annotate-style')
|
||||
return {
|
||||
display: getComputedStyle(el).display,
|
||||
position: getComputedStyle(el).position,
|
||||
zIndex: getComputedStyle(el).zIndex,
|
||||
bg: getComputedStyle(el).backgroundColor,
|
||||
styleInjected: Boolean(style && style.textContent.includes('.iwb-editor-')),
|
||||
}
|
||||
})
|
||||
check('编辑器浮层可见', opened.display === 'flex' && opened.position === 'fixed')
|
||||
check('样式注入生效(CSP unsafe-inline)', opened.styleInjected)
|
||||
check('浮层压住宿主 UI', Number(opened.zIndex) >= 999998, 'z=' + opened.zIndex + ' bg=' + opened.bg)
|
||||
|
||||
// ---------- 4.5) 剪贴板粘贴:⌘V 把剪贴板图片贴为新图层 ----------
|
||||
// 合成 ClipboardEvent(带 image/png File),粘贴应进入「图片放置」模式;回车确认后图层面板 +1 项。
|
||||
// SKIP_PASTE=1 可跳过(隔离「粘贴」与「覆盖写回」两条链路的排查用)。
|
||||
const SKIP_PASTE = process.env.SKIP_PASTE === '1'
|
||||
if (!SKIP_PASTE) {
|
||||
// 先画一个矢量矩形,制造「截图 + 图形」共存场景 —— 这是 z 撞车 / 排序按钮失效的复现前提
|
||||
const imgBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
|
||||
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
|
||||
await page.mouse.move(imgBox.x + imgBox.width * 0.25, imgBox.y + imgBox.height * 0.25)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(imgBox.x + imgBox.width * 0.75, imgBox.y + imgBox.height * 0.75, { steps: 8 })
|
||||
await page.mouse.up()
|
||||
await page.waitForTimeout(200)
|
||||
const layersBefore = await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length)
|
||||
await page.evaluate((png) => {
|
||||
const bin = atob(png.split(',')[1])
|
||||
const bytes = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
||||
const dt = new DataTransfer()
|
||||
dt.items.add(new File([bytes], 'paste.png', { type: 'image/png' }))
|
||||
document.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }))
|
||||
}, PNG)
|
||||
await page.waitForTimeout(800) // FileReader → loadImage → 进入放置模式
|
||||
await page.keyboard.press('Enter') // 确认放置 → 落层
|
||||
const pasted = await poll(async () => page.evaluate((n) => document.querySelectorAll('.iwb-editor-layer-list > *').length > n, layersBefore))
|
||||
check('⌘V 粘贴剪贴板图片 → 确认后图层面板 +1', Boolean(pasted), '图层项 ' + layersBefore + ' → ' + await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length))
|
||||
|
||||
// ---------- 4.6) 图层顺序回归(2026-11-04 修):z 唯一 / 选中唯一 / 四个排序按钮 ----------
|
||||
const panelSeq = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-editor-layer-list .iwb-layer-item'))
|
||||
.map((n) => n.querySelector('.iwb-layer-name')?.textContent).join(' > '))
|
||||
const activeCount = () => page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list .iwb-layer-item.active').length)
|
||||
check('图层面板只有一个选中项(画笔目标改用 ✎ 标记)', (await activeCount()) === 1,
|
||||
'active=' + await activeCount() + ' / ' + await panelSeq())
|
||||
|
||||
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
|
||||
await page.mouse.click(imgBox.x + imgBox.width * 0.5, imgBox.y + imgBox.height * 0.5)
|
||||
await page.waitForTimeout(150)
|
||||
const activeItem = await page.evaluate(() => {
|
||||
const n = document.querySelector('.iwb-editor-layer-list .iwb-layer-item.active')
|
||||
return n && { type: n.dataset.layerType, name: n.querySelector('.iwb-layer-name')?.textContent }
|
||||
})
|
||||
check('点击「截图+图形」重叠区选中最上层截图(不被下方图形抢走)',
|
||||
Boolean(activeItem && activeItem.type === 'bitmap' && /图层/.test(activeItem.name)), JSON.stringify(activeItem))
|
||||
|
||||
// v1.13 起顶栏四个层级按钮已删除(改为图层拖动 + Ctrl+]/[ 快捷键),
|
||||
// 这里改为断言「按钮确实没了」+ 用快捷键验证排序仍然可用。
|
||||
check('顶栏不再有层级排序按钮(改用图层拖动 + Ctrl+]/[)',
|
||||
(await page.locator('.iwb-editor-layer-btn').count()) === 0 &&
|
||||
(await page.locator('.iwb-editor-header .iwb-editor-commands').count()) === 0,
|
||||
'layerBtn=' + await page.locator('.iwb-editor-layer-btn').count())
|
||||
|
||||
// v1.18(用户 2026-11-10):撤销 / 重做 / 还原 从顶栏搬到工具条最右,
|
||||
// 「适应窗口 / 收起侧栏」退到它前面两位。这里断言「末尾是撤销组、视图按钮在其前」
|
||||
// —— 光看版本号挡不住产物没重建。
|
||||
const toolsOrder = await page.evaluate(() => {
|
||||
const kids = Array.from(document.querySelectorAll('.iwb-editor-tools > *'))
|
||||
const acts = kids.filter((n) => n.dataset && n.dataset.action).map((n) => n.dataset.action)
|
||||
const hist = kids[kids.length - 1]
|
||||
return {
|
||||
tail: acts.slice(-2),
|
||||
lastIsHistory: Boolean(hist && hist.classList.contains('iwb-editor-history')),
|
||||
histActs: [...(hist ? hist.querySelectorAll('[data-action]') : [])].map((b) => b.dataset.action),
|
||||
headerHasHistory: Boolean(document.querySelector('.iwb-editor-header .iwb-editor-history')),
|
||||
}
|
||||
})
|
||||
check('工具栏最右是「撤销/重做/还原」组(视图按钮在其前)',
|
||||
JSON.stringify(toolsOrder.tail) === JSON.stringify(['zoomFit', 'togglePanels']) &&
|
||||
toolsOrder.lastIsHistory && toolsOrder.histActs.join(',') === 'undo,redo,reset' &&
|
||||
!toolsOrder.headerHasHistory, JSON.stringify(toolsOrder))
|
||||
|
||||
const before = await panelSeq()
|
||||
const activeName = await page.evaluate(() => document.querySelector('.iwb-editor-layer-list .iwb-layer-item.active .iwb-layer-name')?.textContent)
|
||||
await page.keyboard.press('Control+[') // 下移一层
|
||||
const afterDown = await panelSeq()
|
||||
check('Ctrl+[ 下移一层改变图层顺序', before !== afterDown, before + ' → ' + afterDown)
|
||||
await page.keyboard.press('Control+]') // 上移一层
|
||||
check('Ctrl+] 上移一层恢复原顺序', (await panelSeq()) === before, await panelSeq())
|
||||
|
||||
await page.keyboard.press('Control+Shift+[') // 置底
|
||||
const afterBottom = await panelSeq()
|
||||
check('Ctrl+Shift+[ 置底生效(元素不会消失)',
|
||||
afterBottom !== before && afterBottom.endsWith(String(activeName)), afterBottom)
|
||||
check('置底后原图不再被钉在最底 —— 图层可以压到原图下面(v1.13 解封)',
|
||||
!afterBottom.endsWith('原图'), afterBottom)
|
||||
await page.keyboard.press('Control+Shift+]') // 置顶
|
||||
check('Ctrl+Shift+] 置顶生效', (await panelSeq()) !== afterBottom, await panelSeq())
|
||||
check('排序后仍只有一个选中项', (await activeCount()) === 1, 'active=' + await activeCount())
|
||||
|
||||
// v1.15 图片调节:真站确认面板存在、11 项按参数表生成(DOM 由 adjust.js 生成,
|
||||
// 构建时漏带就会是 0 行 —— 这类「打包产物缺模块」只有真站能发现)
|
||||
const adjRowCount = await page.locator('.iwb-editor-adj-row').count()
|
||||
const adjNames = await page.locator('.iwb-editor-adj-name').allTextContents()
|
||||
check('右侧栏「图片调节」11 项齐全',
|
||||
adjRowCount === 11 && adjNames.join('/') === '曝光/明度/对比度/阴影/高光/色相/饱和度/温度/色调/锐度/清晰度',
|
||||
'rows=' + adjRowCount + ' ' + adjNames.join('/'))
|
||||
check('调节面板认到了作用层(不是「无图层」)',
|
||||
(await page.locator('.iwb-editor-adj-target').textContent()) !== '无图层',
|
||||
await page.locator('.iwb-editor-adj-target').textContent())
|
||||
|
||||
// v1.19:右栏常驻调色面板已删(用户 2026-11-10),颜色只剩工具栏弹层一处。
|
||||
// 真站里 DOM 与 CSS 分别打包,这里同时验「右栏干净」和「弹层头部一行 / 16 色 8 列」——
|
||||
// 样式漏打包时,头部会退回竖排或色块掉成 6 列,这条会直接露出来。
|
||||
const sideColor = await page.evaluate(() => ({
|
||||
hasSide: Boolean(document.querySelector('.iwb-editor-left [data-color-surface]')),
|
||||
firstSection: (document.querySelector('.iwb-editor-left > section') || {}).className || '',
|
||||
}))
|
||||
check('右栏调色模块已删(第一个模块是图片调节)',
|
||||
sideColor.hasSide === false && /iwb-editor-adj/.test(sideColor.firstSection),
|
||||
JSON.stringify(sideColor))
|
||||
|
||||
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(240)
|
||||
const popShape = await page.evaluate(() => {
|
||||
const pop = document.querySelector('.iwb-editor-color-pop')
|
||||
if (!pop) return null
|
||||
const r = (el) => el.getBoundingClientRect()
|
||||
const head = r(pop.querySelector('.iwb-color-pop-head'))
|
||||
const items = [pop.querySelector('[data-action="palettePick"]'),
|
||||
pop.querySelector('.iwb-editor-color-hex-input'),
|
||||
pop.querySelector('[data-action="pinColorPop"]')].map((el) => {
|
||||
const b = r(el)
|
||||
return { c: b.top + b.height / 2, l: b.left, r: b.right }
|
||||
})
|
||||
const sw = [...pop.querySelectorAll('.iwb-editor-color-swatches [data-panel-color]')]
|
||||
const grid = pop.querySelector('.iwb-editor-color-swatches')
|
||||
return {
|
||||
w: Math.round(r(pop).width),
|
||||
sameRow: items.every((it) =>
|
||||
Math.abs(it.c - (head.top + head.height / 2)) < 3 && it.l >= head.left - 1 && it.r <= head.right + 1),
|
||||
common: sw.length,
|
||||
cols: new Set(sw.map((b) => Math.round(r(b).left))).size,
|
||||
swatch: sw.length ? Math.round(r(sw[0]).width) : 0,
|
||||
// v1.20:去色占常用色第一格(20px 同尺寸、第一排最左)
|
||||
noneFirst: grid.children[0] === pop.querySelector('[data-color-none]'),
|
||||
cells: grid.children.length,
|
||||
}
|
||||
})
|
||||
check('色板弹层:头部一行(吸管 / 色值 / 图钉同排)+ 去色占常用色第一格 + 15 色 8 列',
|
||||
Boolean(popShape) && popShape.sameRow && popShape.noneFirst && popShape.cells === 16 &&
|
||||
popShape.common === 15 && popShape.cols === 8 && popShape.swatch === 20 && popShape.w === 440,
|
||||
JSON.stringify(popShape))
|
||||
await page.keyboard.press('Escape')
|
||||
await page.waitForTimeout(140)
|
||||
|
||||
const sideBefore = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width))
|
||||
const sideGrip = await page.locator('.iwb-editor-side-resizer').boundingBox()
|
||||
if (sideGrip) {
|
||||
await page.mouse.move(sideGrip.x + 3, sideGrip.y + 120)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(sideGrip.x + 3 - 70, sideGrip.y + 120, { steps: 6 })
|
||||
await page.mouse.up()
|
||||
await page.waitForTimeout(180)
|
||||
}
|
||||
const sideAfter = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width))
|
||||
check('右栏可以拖宽(不再固定 220)', sideAfter >= sideBefore + 60, sideBefore + ' → ' + sideAfter)
|
||||
await page.locator('.iwb-editor-side-resizer').dblclick()
|
||||
await page.waitForTimeout(150)
|
||||
|
||||
// v1.17:描边可以是「无色」。真站要验的是按钮真的出现在描边槽、点完对象上真的关了,
|
||||
// 而不只是 CSS 里多了个类 —— 形状消失与否只有跑起来才知道。
|
||||
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
|
||||
await page.mouse.move(imgBox.x + imgBox.width * 0.12, imgBox.y + imgBox.height * 0.12)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(imgBox.x + imgBox.width * 0.30, imgBox.y + imgBox.height * 0.30, { steps: 6 })
|
||||
await page.mouse.up()
|
||||
await page.waitForTimeout(250)
|
||||
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
|
||||
await page.mouse.click(imgBox.x + imgBox.width * 0.21, imgBox.y + imgBox.height * 0.21)
|
||||
await page.waitForTimeout(200)
|
||||
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
|
||||
await page.waitForTimeout(250)
|
||||
const noneOnStroke = await page.evaluate(() => {
|
||||
const n = document.querySelector('.iwb-editor-color-pop [data-color-none]')
|
||||
// v1.20:去色不再 hidden,改用 disabled 表达「这个上下文不能去色」
|
||||
return Boolean(n) && Boolean(n.offsetParent) && !n.disabled
|
||||
})
|
||||
await page.evaluate(() => document.querySelector('.iwb-editor-color-pop [data-color-none]').click())
|
||||
await page.waitForTimeout(300)
|
||||
const noStrokeState = await page.evaluate(() => {
|
||||
const d = window.__iwbEditor.__debug()
|
||||
const s = d.shapes.find((x) => x.id === d.selectedShapeId)
|
||||
return s ? { strokeOn: s.strokeOn, fill: s.fill } : null
|
||||
})
|
||||
check('真站:描边能置「无」(去掉描边顺手切实心,对象不会消失)',
|
||||
noneOnStroke && Boolean(noStrokeState) && noStrokeState.strokeOn === false && noStrokeState.fill === true,
|
||||
JSON.stringify({ noneOnStroke, noStrokeState }))
|
||||
await page.keyboard.press('Escape')
|
||||
await page.waitForTimeout(120)
|
||||
|
||||
// v1.14 字体选择:真站是带 CSP 的环境,这里确认下拉可用、字体切换真的落到了对象上。
|
||||
// 系统字体不受 CSP 约束(CSP 管的是网络字体),所以只要 canvas 能画就没问题。
|
||||
const famDbg = () => page.evaluate(() => window.__iwbEditor.__debug())
|
||||
const FAM_SEL = '.iwb-editor-optionbar-body select[data-opt-text="fontFamily"]'
|
||||
await page.locator('.iwb-editor-tool[data-tool="text"]').click()
|
||||
const famBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
|
||||
await page.mouse.click(famBox.x + 60, famBox.y + 60)
|
||||
await page.waitForTimeout(300)
|
||||
await page.evaluate(() => {
|
||||
const el = document.querySelector('.iwb-editor-text-input')
|
||||
if (!el) return
|
||||
el.focus()
|
||||
el.value = '字体测试'
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }))
|
||||
})
|
||||
await page.keyboard.press('Enter')
|
||||
await page.waitForTimeout(400)
|
||||
|
||||
const famOpts = await page.locator(FAM_SEL + ' option').allTextContents()
|
||||
check('真站选项栏出现字体下拉,四档:黑体 / 宋体 / 楷体 / 圆体',
|
||||
famOpts.length === 4, JSON.stringify(famOpts))
|
||||
|
||||
const wSans = ((await famDbg()).texts.find((t) => t.text === '字体测试') || {}).box
|
||||
await page.selectOption(FAM_SEL, 'serif')
|
||||
await page.waitForTimeout(320)
|
||||
const tSerif = (await famDbg()).texts.find((t) => t.text === '字体测试')
|
||||
check('真站切换宋体生效,且中文宽度不变(全角等宽,版面不跳动)',
|
||||
Boolean(tSerif && tSerif.fontFamily === 'serif' && wSans && Math.abs(tSerif.box.w - wSans.w) <= 1),
|
||||
(wSans ? wSans.w : '?') + ' → ' + (tSerif ? tSerif.box.w : '?'))
|
||||
await page.keyboard.press('Delete')
|
||||
await page.waitForTimeout(200)
|
||||
|
||||
// 复原成画笔工具,避免影响后面「覆盖」链路的画笔取样
|
||||
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
|
||||
}
|
||||
|
||||
// ---------- 4.7) v1.1:选区 / 单层 Delete / 还原原图 / ≤500KB 预设 ----------
|
||||
const dbg = () => page.evaluate(() => window.__iwbEditor.__debug())
|
||||
const v11Box = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
|
||||
await page.locator('.iwb-editor-tool[data-tool="marquee"]').click()
|
||||
await page.mouse.move(v11Box.x + v11Box.width * 0.25, v11Box.y + v11Box.height * 0.25)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(v11Box.x + v11Box.width * 0.7, v11Box.y + v11Box.height * 0.7, { steps: 8 })
|
||||
await page.mouse.up()
|
||||
await page.waitForTimeout(150)
|
||||
const v11sel = (await dbg()).selection
|
||||
check('v1.1 框选 + 浮动操作条出现', Boolean(v11sel && v11sel.w > 5 && v11sel.h > 5) &&
|
||||
await page.locator('.iwb-editor-sel-bar').isVisible(), JSON.stringify(v11sel))
|
||||
const v11px = (x, y) => page.evaluate(({ px, py }) => {
|
||||
const d = window.__iwbEditor.__debug()
|
||||
// 1.2.1 起默认没有 id='draw' 的预建层:填充落进「当前活动层」,
|
||||
// 所以这里读活动层像素而不是写死 'draw'
|
||||
return { base: d.pixel('base', px, py), draw: d.pixel(d.activeLayerId, px, py), activeId: d.activeLayerId }
|
||||
}, { px: x, py: y })
|
||||
const vcX = Math.round(v11sel.x + v11sel.w / 2)
|
||||
const vcY = Math.round(v11sel.y + v11sel.h / 2)
|
||||
const v11before = await v11px(vcX, vcY)
|
||||
await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.fill"]').click()
|
||||
await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.delete"]').click()
|
||||
const v11after = await v11px(vcX, vcY)
|
||||
check('v1.1 Delete 只清当前层(base 像素原样)',
|
||||
v11after.draw[3] === 0 && JSON.stringify(v11after.base) === JSON.stringify(v11before.base),
|
||||
'draw=' + JSON.stringify(v11after.draw) + ' base=' + JSON.stringify(v11after.base))
|
||||
await page.keyboard.press('Control+z')
|
||||
const v11layersBeforeReset = (await dbg()).layers.length
|
||||
await page.locator('[data-action="reset"]').click()
|
||||
check('v1.1 还原原图=只剩原图单层(1.2.1 起不预建画笔层)', (await dbg()).layers.length === 1, JSON.stringify((await dbg()).layers))
|
||||
await page.keyboard.press('Control+z')
|
||||
check('v1.1 还原原图可 Ctrl+Z 撤销', (await dbg()).layers.length === v11layersBeforeReset,
|
||||
'层数 ' + v11layersBeforeReset + ' → 2 → ' + (await dbg()).layers.length)
|
||||
await page.locator('[data-action="toggleExportSettings"]').click()
|
||||
await page.locator('[data-export-key="preset"][data-export-value="ecom800"]').click()
|
||||
check('v1.1 ≤500KB 输出预设可切换', (await dbg()).exportOptions.maxKB === 500,
|
||||
JSON.stringify((await dbg()).exportOptions))
|
||||
await page.locator('[data-export-key="preset"][data-export-value="original"]').click()
|
||||
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
|
||||
|
||||
// ---------- 5) 覆盖:回写真机画布 ----------
|
||||
await page.mouse.move(400, 300)
|
||||
await page.mouse.down()
|
||||
await page.mouse.move(760, 520, { steps: 8 })
|
||||
await page.mouse.up()
|
||||
await page.locator('[data-action="replace"]').click()
|
||||
|
||||
const replaced = await poll(async () => page.evaluate((orig) => {
|
||||
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
|
||||
const n = (ws.nodes || []).find((x) => x.id === 'r1')
|
||||
if (!n) return false
|
||||
const v = n.data && (typeof n.data.data === 'string' ? n.data.data : (n.data.data && (n.data.data.__blob || JSON.stringify(n.data.data))))
|
||||
return (ws.nodes.length === 1 && v && v !== orig) ? { nodes: ws.nodes.length, changed: true } : false
|
||||
}, PNG))
|
||||
check('「覆盖」写回原节点(节点数不变、内容已变)', Boolean(replaced), JSON.stringify(replaced))
|
||||
check('编辑器导出后关闭', (await page.locator('#iwb-editor-overlay').isVisible().catch(() => false)) === false)
|
||||
|
||||
// ---------- 6) 新建:真机画布新增节点 ----------
|
||||
await openEditor()
|
||||
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
|
||||
await page.locator('[data-action="newNode"]').click()
|
||||
const created = await poll(async () => page.evaluate(() => {
|
||||
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
|
||||
return (ws.nodes || []).length === 2 ? { nodes: 2 } : false
|
||||
}))
|
||||
check('「新建」在真机画布新增节点', Boolean(created), JSON.stringify(created))
|
||||
await page.locator('.iwb-canvas').waitFor({ state: 'visible' })
|
||||
check('画布渲染出 2 个节点', (await page.locator('.iwb-node').count()) === 2)
|
||||
|
||||
// ---------- 7) 无 CSP / 运行时错误 ----------
|
||||
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
|
||||
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
|
||||
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
|
||||
|
||||
await browser.close()
|
||||
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
|
||||
process.exit(failed ? 1 : 0)
|
||||
@@ -13,7 +13,7 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||||
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
|
||||
// 版本真源是 package.json(构建时注入 manifest),探针不再硬编码,免得每次发版都要改测试
|
||||
const PKG_VERSION = JSON.parse(readFileSync(path.resolve(HERE, '../package.json'), 'utf8')).version
|
||||
|
||||
@@ -136,8 +136,7 @@ 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,64 项)
|
||||
node image-vectorize/tools/e2e-site.mjs # 桌面客户端端到端(市场安装 / SRI / CSP / 真实画布桥)
|
||||
node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,64 项,含 CSP / 画布桥)
|
||||
|
||||
# 拿真实素材调参数(不进 CI,最快看到效果):
|
||||
node image-vectorize/tools/trace-cli.mjs ~/Desktop/menu.png --mode gray --levels 3
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/image-vectorize",
|
||||
"private": true,
|
||||
"version": "0.6.1",
|
||||
"version": "0.6.2",
|
||||
"description": "位图转矢量:potrace(纯 JS)单色/灰度描摹,输出 SVG 与 PNG 节点;对文字、logo、线稿保形好,不需要 wasm",
|
||||
"ibwPlugin": {
|
||||
"id": "image-vectorize",
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
id: 'image-vectorize',
|
||||
name: '位图转矢量',
|
||||
version: '0.6.1',
|
||||
version: '0.6.2',
|
||||
apiVersion: 1,
|
||||
skin: 'private',
|
||||
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
|
||||
@@ -3691,7 +3691,7 @@ var __IWB_VECTORIZE_MANIFEST__ = {
|
||||
});
|
||||
}
|
||||
async function resolveImage(nodeId) {
|
||||
const image = await ctx.canvas.getNodeImage(nodeId);
|
||||
const image = await ctx.canvas.getNodeImage(nodeId, { max: 2048 }); // v: 预览/矢量化封顶 2048
|
||||
if (!image) throw new Error("该节点没有可描摹的图片");
|
||||
if (image.dataUrl) return image.dataUrl;
|
||||
if (!image.url) throw new Error("该节点没有可描摹的图片");
|
||||
|
||||
@@ -7,7 +7,7 @@ import { createRequire } from 'node:module'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const PLUGIN = path.resolve(HERE, '../plugin')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
|
||||
export function esbuildModule() {
|
||||
|
||||
@@ -1,276 +0,0 @@
|
||||
// 真实站点端到端(开发用,不进 CI)。
|
||||
//
|
||||
// 与 harness 的分工:harness 用合成宿主,能验功能但不能验真实 CSP/网络;这里走真站 ——
|
||||
// 真实的 `_headers`(**不含 wasm-unsafe-eval**)、真实 KV、浏览器 SRI 校验、真实画布桥。
|
||||
// v0.2 是纯 JS potrace,所以这里反而要断言「wasm 仍被 CSP 拦住」——防止有人为了别的功能
|
||||
// 悄悄把 'wasm-unsafe-eval' 加回去。
|
||||
//
|
||||
// 运行:
|
||||
// node image-vectorize/tools/e2e-site.mjs
|
||||
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-vectorize/tools/e2e-site.mjs
|
||||
import { createRequire } from 'node:module'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
|
||||
let chromium = null
|
||||
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
|
||||
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
|
||||
}
|
||||
if (!chromium) {
|
||||
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
|
||||
const PLUGIN_ID = 'image-vectorize'
|
||||
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-vectorize/package.json'), 'utf8')).version
|
||||
const CFG = { providers: [], canvas: {} }
|
||||
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
|
||||
|
||||
let failed = 0
|
||||
const check = (name, ok, detail) => {
|
||||
if (!ok) failed++
|
||||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||||
}
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
||||
const poll = async (fn, timeout = 25000, step = 250) => {
|
||||
const end = Date.now() + timeout
|
||||
for (;;) {
|
||||
let v
|
||||
try { v = await fn() } catch { v = false }
|
||||
if (v) return v
|
||||
if (Date.now() > end) return false
|
||||
await sleep(step)
|
||||
}
|
||||
}
|
||||
|
||||
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
|
||||
const browser = await chromium.launch()
|
||||
// 剪贴板要显式授权(真站是 https,安全上下文成立;本地 file/about:blank 测不到这条)
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } })
|
||||
try {
|
||||
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(BASE).origin })
|
||||
} catch (error) {
|
||||
console.log('(剪贴板授权失败,相关断言会跳过:' + (error && error.message) + ')')
|
||||
}
|
||||
const page = await context.newPage()
|
||||
const consoleErrors = []
|
||||
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
|
||||
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
|
||||
page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
|
||||
|
||||
await page.goto('about:blank')
|
||||
const PNG = await page.evaluate(() => {
|
||||
const c = document.createElement('canvas')
|
||||
c.width = 320; c.height = 320
|
||||
const g = c.getContext('2d')
|
||||
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 320, 320)
|
||||
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(96, 96, 58, 0, Math.PI * 2); g.fill()
|
||||
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(170, 130, 120, 84, 12); g.fill()
|
||||
g.fillStyle = '#111111'; g.font = 'bold 38px "PingFang SC", sans-serif'; g.fillText('菜单', 96, 250)
|
||||
return c.toDataURL('image/png')
|
||||
})
|
||||
|
||||
await page.addInitScript((d) => {
|
||||
localStorage.clear()
|
||||
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
|
||||
const ws = JSON.parse(JSON.stringify(d.ws))
|
||||
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
|
||||
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
|
||||
localStorage.setItem('iwb_ws_active', ws.activeId)
|
||||
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
|
||||
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
|
||||
localStorage.setItem('iwb_plugins', JSON.stringify({ [d.id]: { enabled: true, settings: {}, data: {} } }))
|
||||
}, { cfg: CFG, ws: WS, png: PNG, id: PLUGIN_ID })
|
||||
|
||||
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
|
||||
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
|
||||
|
||||
// ---------- 1) 真实 KV 加载 + SRI ----------
|
||||
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
|
||||
const active = await poll(async () => page.evaluate((id) => {
|
||||
const p = window.IWBPluginHost.list().find((x) => x.id === id)
|
||||
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
|
||||
}, PLUGIN_ID))
|
||||
check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active))
|
||||
check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
|
||||
|
||||
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
|
||||
check('插件脚本用 SRI(sha256) 加载',
|
||||
scripts.some((s) => s.src.indexOf('/plugins/plugin-' + PLUGIN_ID + '.') === 0 && /^sha256-/.test(s.integrity)),
|
||||
JSON.stringify(scripts.map((s) => s.src)))
|
||||
|
||||
// ---------- 2) 宿主 CSP 不再放行 wasm(v0.2 纯 JS,不需要放宽) ----------
|
||||
const cspProbe = await page.evaluate(async () => {
|
||||
try {
|
||||
const b = Uint8Array.from(atob('AGFzbQEAAAA='), (c) => c.charCodeAt(0))
|
||||
await WebAssembly.instantiate(b)
|
||||
return 'ok'
|
||||
} catch (e) { return 'blocked: ' + e.message }
|
||||
})
|
||||
check('宿主 CSP 仍禁止 wasm 编译(本插件是纯 JS,不该再放宽)', cspProbe.indexOf('blocked') === 0, cspProbe.slice(0, 120))
|
||||
|
||||
// ---------- 3) 打开工作区 ----------
|
||||
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
|
||||
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
|
||||
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
|
||||
|
||||
// ---------- 4) 入口 → 模态 ----------
|
||||
await page.locator('.iwb-node[data-node-id="r1"]').click()
|
||||
const floatBtn = page.locator('.iwb-node-floatbar button[title="位图转矢量"]')
|
||||
let entry = ''
|
||||
if (await floatBtn.count()) {
|
||||
await floatBtn.click()
|
||||
entry = '漂浮菜单'
|
||||
} else {
|
||||
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
|
||||
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '位图转矢量' }).first().click()
|
||||
entry = '右键命令'
|
||||
}
|
||||
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 30000 })
|
||||
check('节点入口可触发(' + entry + ')', true)
|
||||
check('样式注入生效(CSP unsafe-inline)', await page.evaluate(() => {
|
||||
const s = document.getElementById('iwb-vectorize-style')
|
||||
return Boolean(s && s.textContent.indexOf('.vz-') >= 0)
|
||||
}))
|
||||
|
||||
// 用户 2026-11-09:取消与保存为节点互换,四颗按钮同一套描边配色(绿色主按钮已去掉)。
|
||||
// 这条同时是「线上真的是新版」的活体证据 —— 光看版本号挡不住产物没重建。
|
||||
check('顶栏顺序 保存为节点→复制→下载→取消,四颗同色', await page.evaluate(() => {
|
||||
const btns = [...document.querySelectorAll('.vz-header .vz-btn')]
|
||||
if (btns.map((b) => b.dataset.act).join(',') !== 'save,copy,svg,cancel') return false
|
||||
const colors = new Set(btns.map((b) => getComputedStyle(b).backgroundColor + '|' + getComputedStyle(b).color))
|
||||
return colors.size === 1
|
||||
}))
|
||||
|
||||
// ---------- 5) 真站 CSP 下引擎能跑 ----------
|
||||
const paths = await poll(async () => {
|
||||
// 统计项是「元素」,合并模式下会带后缀「(N 孤岛合并)」,只取前面的数字
|
||||
const t = await page.locator('[data-stat="elements"]').textContent()
|
||||
const m = /^\s*(\d+)/.exec(t || '')
|
||||
return m && Number(m[1]) > 0 ? m[1] : false
|
||||
}, 30000)
|
||||
check('真站描摹成功(纯 JS 引擎,无 wasm)', Boolean(paths), '元素=' + paths)
|
||||
check('默认按孤岛拆分(元素数 > 层数)', Number(paths) > 3, '元素=' + paths)
|
||||
check('预览为 blob: SVG', await page.evaluate(() => {
|
||||
const v = document.querySelector('[data-stage="vector"]')
|
||||
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
|
||||
}))
|
||||
|
||||
const stats = await page.evaluate(() => ({
|
||||
levels: Number(document.querySelector('[data-stat="levels"]').textContent),
|
||||
bytes: document.querySelector('[data-stat="bytes"]').textContent,
|
||||
ms: document.querySelector('[data-stat="ms"]').textContent,
|
||||
}))
|
||||
check('灰度层数正常(3 层)', stats.levels >= 3, JSON.stringify(stats))
|
||||
|
||||
// ---------- 5.5) 面板形态:高级默认打开 + 精度默认精细 ----------
|
||||
check('高级参数默认展开', await page.evaluate(() => {
|
||||
const box = document.querySelector('[data-adv]')
|
||||
return Boolean(box && !box.hidden)
|
||||
}))
|
||||
check('精度默认「精细」', await page.evaluate(() => {
|
||||
const a = document.querySelector('[data-seg-group="precision"] button.active')
|
||||
return Boolean(a && a.dataset.value === 'fine')
|
||||
}))
|
||||
// v0.3.1:预览白底 + 填充/背景并排(真站 CSP 下 CSS 得真生效,不能只信本地)
|
||||
check('预览区白底、无棋盘格', await page.evaluate(() => {
|
||||
const cs = getComputedStyle(document.querySelector('.vz-preview'))
|
||||
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(cs.backgroundColor)
|
||||
return Boolean(m) && Number(m[1]) > 240 && cs.backgroundImage === 'none'
|
||||
}))
|
||||
check('「填充 / 背景」两个色块并排在同一行', await page.evaluate(() => {
|
||||
const a = document.querySelector('[data-color="color"]')
|
||||
const b = document.querySelector('[data-color="bg"]')
|
||||
if (!a || !b) return false
|
||||
const ra = a.getBoundingClientRect()
|
||||
const rb = b.getBoundingClientRect()
|
||||
return Math.abs(ra.top - rb.top) < 2 && rb.left > ra.right - 1
|
||||
}))
|
||||
|
||||
// v0.4.0:预览缩放 / 平移(真站上鼠标手势得真能走通,不能只信本地合成宿主)
|
||||
const pvBox = await page.locator('.vz-preview').boundingBox()
|
||||
await page.mouse.move(pvBox.x + pvBox.width / 2 + 40, pvBox.y + pvBox.height / 2 - 20)
|
||||
await page.mouse.wheel(0, -300)
|
||||
await sleep(220)
|
||||
// 断言「换算比例」而不是「比容器大」:正方形图 fit 进宽屏预览后本来就比容器窄,
|
||||
// 拿 rect.width > clientWidth 会比较,放大了也可能不成立(实测真站 549 vs 1011)
|
||||
check('滚轮放大预览、倍率胶囊出现', await page.evaluate(() => {
|
||||
const p = document.querySelector('.vz-preview')
|
||||
const v = document.querySelector('[data-stage="vector"]')
|
||||
const z = Number(p.style.getPropertyValue('--vz-zoom') || 1)
|
||||
const chip = document.querySelector('[data-zoom-chip]')
|
||||
const ratio = v.getBoundingClientRect().width / v.clientWidth
|
||||
return z > 1.1 && Boolean(chip) && !chip.hidden && Math.abs(ratio - z) < 0.02
|
||||
}))
|
||||
await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2)
|
||||
await sleep(220)
|
||||
check('双击复位回 100%', await page.evaluate(() => {
|
||||
const p = document.querySelector('.vz-preview')
|
||||
return Number(p.style.getPropertyValue('--vz-zoom') || 1) === 1
|
||||
}))
|
||||
|
||||
// 回归:平滑滚轮(小数 deltaY)在真站也必须缩放。旧逻辑靠整数步长识别鼠标,会把这类滚轮当平移。
|
||||
await page.evaluate(() => {
|
||||
const p = document.querySelector('.vz-preview')
|
||||
const r = p.getBoundingClientRect()
|
||||
p.dispatchEvent(new WheelEvent('wheel', {
|
||||
deltaY: -12.5, deltaMode: 0, bubbles: true, cancelable: true,
|
||||
clientX: r.left + r.width / 2, clientY: r.top + r.height / 2,
|
||||
}))
|
||||
})
|
||||
await sleep(160)
|
||||
check('真站:小数步长滚轮照样放大', await page.evaluate(() => {
|
||||
const p = document.querySelector('.vz-preview')
|
||||
return Number(p.style.getPropertyValue('--vz-zoom') || 1) > 1.001
|
||||
}))
|
||||
await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2)
|
||||
await sleep(160)
|
||||
|
||||
// ---------- 5.6) 复制到剪贴板(真写,读回校验口味) ----------
|
||||
await page.locator('[data-act="copy"]').click()
|
||||
await sleep(400)
|
||||
const clip = await page.evaluate(async () => {
|
||||
try {
|
||||
const items = await navigator.clipboard.read()
|
||||
const types = items[0] ? items[0].types : []
|
||||
let svg = ''
|
||||
if (types.indexOf('image/svg+xml') >= 0) svg = await (await items[0].getType('image/svg+xml')).text()
|
||||
return { types, svg, status: (document.querySelector('[data-status-text]') || {}).textContent || '' }
|
||||
} catch (e) { return { error: String(e && e.message) } }
|
||||
})
|
||||
if (clip.error) {
|
||||
check('复制 SVG 写入剪贴板', false, clip.error)
|
||||
} else {
|
||||
check('复制 SVG:剪贴板含 image/svg+xml(Figma 按矢量粘贴)',
|
||||
clip.types.indexOf('image/svg+xml') >= 0 && clip.svg.indexOf('<svg') === 0 && clip.svg.indexOf('<path') > 0,
|
||||
clip.types.join(',') + ' / ' + clip.svg.length + 'B')
|
||||
check('复制后给了反馈', /已复制/.test(clip.status), clip.status)
|
||||
// 拆分是这个版本的核心诉求:粘到 Figma 必须是多个可单独选中的图层,而不是一个整体
|
||||
const pathCount = (clip.svg.match(/<path/g) || []).length
|
||||
check('剪贴板里是多个独立 path(Figma 可单独选中,不是一个整体)', pathCount >= 5 && !/<g\b/.test(clip.svg), 'path 元素=' + pathCount)
|
||||
}
|
||||
|
||||
// ---------- 6) 保存为节点(真实画布桥) ----------
|
||||
await page.locator('[data-act="save"]').click()
|
||||
const saved = await poll(async () => (await page.locator('.iwb-node').count()) >= 2, 25000)
|
||||
check('保存为节点:画布新增一个图片节点', Boolean(saved), 'nodes=' + await page.locator('.iwb-node').count())
|
||||
check('模态已关闭', (await page.locator('.vz-root').count()) === 0)
|
||||
|
||||
const fatal = consoleErrors.filter((e) => /Content Security Policy|Refused to|SRI|integrity/i.test(e))
|
||||
check('无 CSP / SRI 报错', fatal.length === 0, fatal.slice(0, 2).join(' | '))
|
||||
if (consoleErrors.length) {
|
||||
console.log('')
|
||||
console.log('控制台错误(' + consoleErrors.length + ' 条,前 5 条):')
|
||||
for (const e of consoleErrors.slice(0, 5)) console.log(' ' + String(e).slice(0, 180))
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')
|
||||
await browser.close()
|
||||
process.exit(failed ? 1 : 0)
|
||||
@@ -16,7 +16,7 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||||
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
|
||||
const WANT_VERSION = JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8')).version
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import { bundleEngine } from './bundle-engine.mjs'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||||
|
||||
let chromium = null
|
||||
for (const base of [HOST_REPO, REPO, process.cwd()]) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/promptlib",
|
||||
"private": true,
|
||||
"version": "1.13.1",
|
||||
"version": "1.14.11",
|
||||
"description": "提示词库:右栏提示词列表(搜索/分组/收藏/新建编辑/插入画布/复制/删除),数据由宿主 promptlib 能力提供",
|
||||
"ibwPlugin": {
|
||||
"id": "promptlib",
|
||||
|
||||
+78
-11
@@ -607,13 +607,25 @@
|
||||
// dataURL → { img: 文件名 };失败原样返回(宁可留着内联 base64,也不丢封面)
|
||||
function ensureCoverFile (cover) {
|
||||
if (!FILEAPI || typeof cover !== 'string' || cover.indexOf('data:') !== 0) return Promise.resolve(cover)
|
||||
var name = coverFileName(cover)
|
||||
pendingCoverNames[name] = 1
|
||||
return Promise.resolve(FILEAPI.put(name, cover)).then(function (r) {
|
||||
if (r && r.ok) return { img: name }
|
||||
delete pendingCoverNames[name]
|
||||
return cover
|
||||
}).catch(function () { delete pendingCoverNames[name]; return cover })
|
||||
// v: 封面入库前先在**原生侧**缩到 512 —— 大封面会永久占 plugin-data,
|
||||
// 而且每次显示都要整幅解码(WebKit 上 4K 封面 = 21MB/次)。
|
||||
var prepped = Promise.resolve(cover)
|
||||
try {
|
||||
if (PLP_CTX && PLP_CTX.images && typeof PLP_CTX.images.preview === 'function') {
|
||||
prepped = Promise.resolve(PLP_CTX.images.preview(cover, { max: 512 }))
|
||||
.then(function (r) { return (r && r.ok && r.dataUrl) ? r.dataUrl : cover })
|
||||
.catch(function () { return cover })
|
||||
}
|
||||
} catch (e) { /* 退回未压缩 */ }
|
||||
return prepped.then(function (small) {
|
||||
var name = coverFileName(small)
|
||||
pendingCoverNames[name] = 1
|
||||
return Promise.resolve(FILEAPI.put(name, small)).then(function (r) {
|
||||
if (r && r.ok) return { img: name }
|
||||
delete pendingCoverNames[name]
|
||||
return small
|
||||
}).catch(function () { delete pendingCoverNames[name]; return small })
|
||||
})
|
||||
}
|
||||
// 回收未被任何词条引用的封面文件(判定在模块级 plpGcCoverFiles,设置页复用同一套)。
|
||||
// 返回 { removed, bytes, skipped }
|
||||
@@ -2201,12 +2213,40 @@
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 收藏(v1.14.0:宿主不再提供收藏入口,由插件自己注册)=====
|
||||
function plpNotifyCtx (ctx, t, ty) { try { if (ctx.promptlib && ctx.promptlib.notify) ctx.promptlib.notify(t, ty || 'ok') } catch (e) { /* ignore */ } }
|
||||
function plpCollect (ctx, nodeId) {
|
||||
var nodes = []
|
||||
try { nodes = (ctx.canvas && typeof ctx.canvas.getNodes === 'function') ? (ctx.canvas.getNodes() || []) : [] } catch (e) { nodes = [] }
|
||||
var n = null
|
||||
for (var i = 0; i < nodes.length; i++) if (nodes[i] && nodes[i].id === nodeId) { n = nodes[i]; break }
|
||||
var d0 = (n && n.data) || {}
|
||||
var text = String(d0.text || '').trim()
|
||||
var ttl = String(d0.title || '').trim()
|
||||
if (!text) { plpNotifyCtx(ctx, '提示词为空,无法收藏', 'err'); return Promise.resolve({ ok: false }) }
|
||||
var read = (ctx.data && typeof ctx.data.read === 'function') ? Promise.resolve(ctx.data.read()).catch(function () { return {} }) : Promise.resolve({})
|
||||
return read.then(function (d) {
|
||||
if (d && Array.isArray(d.prompts) && d.prompts.length) return { prompts: d.prompts, groups: Array.isArray(d.groups) ? d.groups : [] }
|
||||
return Promise.resolve(ctx.promptlib.list()).then(function (r) { return { prompts: (r && r.prompts) || [], groups: (r && r.groups) || [] } })
|
||||
}).then(function (cur) {
|
||||
var list = cur.prompts.slice()
|
||||
list.push({ id: 'q' + Date.now() + '_' + Math.floor(Math.random() * 1e6), name: ttl || ('提示词 ' + text.slice(0, 8) + '…'), text: text, tags: [], group: '' })
|
||||
var payload = { schemaVersion: 3, prompts: list, groups: cur.groups, updatedAt: Date.now() }
|
||||
var jobs = []
|
||||
if (ctx.data && typeof ctx.data.write === 'function') jobs.push(Promise.resolve(ctx.data.write(payload)).catch(function () {}))
|
||||
if (ctx.promptlib && typeof ctx.promptlib.save === 'function') jobs.push(Promise.resolve(ctx.promptlib.save({ prompts: list, groups: cur.groups })).catch(function () {}))
|
||||
return Promise.all(jobs)
|
||||
}).then(function () { plpNotifyCtx(ctx, '已收藏到未分组'); return { ok: true } })
|
||||
.catch(function () { plpNotifyCtx(ctx, '收藏失败,请重试', 'err'); return { ok: false } })
|
||||
}
|
||||
|
||||
|
||||
global.IWBPluginHost.register({
|
||||
id: 'promptlib',
|
||||
name: '提示词库',
|
||||
version: '1.13.1',
|
||||
version: '1.14.11',
|
||||
apiVersion: 1,
|
||||
capabilities: ['panels', 'promptlib', 'nodeTypes', 'canvas', 'canvasWrite'],
|
||||
capabilities: ['panels', 'promptlib', 'nodeTypes', 'canvas', 'canvasWrite', 'nodeActions', 'commands'],
|
||||
data: { schemaVersion: 3, maxBytes: 4 * 1024 * 1024 },
|
||||
settings: {
|
||||
panel: { type: 'custom', label: '分组与备份', render: renderPluginSettings },
|
||||
@@ -2289,15 +2329,18 @@
|
||||
titleBox.appendChild(title); titleBox.appendChild(meta)
|
||||
head.appendChild(thumb); head.appendChild(titleBox)
|
||||
var vars = el('div', { class: 'iwb-plp-nvars' })
|
||||
// v1.14.2:参考图开关移到头部(title 下面、变量列表上面)——与样式节点位置一致。
|
||||
// 原来放在节点底部,变量一多就要滚到底才点得到。
|
||||
var refRow = el('label', { class: 'iwb-plp-nref' })
|
||||
var refChk = el('input', { type: 'checkbox' })
|
||||
var refTxt = el('span', { text: '封面作参考图' })
|
||||
var refNum = el('em', { text: '0' })
|
||||
refRow.appendChild(refChk); refRow.appendChild(refTxt); refRow.appendChild(refNum)
|
||||
var warn = el('div', { class: 'iwb-plp-nwarn' })
|
||||
root.appendChild(head); root.appendChild(vars); root.appendChild(refRow); root.appendChild(warn)
|
||||
titleBox.appendChild(refRow)
|
||||
root.appendChild(head); root.appendChild(vars); root.appendChild(warn)
|
||||
host.appendChild(root)
|
||||
var st = { root: root, thumb: thumb, title: title, meta: meta, vars: vars, warn: warn, refChk: refChk, refNum: refNum, inputs: {}, key: '' }
|
||||
var st = { root: root, thumb: thumb, title: title, meta: meta, vars: vars, warn: warn, refChk: refChk, refNum: refNum, refRow: refRow, inputs: {}, key: '' }
|
||||
refChk.addEventListener('change', function () {
|
||||
var on = Boolean(refChk.checked)
|
||||
var cover = st.node && st.node.data ? st.node.data.cover : ''
|
||||
@@ -2403,6 +2446,7 @@
|
||||
if (!coverKey) st.thumb.style.display = 'none'
|
||||
var refOn = d.refOn === true
|
||||
if (st.refChk.checked !== refOn) st.refChk.checked = refOn
|
||||
try { if (st.refRow) st.refRow.classList.toggle('is-on', refOn) } catch (e) { /* ignore */ }
|
||||
st.refNum.textContent = refOn ? '1 张' : '0'
|
||||
// 未填提示(v1.12.3 语义变了):输入框空但「内容」有值 ⇒ 用内容兜底,不算缺;
|
||||
// 只有既没填、内容也空,这段占位才会在提示词里被去掉 —— 那才值得提醒。
|
||||
@@ -2433,6 +2477,29 @@
|
||||
}
|
||||
}
|
||||
|
||||
// v1.14.0:收藏入口归插件 —— 节点气泡(nodeAction)+ 右键「插件命令」;插件停用即消失
|
||||
if (ctx.nodeActions && typeof ctx.nodeActions.register === 'function') {
|
||||
ctx.nodeActions.register({
|
||||
id: 'collect-prompt',
|
||||
title: '收藏为提示词',
|
||||
icon: 'star',
|
||||
appliesTo: function (node) { return !!node && node.type === 'prompt' && String((node.data && node.data.text) || '').trim() !== '' },
|
||||
run: function (node) { if (node && node.id) plpCollect(ctx, node.id) },
|
||||
})
|
||||
}
|
||||
if (ctx.commands && typeof ctx.commands.register === 'function') {
|
||||
ctx.commands.register({
|
||||
id: 'collect-selected',
|
||||
title: '收藏选中的提示词',
|
||||
icon: 'star',
|
||||
run: function () {
|
||||
var sel = (ctx.canvas && typeof ctx.canvas.getSelectedNode === 'function') ? ctx.canvas.getSelectedNode() : null
|
||||
if (!sel || !sel.id) { plpNotifyCtx(ctx, '先选中一个提示词节点', 'err'); return }
|
||||
plpCollect(ctx, sel.id)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return {}
|
||||
})
|
||||
})(typeof window !== 'undefined' ? window : globalThis)
|
||||
+13
-4
@@ -151,8 +151,17 @@
|
||||
.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}
|
||||
/* v1.14.2:参考图开关移到头部(与样式节点一致)——做成浅色药丸,不再是底部分隔行 */
|
||||
.iwb-plp-nref{display:inline-flex;align-items:center;gap:6px;margin-top:6px;padding:2px 8px;border-radius:6px;background:var(--iwb-layer,#f0f1f4);color:var(--iwb-text2,#4d5668);font-size: 12px;cursor:pointer;align-self:flex-start}
|
||||
.iwb-plp-nref em{font-style:normal;color:var(--iwb-text2,#8b929c)}
|
||||
/* v1.14.3:勾选框改成自绘的蓝色实心勾(与样式节点视觉一致;原生 macOS 勾选框在不同外观下不一致) */
|
||||
.iwb-plp-nref input[type="checkbox"]{appearance:none;-webkit-appearance:none;margin:0;width:15px;height:15px;flex:0 0 auto;border-radius:var(--iwb-set-check-radius,4px);border:1.5px solid color-mix(in srgb, var(--iwb-border2) 70%, var(--iwb-text2));background:var(--iwb-field,var(--iwb-plugin-surface,#fff));cursor:pointer;position:relative;transition:background .12s ease,border-color .12s ease}
|
||||
.iwb-plp-nref input[type="checkbox"]:checked{background:var(--iwb-brand,#1677ff);border-color:var(--iwb-brand,#1677ff)}
|
||||
.iwb-plp-nref input[type="checkbox"]:checked::after{content:"";position:absolute;left:50%;top:50%;width:4px;height:8px;border:solid var(--iwb-on-brand,#ffffff);border-width:0 2px 2px 0;transform:translate(-50%,-58%) rotate(45deg)}
|
||||
/* v1.14.6:强调色当文字用时必须和正文色混合 —— 直接用 --iwb-brand 在暗色下对比度不够(蓝字压深灰底)。
|
||||
亮色混深(更沉),暗色混浅(更亮),两端都过 4.5:1。 */
|
||||
.iwb-plp-nref.is-on{background:var(--iwb-accent-tint, color-mix(in srgb, var(--iwb-brand) 18%, transparent));color:var(--iwb-accent-on-surface, color-mix(in srgb, var(--iwb-brand) 45%, var(--iwb-text)))}
|
||||
.iwb-plp-nref.is-on em{color:inherit;opacity:.8}
|
||||
.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:变量编辑器 / 详情变量 */
|
||||
@@ -370,7 +379,7 @@ box-shadow: 0 24px 60px rgba(0,0,0,.32);
|
||||
|
||||
/* 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:hover{border-color:var(--iwb-border2,#b9bfca)}
|
||||
.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)}
|
||||
|
||||
@@ -382,9 +391,9 @@ box-shadow: 0 24px 60px rgba(0,0,0,.32);
|
||||
.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-bg{position:absolute;inset:0;overflow:hidden;border-radius:inherit;transition:transform .16s ease;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:hover{border-color:var(--iwb-border2,#b9bfca)}
|
||||
/* 取消卡片本体的缩放/层级切换(闪烁与边缘点击丢失的来源) */
|
||||
.iwb-plp-card{transform:none}
|
||||
.iwb-plp-card:hover{transform:none;z-index:auto}
|
||||
|
||||
+14
-5
@@ -37,19 +37,28 @@ export const checkPlugin = (dir) => {
|
||||
|
||||
if (src.indexOf('IWBPluginHost.register(') < 0) errors.push('entry 未调用 IWBPluginHost.register(manifest, factory)')
|
||||
|
||||
const idMatch = /(?:^|[\s{,])id:\s*'([^']+)'/.exec(src)
|
||||
// v1.0.2:只在 register(...) 的 manifest 块里找字段。
|
||||
// 旧写法在整份源码里找第一个 id:/version:,会被业务代码里的 { id: 'q' + Date.now() } 误命中
|
||||
// (promptlib 就因此被判「entry 内 id (q) 与 ibwPlugin.id 不一致」)。
|
||||
const regAt = src.indexOf('IWBPluginHost.register(')
|
||||
// 从 register( 开始截到文件末尾:manifest 一定在 factory 之前,而业务代码里的同名键都在 register 之前
|
||||
const regBlock = regAt >= 0 ? src.slice(regAt) : src
|
||||
// 两段扫描:优先 register( 之后(避开业务代码里的同名键),找不到字面量再回退整份源码——
|
||||
// image-annotate / image-vectorize 是构建产物,manifest 用 __IWB_XXX_MANIFEST__ 常量传入。
|
||||
const pick = (re) => re.exec(regBlock) || re.exec(src)
|
||||
const idMatch = pick(/(?:^|[\s{,])id:\s*'([^']+)'/)
|
||||
if (!idMatch) errors.push("entry 内未找到 id: '<id>' 字面量(manifest 必须显式声明 id)")
|
||||
else if (idMatch[1] !== id) errors.push('entry 内 id (' + idMatch[1] + ') 与 ibwPlugin.id (' + id + ') 不一致')
|
||||
|
||||
const apiMatch = /apiVersion:\s*(\d+)/.exec(src)
|
||||
const apiMatch = pick(/apiVersion:\s*(\d+)/)
|
||||
if (!apiMatch) errors.push('entry 内未找到 apiVersion 字面量')
|
||||
else if (Number(apiMatch[1]) !== meta.apiVersion) errors.push('entry 内 apiVersion (' + apiMatch[1] + ') 与 ibwPlugin.apiVersion (' + meta.apiVersion + ') 不一致')
|
||||
|
||||
const versionMatch = /version:\s*'([^']+)'/.exec(src)
|
||||
const versionMatch = pick(/version:\s*'([^']+)'/)
|
||||
if (!versionMatch) errors.push("entry 内未找到 version: '<ver>' 字面量")
|
||||
else if (versionMatch[1] !== String(pkg.version)) errors.push('entry 内 version (' + versionMatch[1] + ') 与 package.json version (' + pkg.version + ') 不一致')
|
||||
if (!/name:\s*'[^']+'/.test(src)) errors.push("entry 内未找到 name: '<name>' 字面量")
|
||||
if (!/capabilities:\s*\[/.test(src)) errors.push('entry 内未找到 capabilities 数组')
|
||||
if (!/name:\s*'[^']+'/.test(regBlock) && !/name:\s*'[^']+'/.test(src)) errors.push("entry 内未找到 name: '<name>' 字面量")
|
||||
if (!/capabilities:\s*\[/.test(regBlock) && !/capabilities:\s*\[/.test(src)) errors.push('entry 内未找到 capabilities 数组')
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
+6
-1
@@ -1,8 +1,13 @@
|
||||
# sticky · 便利贴(v1.0.7)
|
||||
# sticky · 便利贴(v1.0.10)
|
||||
|
||||
画布上的便签节点:一张纸片,写多行文字,能调字号、粗细、背景色,能拖大拖小。
|
||||
**不连线、不进生图链路**——纯标注用途(说明节点、分组标题、随手记)。
|
||||
|
||||
> v1.0.10(2026-11-29):**移除左侧栏面板**。v1.0.8 的产物把面板登记又带回来了,用户截图显示资源面板
|
||||
> 多出「便利贴」标签页。现在只登记节点类型,插入便利贴走画布右键菜单;`capabilities` 同步去掉 `panels`。
|
||||
> 教训:这个面板被删过两次(11-28 删过、11-29 又出现),因为改的是产物层或从旧源码重打包 —— 只改这个源仓,
|
||||
> 发版前确认 `main.js` 里搜不到 panel 登记。
|
||||
|
||||
## 设计由来
|
||||
|
||||
用户要一个"在画布上建立说明文字"的插件。最初设想是"标题节点",后来改成便签:
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/sticky",
|
||||
"private": true,
|
||||
"version": "1.0.7",
|
||||
"version": "1.0.10",
|
||||
"description": "画布便利贴:多行文本 + 字号/粗细调节 + 8 色背景,纯标注节点不连线",
|
||||
"ibwPlugin": {
|
||||
"id": "sticky",
|
||||
|
||||
+45
-87
@@ -280,19 +280,55 @@
|
||||
body.addEventListener('input', onInput)
|
||||
|
||||
st._listeners = { tools: onTool, pal: onPal, color: onColor, input: onInput, dblclick: onDblClick, setEditing: setEditing }
|
||||
|
||||
// 宽度变化 → 重新算行数(2026-11-26)。宿主改卡片宽度的时机都不经过 render:
|
||||
// 拖右下角改宽、左右侧栏开合、首帧布局落后于脚本。没有这条监听时,
|
||||
// 「先窄后宽」会让 textarea 一直按窄的时候的行数留高度 —— 文字下面就多出一行空白。
|
||||
if (typeof global.ResizeObserver === 'function') {
|
||||
try {
|
||||
st.ro = new global.ResizeObserver(function () {
|
||||
// 宿主销毁节点后 observer 会继续活着:发现骨架已摘除就自我断开
|
||||
if (st.root && st.root.isConnected === false) { try { st.ro.disconnect() } catch (e3) { /* noop */ } st.ro = null; return }
|
||||
var d = (st.node && st.node.data) || {}
|
||||
fitBody(st, d.text == null ? '' : String(d.text), normSize(d.fontSize == null ? DEFAULT_SIZE : d.fontSize))
|
||||
fitOuterBox(st, st.node)
|
||||
})
|
||||
st.ro.observe(body)
|
||||
} catch (e3) { st.ro = null }
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// textarea 高度贴字:数据(文本/字号)变了才重算,避免每次 render 都 reflow。
|
||||
// textarea 高度贴字:文本 / 字号 / **宽度** 变了才重算,避免每次 render 都 reflow。
|
||||
// 设 auto → 读 scrollHeight → 写回,是 textarea 自适应的标准做法;浏览器里行数/自动换行都算准。
|
||||
//
|
||||
// 2026-11-26(用户反馈「文字下面又多出一行空白行」,v1.0.4 修过又回来了):
|
||||
// ① 旧实现只比 text/size ⇒ **宽度一变就沿用旧行数的高度**。宿主会在这些时候改卡片宽度:
|
||||
// 拖动改宽、左右侧栏开合、首帧还没布局完(clientWidth=0 时会算出很多行)。宽了以后
|
||||
// 文本少一行,高度却按多一行留着 —— 正好在文字下面空一整行。
|
||||
// ② scrollHeight 是整数像素,line-height 1.7×14=23.8 时每行都有取整误差,累加后同样表现为
|
||||
// 「多出半行到一行」。改成先按行数取整、再乘回去。
|
||||
function fitBody(st, text, size) {
|
||||
if (st.fitText === text && st.fitSize === size) return
|
||||
st.fitText = text; st.fitSize = size
|
||||
var b = st.body
|
||||
var w = b.clientWidth || 0
|
||||
if (st.fitText === text && st.fitSize === size && st.fitW === w) return
|
||||
st.fitText = text; st.fitSize = size; st.fitW = w
|
||||
var padY = 24
|
||||
var lineH = Math.round(size * 1.7) || 24
|
||||
try {
|
||||
var cs = global.getComputedStyle ? global.getComputedStyle(b) : null
|
||||
if (cs) {
|
||||
var pt = parseFloat(cs.paddingTop), pb = parseFloat(cs.paddingBottom)
|
||||
if (isFinite(pt) && isFinite(pb)) padY = pt + pb
|
||||
var lh = parseFloat(cs.lineHeight)
|
||||
if (isFinite(lh) && lh > 0) lineH = lh
|
||||
}
|
||||
} catch (e) { /* noop */ }
|
||||
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'
|
||||
var raw = b.scrollHeight
|
||||
var lines = (raw > 0 && lineH > 0) ? Math.max(1, Math.round((raw - padY) / lineH)) : Math.max(1, String(text).split('\n').length)
|
||||
b.style.height = Math.round(lines * lineH + padY) + 'px'
|
||||
// 高度没变就不留空字符串(兼容 stub:style.height 是普通对象)
|
||||
if (!b.style.height && prev) b.style.height = prev
|
||||
}
|
||||
@@ -361,89 +397,19 @@
|
||||
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
|
||||
}
|
||||
// ⚠️ 不要给便签加左侧栏面板(用户 2026-11-29 再次确认,此前 11-28 做过一次又被改回来):
|
||||
// 一旦向宿主登记「面板」,资源面板就会多出一个「便利贴」标签页。插入便利贴走画布右键菜单,不走面板。
|
||||
|
||||
function dispose() {
|
||||
ctxRef = null
|
||||
ctxForPanel = null
|
||||
noteList = []
|
||||
}
|
||||
|
||||
global.IWBPluginHost.register({
|
||||
id: 'sticky',
|
||||
name: '便利贴',
|
||||
version: '1.0.7',
|
||||
version: '1.0.10',
|
||||
apiVersion: 1,
|
||||
capabilities: ['panels', 'nodeTypes', 'canvas'],
|
||||
capabilities: ['nodeTypes', 'canvas'],
|
||||
}, function (ctx) {
|
||||
ctxRef = ctx
|
||||
if (ctx.nodes && typeof ctx.nodes.register === 'function') {
|
||||
@@ -456,14 +422,6 @@
|
||||
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)
|
||||
@@ -27,11 +27,20 @@ function makeNode(tag) {
|
||||
children: [], parentNode: null, _text: '', attrs: {}, listeners: {},
|
||||
style: {}, className: '', hidden: false, value: '',
|
||||
// textarea 自适应高度需要 scrollHeight:按「行数 × 行高 + 上下 padding」模拟。
|
||||
// 给了 clientWidth 就按宽度粗估换行(越宽行数越少)—— v1.0.8「宽度变了高度要跟着重算」靠它验证。
|
||||
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
|
||||
const w = Number(this.clientWidth) || 0
|
||||
const text = String(this.value || '')
|
||||
let lines = 0
|
||||
if (w > 40) {
|
||||
const per = Math.max(1, Math.floor((w - 24) / (size * 0.55)))
|
||||
text.split('\n').forEach((p) => { lines += Math.max(1, Math.ceil(p.length / per)) })
|
||||
} else {
|
||||
lines = Math.max(1, text.split('\n').length)
|
||||
}
|
||||
return Math.ceil(Math.max(1, lines) * size * 1.7) + 24
|
||||
},
|
||||
get textContent() { return this._text },
|
||||
set textContent(v) { this._text = String(v); this.children = [] },
|
||||
@@ -127,7 +136,8 @@ 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')
|
||||
const PKG_VERSION = JSON.parse(readFileSync(path.resolve(HERE, '../package.json'), 'utf8')).version
|
||||
check('manifest.version = package.json', r.manifest.version === PKG_VERSION, r.manifest.version + ' / ' + PKG_VERSION)
|
||||
check('manifest.apiVersion = 1', r.manifest.apiVersion === 1)
|
||||
check('capabilities 含 panels/nodeTypes/canvas',
|
||||
['panels', 'nodeTypes', 'canvas'].every((c) => r.manifest.capabilities.includes(c)))
|
||||
@@ -253,6 +263,27 @@ 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
|
||||
// v1.0.8(用户反馈「文字下面又多出一行空白行」):宽度变化必须重算高度。
|
||||
// 旧实现只比 text/size ⇒ 先窄后宽时行数少了、高度仍按多的那行留着,正好空出一整行。
|
||||
{
|
||||
const hostW = makeNode('div')
|
||||
const nodeW = { id: 'w1', type: 'plugin:sticky:sticky', data: { text: 'x'.repeat(120), fontSize: 14, fontWeight: 400, bgColor: '#FCE8B0' } }
|
||||
const propsW = { onUpdate() {} }
|
||||
const taW = () => findByClass(hostW, 'iwb-sticky-body')
|
||||
r.nodeApi.render(nodeW, propsW, hostW)
|
||||
taW().clientWidth = 160
|
||||
r.nodeApi.render(nodeW, propsW, hostW)
|
||||
const tall = parseFloat(taW().style.height)
|
||||
taW().clientWidth = 420
|
||||
r.nodeApi.render(nodeW, propsW, hostW)
|
||||
const wide = parseFloat(taW().style.height)
|
||||
check('宽度 160→420(同一段文字)textarea 高度跟着变矮', wide < tall, tall + ' → ' + wide)
|
||||
// 行高对齐:高度必须是「行高 × 整数行 + padding」,不能带半行误差
|
||||
const padY = 24
|
||||
const lineH = 14 * 1.7
|
||||
const rem = ((wide - padY) % lineH + lineH) % lineH
|
||||
check('高度按整数行对齐(无半行残差)', rem < 1.5 || rem > lineH - 1.5, 'remainder=' + rem.toFixed(2))
|
||||
}
|
||||
findByAct(nh.h, 'bold').fire('click', { target: findByAct(nh.h, 'bold') })
|
||||
check('B 切 fontWeight=600', nh.h.__updates.some((u) => u.patch.fontWeight === 600))
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
`ensureStyle()` 原本只在 `mount()`(面板)里调用 ⇒ **没打开过「风格库」面板**时,节点体是无样式的裸 DOM,
|
||||
`<img class="iwb-ssn-thumb">` 按原图尺寸铺满整个节点(真机表现:图片"跑出来了")。
|
||||
现在 setup 注册变体前注入一次,`renderStyleNode()` 里再兜一次(幂等)。
|
||||
回归用例:`tools/e2e-test-site.mjs` 第 9 段(不开面板直接进存档画布,断言缩略图宽高 ≈56px)。
|
||||
回归用例:`tools/harness.mjs` 的「样式表在脚本执行时就已注入(不开面板、不跑 setup 也在)」闸门,以及缩略图 56px 方块的断言。
|
||||
|
||||
### v1.3.2(2026-11-14)注入点再提前到脚本执行 + 缩略图内联兜底
|
||||
|
||||
@@ -182,15 +182,14 @@
|
||||
数据与图片都是公网 `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/harness.mjs`(88 项) | 面板交互、详情页按钮顺序与同色、节点体结构、变量写入/防抖/不失焦、收起变量、CSS 注入闸门、截图 | 无(自带 mock 宿主 + 真 Chromium) |
|
||||
| 线上数据真网 | `node tools/e2e-real.mjs`(10 项) | styles.json 真拉得到、卡片渲染、样式节点入口 | 网络 |
|
||||
| 桌面客户端端到端 | `node tools/e2e-test-site.mjs`(15 项) | **宿主新接口到底接上没有**:进画布 → 开资源库 → 点「样式节点」→ 节点体由插件渲染、示例图默认勾选、变量输入不失焦、多变量不裁切、收起生效 | 桌面客户端已装本插件(`SITE=` 换地址,`HEADED=1` 看着跑) |
|
||||
|
||||
前两支只验插件自己;**第三支才验宿主**,发布宿主改动后必跑。
|
||||
两支都验插件自己;发布宿主改动后,在桌面客户端市场里确认版本与加载状态,并用真实存档画布核对样式节点体(harness 的 CSS 闸门已覆盖「不开面板直接进画布」这一关键场景)。
|
||||
|
||||
## 发布
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||||
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
|
||||
|
||||
let chromium = null
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
// 真机验收:**测试站上「宿主新接口 + 本插件」端到端**跑通(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)
|
||||
@@ -18,7 +18,7 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/style-source/tools
|
||||
const REPO = path.resolve(HERE, '../..')
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||||
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
|
||||
const STYLES_JSON = '/Users/qiqi/open/github/style-source/data/styles.json'
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ npm run validate
|
||||
```bash
|
||||
node white-bg-800/tools/harness.mjs
|
||||
```
|
||||
- `tools/e2e-site.mjs`:真实桌面客户端的端到端(市场安装 + SRI + 漂浮菜单 → 新建节点),透明底等设置类用例由 harness 覆盖。
|
||||
- 发布后回读市场索引 + 客户端市场里确认版本与加载状态;透明底等设置类用例由 harness 覆盖。
|
||||
|
||||
> harness 里的 mock `ctx.log` 必须是**函数**(真实宿主如此),早先写成对象导致凡是走 `ctx.log` 的分支全炸。
|
||||
> 另外几何断言在有损格式下要留 ±4px 容差(jpeg 边缘振铃),精确几何用 `format=png` 的用例测。
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/white-bg-800",
|
||||
"private": true,
|
||||
"version": "1.2.1",
|
||||
"version": "1.2.2",
|
||||
"description": "白底图:把节点图等比缩放居中合成到正方形画布,按格式/质量/体积上限编码,输出 <name>_<size>x<size>.<ext>;可开双版本出透明 PNG + 白底 JPG",
|
||||
"ibwPlugin": {
|
||||
"id": "white-bg-800",
|
||||
|
||||
@@ -145,7 +145,7 @@
|
||||
global.IWBPluginHost.register({
|
||||
id: 'white-bg-800',
|
||||
name: '白底图',
|
||||
version: '1.2.1',
|
||||
version: '1.2.2',
|
||||
apiVersion: 1,
|
||||
capabilities: ['commands', 'canvas', 'canvasWrite', 'nodeActions'],
|
||||
settings: {
|
||||
@@ -166,7 +166,7 @@
|
||||
// 绝不对 data: URL 发网络请求 —— 宿主 CSP connect-src 不含 data:,必被拦(姊妹插件 image-annotate 踩过并修掉的坑)。
|
||||
// 远程 url 才走 fetch,转成 blob: URL 再解码(blob: 同样不污染画布)。
|
||||
async function resolveImage(nodeId) {
|
||||
const image = await ctx.canvas.getNodeImage(nodeId)
|
||||
const image = await ctx.canvas.getNodeImage(nodeId, { max: 2048 }) // v: 白底处理封顶 2048
|
||||
if (!image) throw new Error(NO_IMAGE)
|
||||
|
||||
if (image.dataUrl) return loadImage(image.dataUrl)
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
// 真实站点端到端(开发用,不进 CI)—— white-bg-800「白底图」。
|
||||
//
|
||||
// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被
|
||||
// `connect-src 'self' https: …` 拦掉,因为宿主 CSP 的 `connect-src` 不含 `data:`)
|
||||
// 在 mock 下永远绿,只有带真实 KV + 浏览器 SRI + 真实 CSP 的真站能抓出来。
|
||||
// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)校验 + 真实画布桥。
|
||||
//
|
||||
// 运行(需要 Playwright):
|
||||
// node white-bg-800/tools/e2e-site.mjs # 默认测试站
|
||||
// IWB_BASE_URL=https://iwb.maqiart.eu.org node white-bg-800/tools/e2e-site.mjs # 正式站
|
||||
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
|
||||
import { createRequire } from 'node:module'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/white-bg-800/tools
|
||||
const REPO = path.resolve(HERE, '../..') // <repo>
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
|
||||
let chromium = null
|
||||
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
|
||||
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
|
||||
}
|
||||
if (!chromium) {
|
||||
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT:')
|
||||
console.error(' npm i -D playwright # 本仓或宿主仓皆可')
|
||||
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node white-bg-800/tools/e2e-site.mjs')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
|
||||
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'white-bg-800/package.json'), 'utf8')).version
|
||||
const CFG = { providers: [], canvas: {} }
|
||||
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
|
||||
|
||||
let failed = 0
|
||||
const check = (name, ok, detail) => {
|
||||
if (!ok) failed++
|
||||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||||
}
|
||||
const poll = async (fn, timeout = 25000, step = 250) => {
|
||||
const end = Date.now() + timeout
|
||||
for (;;) {
|
||||
let v
|
||||
try { v = await fn() } catch { v = false }
|
||||
if (v) return v
|
||||
if (Date.now() > end) return false
|
||||
await new Promise((r) => setTimeout(r, step))
|
||||
}
|
||||
}
|
||||
|
||||
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
|
||||
const browser = await chromium.launch()
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } })
|
||||
const consoleErrors = []
|
||||
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
|
||||
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
|
||||
|
||||
// 造一张真实的 96x64 PNG 作为节点图片(故意非正方形,让 800 方画布的等比缩放/居中被真正练到)
|
||||
await page.goto('about:blank')
|
||||
const PNG = await page.evaluate(() => {
|
||||
const c = document.createElement('canvas')
|
||||
c.width = 96; c.height = 64
|
||||
const x = c.getContext('2d')
|
||||
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 96, 64)
|
||||
x.fillStyle = '#ffffff'; x.fillRect(20, 12, 56, 40)
|
||||
return c.toDataURL('image/png')
|
||||
})
|
||||
|
||||
// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled
|
||||
await page.addInitScript((d) => {
|
||||
localStorage.clear()
|
||||
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
|
||||
const ws = JSON.parse(JSON.stringify(d.ws))
|
||||
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
|
||||
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
|
||||
localStorage.setItem('iwb_ws_active', ws.activeId)
|
||||
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
|
||||
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
|
||||
localStorage.setItem('iwb_plugins', JSON.stringify({ 'white-bg-800': { enabled: true, settings: {}, data: {} } }))
|
||||
}, { cfg: CFG, ws: WS, png: PNG })
|
||||
|
||||
// ---------- 1) 站点可达 ----------
|
||||
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
|
||||
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
|
||||
|
||||
// ---------- 2) 宿主就绪 + 真实 KV 加载并启用 ----------
|
||||
const hostReady = await poll(async () => page.evaluate(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true), 30000)
|
||||
check('window.IWBPluginHost 就绪(initialized)', Boolean(hostReady))
|
||||
const active = await poll(async () => page.evaluate(() => {
|
||||
const p = window.IWBPluginHost.list().find((x) => x.id === 'white-bg-800')
|
||||
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
|
||||
}))
|
||||
check('从真实 KV 加载并启用(active)', Boolean(active), JSON.stringify(active))
|
||||
|
||||
// ---------- 3) 版本 ----------
|
||||
check('线上版本 = white-bg-800/package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
|
||||
|
||||
// ---------- 4) SRI ----------
|
||||
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
|
||||
check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /plugin-white-bg-800(\.[0-9a-f]{12})?\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
|
||||
|
||||
// ---------- 5) 打开工作区 + 种子节点 ----------
|
||||
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
|
||||
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
|
||||
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
|
||||
|
||||
// ---------- 6) 入口:节点漂浮菜单(title 是静态字面量「白底图」;回落右键插件命令)----------
|
||||
const triggerWhiteBg = async () => {
|
||||
await page.locator('.iwb-node[data-node-id="r1"]').click()
|
||||
const btn = page.locator('.iwb-node-floatbar button[title="白底图"]')
|
||||
if (await btn.count()) { await btn.click(); return '漂浮菜单' }
|
||||
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
|
||||
await page.locator('.iwb-ctx-item').filter({ hasText: '白底图:选中节点' }).click()
|
||||
return '右键命令'
|
||||
}
|
||||
const entry = await triggerWhiteBg()
|
||||
check('节点入口可触发(漂浮菜单或右键命令)', true, entry)
|
||||
|
||||
// ---------- 7) 默认「新建」:恰好 2 个节点、新节点为 src_800x800.png ----------
|
||||
const created = await poll(async () => page.evaluate(() => {
|
||||
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
|
||||
const nodes = ws.nodes || []
|
||||
if (nodes.length !== 2) return false
|
||||
const n = nodes.find((x) => x.id !== 'r1') || nodes[1]
|
||||
return { nodes: nodes.length, name: n.data && n.data.name }
|
||||
}))
|
||||
const wsNodes = created ? created.nodes : await page.evaluate(() => (JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}').nodes || []).length)
|
||||
check('默认「新建」:iwb_ws_w1 恰好 2 个节点', wsNodes === 2, 'nodes=' + wsNodes)
|
||||
check('新节点 data.name = src_800x800.jpg(默认 format=jpeg)', Boolean(created && /^src_800x800\.jpg$/.test(created.name || '')), created && String(created.name))
|
||||
|
||||
// ---------- 8) 页内解引用 + 解码新建 JPEG:800x800、左上像素为白色 ----------
|
||||
// 宿主「C3」引用模型:localStorage 里只存引用,字节在别处 —— 假设 localStorage 里有 base64 是
|
||||
// 不可能的(by design)。两种引用形态都要认:
|
||||
// a) { __blob: 'imgblob_<hash>_<len>' } → IndexedDB(src/image-blob-store.js)
|
||||
// b) { __cache: '<同源 URL>' } → 宿主把大 dataURL 外置成 /__iwb_cache__/xxx(当前线上形态)
|
||||
// 故在页内经 IWBImageBlobStore 解引用或同源 fetch __cache(CSP connect-src 'self' 放行)。
|
||||
const resolved = await poll(async () => page.evaluate(async () => {
|
||||
// 读节点图(按优先级解引用):a) data: 字符串直用 b) {__blob} 引用解引用 c) 其余形态给诊断失败
|
||||
const resolveNodeDataUrl = async (d) => {
|
||||
if (typeof d === 'string' && /^data:/.test(d)) return { dataUrl: d, via: 'data:' } // a)
|
||||
if (d && typeof d === 'object' && typeof d.__cache === 'string' && d.__cache) { // b2) 宿主把大 dataURL 外置成同源缓存引用
|
||||
const toDataUrl = (blob) => new Promise((res) => {
|
||||
const fr = new FileReader()
|
||||
fr.onload = () => res(String(fr.result || ''))
|
||||
fr.onerror = () => res('')
|
||||
fr.readAsDataURL(blob)
|
||||
})
|
||||
try {
|
||||
// /__iwb_cache__/<hash> 由 SW 直出;冷启动 SW 未接管时该路径会落到 Pages 404(返回 HTML)。
|
||||
// 故优先直接读 Cache Storage,读不到再走 fetch(此时 SW 已接管)。
|
||||
const abs = new URL(d.__cache, location.origin).href
|
||||
if (typeof caches !== 'undefined') {
|
||||
const hit = (await caches.match(abs)) || (await caches.match(d.__cache))
|
||||
if (hit) {
|
||||
const blob = await hit.blob()
|
||||
const u = await toDataUrl(blob)
|
||||
return u ? { dataUrl: u, via: '__cache(CS ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' }
|
||||
}
|
||||
}
|
||||
const resp = await fetch(abs)
|
||||
const blob = await resp.blob()
|
||||
const u = await toDataUrl(blob)
|
||||
return u ? { dataUrl: u, via: '__cache(fetch ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' }
|
||||
} catch (e) {
|
||||
return { error: '__cache 抓取抛错: ' + ((e && e.message) || String(e)) }
|
||||
}
|
||||
}
|
||||
if (d && typeof d === 'object' && typeof d.__blob === 'string' && d.__blob) { // b)
|
||||
const Lib = window.IWBImageBlobStore
|
||||
if (!Lib) return { error: 'window.IWBImageBlobStore 缺失' }
|
||||
try {
|
||||
let u = ''
|
||||
if (typeof Lib.resolveDataUrl === 'function') {
|
||||
u = await Lib.resolveDataUrl(d.__blob)
|
||||
} else if (typeof Lib.create === 'function') {
|
||||
// 与 app.js:730 同一构造:idb 用宿主同一存储运行时(get 直出 Blob)
|
||||
const idb = (window.IWBStorageRuntime && window.IWBStorageRuntime.indexedDb) ||
|
||||
(window.IWBStorageFallbackIndexeddb && window.IWBStorageContract && window.IWBStorageFallbackIndexeddb.create({ contract: window.IWBStorageContract.indexedDb }))
|
||||
if (!idb || typeof idb.get !== 'function') return { error: '取不到宿主 idb(IWBStorageRuntime.indexedDb)' }
|
||||
u = await Lib.create({ idb }).resolveDataUrl(d.__blob)
|
||||
} else {
|
||||
return { error: 'IWBImageBlobStore 无 resolveDataUrl / create' }
|
||||
}
|
||||
return (typeof u === 'string' && u) ? { dataUrl: u, via: '__blob' } : { error: '解引用未返回字节(' + d.__blob + ')' }
|
||||
} catch (e) {
|
||||
return { error: '解引用抛错: ' + ((e && e.message) || String(e)) }
|
||||
}
|
||||
}
|
||||
return { error: '未知 data 形态: ' + (d == null ? String(d) : typeof d) + ' keys=' + (d && typeof d === 'object' ? Object.keys(d).join(',') : '-') + ' sample=' + JSON.stringify(d).slice(0, 220) } // c)
|
||||
}
|
||||
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
|
||||
const nodes = ws.nodes || []
|
||||
const n = nodes.length === 2 ? (nodes.find((x) => x.id !== 'r1') || nodes[1]) : null
|
||||
if (!n) return false // 新节点未就绪 → 重试
|
||||
const r = await resolveNodeDataUrl(n.data && n.data.data)
|
||||
if (r.error) return { error: r.error }
|
||||
if (!/^data:image\/jpeg;base64,/.test(r.dataUrl)) return { error: '解引用结果不是 JPEG dataURL(via=' + r.via + '): ' + String(r.dataUrl).slice(0, 40) }
|
||||
const img = new Image()
|
||||
const ok = await new Promise((res) => { img.onload = () => res(true); img.onerror = () => res(false); img.src = r.dataUrl })
|
||||
if (!ok) return { dataOk: true, via: r.via, decodeError: 'Image 解码失败' }
|
||||
const c = document.createElement('canvas')
|
||||
c.width = img.naturalWidth; c.height = img.naturalHeight
|
||||
const x = c.getContext('2d')
|
||||
x.drawImage(img, 0, 0)
|
||||
const px = x.getImageData(0, 0, 1, 1).data
|
||||
return { dataOk: true, via: r.via, w: img.naturalWidth, h: img.naturalHeight, px: [px[0], px[1], px[2], px[3]] }
|
||||
}))
|
||||
const d = resolved || {}
|
||||
const dDiag = d.error || d.decodeError || (resolved ? '' : '轮询超时:新节点未出现')
|
||||
check('新节点 data 为 JPEG 字节(引用已解析)', Boolean(d.dataOk), d.dataOk ? d.via : dDiag)
|
||||
check('新建 JPEG 解码尺寸 = 800x800', Boolean(d.dataOk && d.w === 800 && d.h === 800), d.dataOk ? d.w + 'x' + d.h : dDiag)
|
||||
// jpeg 有损:纯白角落允许 ±5 的压缩抖动,但 alpha 必须不透明
|
||||
check('新建 JPEG 左上像素 ≈ 白色且不透明', Boolean(d.dataOk && d.px && d.px[0] >= 250 && d.px[1] >= 250 && d.px[2] >= 250 && d.px[3] === 255), JSON.stringify(d.px) || dDiag)
|
||||
|
||||
// 透明模式(transparent)不在此二次跑(需改设置再整轮重放,易碎)——由 white-bg-800/tools/harness.mjs 覆盖。
|
||||
|
||||
// ---------- 9) 无 CSP / SRI 拦截 ----------
|
||||
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
|
||||
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
|
||||
|
||||
// ---------- 10) 无页面级运行时错误 ----------
|
||||
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
|
||||
|
||||
await browser.close()
|
||||
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
|
||||
process.exit(failed ? 1 : 0)
|
||||
@@ -15,7 +15,7 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/white-bg-800/tools
|
||||
const REPO = path.resolve(HERE, '../..') // <repo>
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
|
||||
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
|
||||
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
|
||||
|
||||
let chromium = null
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@iwb-plugin/xianyi-cutout",
|
||||
"private": true,
|
||||
"version": "1.0.3",
|
||||
"version": "1.0.4",
|
||||
"description": "鲜艺抠图:调用本机 30092 的 /rmbg 把节点图抠成透明底",
|
||||
"ibwPlugin": {
|
||||
"id": "xianyi-cutout",
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
global.IWBPluginHost.register({
|
||||
id: 'xianyi-cutout',
|
||||
name: '鲜艺抠图',
|
||||
version: '1.0.3',
|
||||
version: '1.0.4',
|
||||
apiVersion: 1,
|
||||
capabilities: ['commands', 'canvas', 'canvasWrite', 'nodeActions'],
|
||||
settings: {
|
||||
@@ -47,7 +47,7 @@
|
||||
},
|
||||
}, function (ctx) {
|
||||
async function cutoutOne(nodeId) {
|
||||
const image = await ctx.canvas.getNodeImage(nodeId)
|
||||
const image = await ctx.canvas.getNodeImage(nodeId, { max: 2048 }) // v: 抠图封顶 2048
|
||||
if (!image || !image.dataUrl) throw new Error('该节点没有可编码的图片(请选中带图的参考图或输出节点)')
|
||||
|
||||
const apiUrl = trimUrl(ctx.settings.get('apiUrl'))
|
||||
|
||||
Reference in new issue
Block a user