Compare commits

...
Author SHA1 Message Date
qiqi a923834595 feat(album): 1.1.2 看大图支持左右切换(整本相册循环浏览)
validate / validate (push) Canceled after 0s
宿主 props.onPreview 只收「已解析好的 URL 列表」:要切换就得开窗前把整本相册
的原图全部转成 dataURL(30 张 4K 图 = 几十上百 MB,还会卡主线程)。因此改成
插件自带全屏查看器,挂在 document.body:

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

测试:静态 harness 增 14 项断言;新增 album/tools/viewer-e2e.mjs(Chromium
真浏览器 22 项:开/关、键盘与按钮、循环、滚轮、单图、监听清理、复制下载)。
npm test 全过。
2026-11-25 10:32:10 +08:00
6 changed files with 392 additions and 32 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@iwb-plugin/album",
"private": true,
"version": "1.1.1",
"version": "1.1.2",
"description": "相册:一个节点装多张本地图(只引用不复制),宫格自适应分页,一图一任务 / 批量两种模式批量生图",
"ibwPlugin": {
"id": "album",
+170 -22
View File
@@ -377,11 +377,11 @@
update(st.props, st.node, { items: items, page: Math.min(pageNow, pagesNow - 1) }, true)
})
btn.appendChild(del)
// 放大镜(右下角):点击 → 宿主全屏预览。1.1.1 去掉了 hover 预览(会盖住放大镜导致点不到,
// 用户实测),只留「点一下看大图」这一条路径:宿主预览点图片外的空白或按 Esc 自动退出。
const zoom = el('span', { className: 'iwb-album-zoom', title: '查看大图(点击空白处或按 Esc 关闭)' }, zoomIcon())
// 放大镜(右下角):点开插件自带的全屏查看器,可 ← → 切换整本相册(1.1.2)。
// 1.1.1 的 hover 预览已废(那层会盖住放大镜本身)。
const zoom = el('span', { className: 'iwb-album-zoom', title: '查看大图(← → 切换,点击空白处或 Esc 关闭)' }, zoomIcon())
zoom.addEventListener('pointerdown', (e) => e.stopPropagation())
zoom.addEventListener('click', (e) => { e.stopPropagation(); openFull(ctx, st, it) })
zoom.addEventListener('click', (e) => { e.stopPropagation(); openFull(ctx, st, index) })
btn.appendChild(zoom)
btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btn.addEventListener('click', (e) => {
@@ -475,23 +475,170 @@
return thumb
}
// ── 看大图:只走宿主全屏预览(1.1.1 定了唯一交互)────────────
// 历史:1.1.0 曾做「hover 放大镜 → 节点框内浮大图(pointer-events:none)+ 点击全屏」两套。
// 实测否决:hover 一进就把整块节点压暗(预览层 z-index 9),放大镜本身被盖在下面 ⇒
// 用户看到的是「滑过去就不能点了」。现在删掉 A,只保留 B:
// 点放大镜 → props.onPreview 打开宿主预览层(铺满窗口);
// 点图片外的空白 / 按 Esc → 宿主自己 onClose(见 src/ui-canvas-view.js 的 ImagePreview)。
// 代价是「看一眼」也要点两下,但少一层状态,点到哪就是哪,不会再互相打架。
function openFull (ctx, st, it) {
const props = st.props || {}
if (typeof props.onPreview !== 'function') return
const fallback = st.thumbs.get(thumbKeyOf(it)) || ''
const run = (url) => { try { props.onPreview(url || fallback) } catch (e) { /* ignore */ } }
if (!ctx.images || typeof ctx.images.dataUrl !== 'function') { run(fallback); return }
try {
// 先给缩略图/原图都行,宿主预览层会再按需解析;读盘失败退回缩略图
Promise.resolve(ctx.images.dataUrl(it && it.src)).then((u) => run(u)).catch(() => run(''))
} catch (e) { run(fallback) }
// ── 看大图:插件自带全屏查看器(1.1.2 起支持 ← → 切换)──────────
// 历史:1.1.0 做过「hover 节点内浮大图 + 点击全屏」两套,hover 层把放大镜盖住了 ⇒ 1.1.1 删掉。
// 1.1.2:宿主 props.onPreview 只收「已解析好的 URL 列表」,一本 30 张的相册要左右切换,
// 就得开窗前把 30 张原图全转成 dataURL(几十上百 MB,还可能卡住主线程)。所以改成自建查看器:
// 只解码当前这张 + 预取左右各一张(最多 3 张常驻),切换即时、内存可控。
// 交互沿用宿主那套肌肉记忆:点图片外的空白 / Esc 退出,← → 切换,滚轮也切。
const FS_KEEP = 3 // 同时保留的原图张数(当前 + 左右各一)
function closeViewer (st) {
const v = st && st.viewer
if (!v) return
st.viewer = null
try { window.removeEventListener('keydown', v.onKey, true) } catch (e) { /* ignore */ }
try { window.removeEventListener('wheel', v.onWheel, true) } catch (e) { /* ignore */ }
if (v.root && v.root.parentNode) v.root.parentNode.removeChild(v.root)
}
function openFull (ctx, st, index) {
closeViewer(st)
const items = itemsOf(st.node)
const total = items.length
if (!total) return
const pick = (i) => items[((i % total) + total) % total]
const keyAt = (i) => thumbKeyOf(pick(i))
let cur = Math.max(0, Math.min(total - 1, Number(index) || 0))
let curUrl = '' // 当前显示图的地址(复制/下载用)
let token = 0
const cache = new Map() // key → 原图 URL
const pending = new Map() // key → Promise(预取与切页会同时要同一张)
const img = el('img', { alt: '', draggable: 'false' })
const count = el('span', { className: 'iwb-album-fs-count' })
const name = el('span', { className: 'iwb-album-fs-name' })
const btnCopy = el('button', { className: 'iwb-album-fs-btn', title: '复制当前图片到剪贴板(PNG)' }, '复制')
const btnDl = el('button', { className: 'iwb-album-fs-btn', title: '下载当前图片' }, '下载')
const bar = el('div', { className: 'iwb-album-fs-bar' }, [count, name, btnCopy, btnDl])
const hint = el('div', { className: 'iwb-album-fs-hint' }, '点击空白处或按 Esc 关闭 · ← → 切换')
const btnPrev = el('button', { className: 'iwb-album-fs-nav prev', title: '上一张(←)' }, '‹')
const btnNext = el('button', { className: 'iwb-album-fs-nav next', title: '下一张(→)' }, '›')
const root = el('div', { className: 'iwb-album-fs' + (total > 1 ? '' : ' single') }, [img, btnPrev, btnNext, bar, hint])
// 原图按需读:命中缓存直接用;读盘失败就保持缩略图(不白屏、不报错)
const fullOf = (i) => {
const it = pick(i)
const key = keyAt(i)
if (cache.has(key)) return Promise.resolve(cache.get(key))
const flight = pending.get(key)
if (flight) return flight
if (!ctx.images || typeof ctx.images.dataUrl !== 'function') return Promise.resolve('')
const p = Promise.resolve(ctx.images.dataUrl(it && it.src)).then((u) => {
pending.delete(key)
if (!u) return ''
cache.set(key, u)
// 只留当前 + 左右各一张:4K 图的 dataURL 一张就几 MB,全书缓存直接爆内存
const keep = new Set([keyAt(cur), keyAt(cur + 1), keyAt(cur - 1)])
if (cache.size > FS_KEEP) for (const k of Array.from(cache.keys())) if (!keep.has(k)) cache.delete(k)
return u
}).catch(() => { pending.delete(key); return '' })
pending.set(key, p)
return p
}
const paint = (i) => {
const it = pick(i)
const my = ++token
const cached = cache.get(keyAt(i))
const thumb = st.thumbs.get(keyAt(i)) || ''
// 先用缩略图占位(切换时不会闪一块黑),原图到了再换上;缩略图也还没好就现做
if (cached) { img.src = cached; curUrl = cached }
else if (thumb) { img.src = thumb; curUrl = thumb }
else {
img.removeAttribute('src'); curUrl = ''
loadThumb(ctx, st, it, keyAt(i)).then((u) => { if (u && my === token) { img.src = u; curUrl = u } }).catch(() => {})
}
fullOf(i).then((u) => { if (u && my === token) { img.src = u; curUrl = u } }).catch(() => {})
count.textContent = (i + 1) + ' / ' + total
name.textContent = (it && it.name) || ('图 ' + (i + 1))
if (total > 1) { fullOf(i + 1).catch(() => {}); fullOf(i - 1).catch(() => {}) }
}
const go = (delta) => { cur = ((cur + delta) % total + total) % total; paint(cur) }
const close = () => closeViewer(st)
img.addEventListener('pointerdown', (e) => e.stopPropagation())
img.addEventListener('click', (e) => e.stopPropagation())
for (const [btn, delta] of [[btnPrev, -1], [btnNext, 1]]) {
btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btn.addEventListener('click', (e) => { e.stopPropagation(); go(delta) })
}
// 复制 / 下载:宿主预览层原本有这两个按钮,不能因为换成自建查看器就丢掉
const flash = (msg) => {
hint.textContent = msg
clearTimeout(flash.timer)
flash.timer = setTimeout(() => { hint.textContent = '点击空白处或按 Esc 关闭 · ← → 切换' }, 1800)
}
const toPngBlob = (url) => new Promise((resolve, reject) => {
const im = new Image()
im.onload = () => {
try {
const cv = document.createElement('canvas')
cv.width = im.naturalWidth || 1; cv.height = im.naturalHeight || 1
cv.getContext('2d').drawImage(im, 0, 0)
cv.toBlob((b) => b ? resolve(b) : reject(new Error('toBlob 失败')), 'image/png')
} catch (e) { reject(e) }
}
im.onerror = () => reject(new Error('图片加载失败'))
im.src = url
})
for (const btn of [btnCopy, btnDl]) btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btnDl.addEventListener('click', (e) => {
e.stopPropagation()
if (!curUrl) return
try {
const a = document.createElement('a')
a.href = curUrl
a.download = (pick(cur) && pick(cur).name) || ('image-' + (cur + 1) + '.png')
document.body.appendChild(a); a.click()
if (a.parentNode) a.parentNode.removeChild(a)
} catch (err) { flash('下载失败:' + String((err && err.message) || err)) }
})
btnCopy.addEventListener('click', async (e) => {
e.stopPropagation()
if (!curUrl) return
try {
const png = await toPngBlob(curUrl)
if (navigator.clipboard && typeof navigator.clipboard.write === 'function' && typeof ClipboardItem !== 'undefined') {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
} else {
// WKWebView 常没有 ClipboardItem ⇒ 走宿主的原生 arboard 通道(与图库预览同一实现)
const D = window.IWBDesktop
if (!D || !D.clipboardWriteImage || !(await D.clipboardWriteImage(png))) throw new Error('当前环境不支持图片剪贴板')
}
flash('已复制图片到剪贴板(PNG)')
} catch (err) { flash('复制失败:' + String((err && err.message) || err)) }
})
// 整个浮层吃掉指针事件:否则点空白会把画布的「取消选中/框选」一起触发
root.addEventListener('pointerdown', (e) => { e.stopPropagation(); if (e.target === root || e.target === bar) close() })
root.addEventListener('click', (e) => e.stopPropagation())
root.addEventListener('pointerup', (e) => e.stopPropagation())
root.addEventListener('dblclick', (e) => e.stopPropagation())
// 键盘:捕获阶段吃掉,避免宿主把 ← → 当成「微调节点」
const onKey = (e) => {
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close() }
else if (e.key === 'ArrowLeft') { e.preventDefault(); e.stopPropagation(); go(-1) }
else if (e.key === 'ArrowRight') { e.preventDefault(); e.stopPropagation(); go(1) }
}
// 滚轮也切(大图查看器的通用手势);40ms 节流,避免一次滑到底翻好几张
let wheelLock = 0
const onWheel = (e) => {
if (total < 2) return
e.preventDefault(); e.stopPropagation()
const now = Date.now()
if (now - wheelLock < 40) return
const d = Math.abs(e.deltaY) > Math.abs(e.deltaX) ? e.deltaY : e.deltaX
if (Math.abs(d) < 2) return
wheelLock = now
go(d > 0 ? 1 : -1)
}
document.body.appendChild(root)
paint(cur)
window.addEventListener('keydown', onKey, true)
window.addEventListener('wheel', onWheel, { passive: false, capture: true })
st.viewer = { root, onKey, onWheel }
}
// ── 一键清空 ────────────────────────────────────────────
@@ -500,6 +647,7 @@
if (!items.length) return
st.thumbs.clear(); st.pending.clear(); st.missing.clear()
st.checkedMissing = false // 清空后再导入要重新做一次失联检测
closeViewer(st) // 正在看大图时清空 ⇒ 先把浮层收掉(别留个没有数据的空查看器)
update(st.props, st.node, { items: [], page: 0, pageRange: null }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
@@ -664,7 +812,7 @@
global.IWBPluginHost.register({
id: 'album',
name: '相册',
version: '1.1.1',
version: '1.1.2',
apiVersion: 1,
capabilities: ['nodeTypes', 'images', 'files'],
settings: {
+17
View File
@@ -51,6 +51,23 @@
.iwb-album-cell:hover .iwb-album-zoom, .iwb-album-cell:focus-within .iwb-album-zoom { opacity: 1; }
.iwb-album-zoom:hover { color: var(--iwb-brand); }
.iwb-album-zoom svg { width: 12px; height: 12px; display: block; }
/* 全屏查看器(1.1.2):挂在 document.body 上,所以是 position: fixed + 自备层级。
810 = 宿主图片预览层(--iwb-z-preview: 800)之上一层,盖住画布但不抢系统弹窗。
为什么不用宿主 onPreview:那个接口只收「已解析好的 URL 列表」,整本相册要一次全转 dataURL。 */
.iwb-album-fs { position: fixed; inset: 0; z-index: 810; display: flex; align-items: center; justify-content: center; background: rgba(10, 12, 18, .92); cursor: zoom-out; }
.iwb-album-fs img { max-width: 92vw; max-height: 88vh; width: auto; height: auto; object-fit: contain; display: block; border-radius: 8px; box-shadow: 0 8px 40px rgba(0, 0, 0, .5); cursor: default; }
.iwb-album-fs-nav { position: fixed; top: 50%; transform: translateY(-50%); width: 46px; height: 64px; padding: 0; border: none; border-radius: 8px; background: rgba(255, 255, 255, .1); color: #fff; font-size: 30px; line-height: 1; display: flex; align-items: center; justify-content: center; cursor: pointer; }
.iwb-album-fs-nav:hover { background: rgba(255, 255, 255, .22); }
.iwb-album-fs-nav.prev { left: 18px; }
.iwb-album-fs-nav.next { right: 18px; }
.iwb-album-fs.single .iwb-album-fs-nav { display: none; }
/* 计数条要放「复制/下载」按钮,所以本身吃事件;点条上空白仍然算点外部(关闭) */
.iwb-album-fs-bar { position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%); display: flex; align-items: center; gap: 10px; max-width: 80vw; padding: 6px 14px; border-radius: 999px; background: rgba(255, 255, 255, .12); color: #fff; font-size: 12px; }
.iwb-album-fs-btn { height: 22px; padding: 0 9px; border: 1px solid rgba(255, 255, 255, .22); border-radius: 999px; background: rgba(255, 255, 255, .08); color: #fff; font-size: 11px; cursor: pointer; flex: 0 0 auto; }
.iwb-album-fs-btn:hover { background: rgba(255, 255, 255, .22); }
.iwb-album-fs-count { font-variant-numeric: tabular-nums; }
.iwb-album-fs-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; opacity: .72; }
.iwb-album-fs-hint { position: fixed; left: 50%; bottom: 6px; transform: translateX(-50%); color: rgba(255, 255, 255, .45); font-size: 11px; white-space: nowrap; pointer-events: none; }
.iwb-album-add { border: 1px dashed var(--iwb-border); background: transparent; color: var(--iwb-node-text2); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--iwb-space-2); font-size: var(--iwb-font-2xs); border-radius: var(--iwb-radius-chip); cursor: pointer; }
.iwb-album-add b { font-size: 15px; line-height: 1; font-weight: 600; }
.iwb-album-pager { border-top: 1px solid color-mix(in srgb, var(--iwb-border) 55%, transparent); height: 26px; }
+32 -8
View File
@@ -30,8 +30,8 @@ const ok = (name, cond, extra) => {
}
// ── 一、版本与注册契约 ───────────────────────────────────────
ok('package.json version = 1.1.1', pkg.version === '1.1.1', pkg.version)
ok('manifest.version = 1.1.1', /version:\s*'1\.1\.1'/.test(src))
ok('package.json version = 1.1.2', pkg.version === '1.1.2', pkg.version)
ok('manifest.version = 1.1.2', /version:\s*'1\.1\.2'/.test(src))
ok('id = album', /id:\s*'album'/.test(src))
ok('capabilities 含 nodeTypes / images / files',
/capabilities:\s*\['nodeTypes',\s*'images',\s*'files'\]/.test(src))
@@ -137,18 +137,42 @@ ok('选中线 1px(用户:2px 太粗)', /\.iwb-album-cell\.sel\s*\{[^}]*out
ok('失联虚线同步 1px', /\.iwb-album-cell\.missing\s*\{[^}]*outline:\s*1px dashed/.test(css))
ok('放大镜元素存在(右下角)', /className:\s*'iwb-album-zoom'/.test(src))
ok('放大镜点击进宿主全屏预览(props.onPreview)',
/zoom\.addEventListener\('click',[\s\S]{0,120}openFull\(ctx, st, it\)/.test(src) &&
/function openFull[\s\S]{0,700}props\.onPreview\(/.test(src))
// 1.1.1 用户裁定:**只保留点击全屏(B)**。hover 方案(A)实测把放大镜盖住了 ⇒ 滑过去点不到。
// 1.1.1 用户裁定:hover 方案(A)实测把放大镜盖住了 ⇒ 只留「点击看大图」。
ok('不再有 hover 预览(pointerenter 触发 showPreview)', !/pointerenter'[\s\S]{0,80}showPreview/.test(src))
ok('showPreview / hidePreview / 预览层代码彻底删除', !/function showPreview|function hidePreview/.test(src))
ok('showPreview / hidePreview / 节点内预览层代码彻底删除', !/function showPreview|function hidePreview|iwb-album-preview/.test(src + css))
ok('CSS 里没有节点内预览层(.iwb-album-preview)', !/iwb-album-preview/.test(css))
ok('放大镜 z-index 高于图片与角标(不再被任何浮层压住)',
/\.iwb-album-zoom\s*\{[^}]*z-index:\s*[1-9]/.test(css))
ok('放大镜在键盘聚焦时也可见(focus-within,不只 hover)',
/\.iwb-album-cell:focus-within \.iwb-album-zoom/.test(css))
ok('放大镜提示文案说明「点空白 / Esc 关闭」', /title:\s*'查看大图(点击空白处或按 Esc 关闭)'/.test(src))
ok('放大镜点击开查看器并带上 item 下标(整本相册可切换)',
/zoom\.addEventListener\('click',[\s\S]{0,120}openFull\(ctx, st, index\)/.test(src))
// 1.1.2:自带全屏查看器(宿主 onPreview 只收现成 URL 列表 ⇒ 整本要全转 dataURL,内存顶不住)
ok('查看器挂在 document.body(节点有 transform,inside 节点的 fixed 会错位)',
/document\.body\.appendChild\(root\)/.test(src))
ok('查看器自带左右按钮 + ← → 键盘切换',
/className:\s*'iwb-album-fs-nav prev'/.test(src) &&
/className:\s*'iwb-album-fs-nav next'/.test(src) &&
/e\.key === 'ArrowLeft'[\s\S]{0,120}go\(-1\)/.test(src) &&
/e\.key === 'ArrowRight'[\s\S]{0,120}go\(1\)/.test(src))
ok('循环切换(首尾相连,不会卡在最后一张)', /const go = \(delta\) => \{ cur = \(\(cur \+ delta\) % total \+ total\) % total/.test(src))
ok('点空白 / Esc 关闭', /if \(e\.target === root \|\| e\.target === bar\) close\(\)/.test(src) && /e\.key === 'Escape'[\s\S]{0,80}close\(\)/.test(src))
ok('原图只留 3 张(当前 + 左右预取),不整本缓存 4K dataURL',
/const FS_KEEP = 3/.test(src) && /cache\.size|keep = new Set\(\[keyAt\(cur\), keyAt\(cur \+ 1\), keyAt\(cur - 1\)\]\)/.test(src))
ok('先用缩略图占位再换原图(切页不闪黑)', /const thumb = st\.thumbs\.get\(keyAt\(i\)\) \|\| ''/.test(src))
ok('切页与预取并发去重(pending 表)', /const flight = pending\.get\(key\)/.test(src))
ok('键盘在捕获阶段吃掉(否则宿主把 ← → 当微调节点)',
/window\.addEventListener\('keydown', onKey, true\)/.test(src))
ok('关闭时摘掉键盘/滚轮监听(不残留全局监听)',
/removeEventListener\('keydown', v\.onKey, true\)/.test(src) && /removeEventListener\('wheel', v\.onWheel, true\)/.test(src))
ok('查看器层级在宿主预览层(800)之上', /\.iwb-album-fs\s*\{[^}]*z-index:\s*8[1-9][0-9]/.test(css))
ok('查看器带「复制 / 下载」(不因换查看器丢掉宿主预览原有能力)',
/iwb-album-fs-btn'/.test(src) && /'复制'/.test(src) && /'下载'/.test(src))
ok('复制转 PNG + 无 ClipboardItem 时走宿主原生通道',
/cv\.toBlob\([\s\S]{0,80}'image\/png'\)/.test(src) && /IWBDesktop[\s\S]{0,120}clipboardWriteImage/.test(src))
ok('查看器不再依赖宿主 props.onPreview(那接口要一次性给全 URL 列表)',
!/props\.onPreview\(/.test(src))
// ── 五、已修复的老 bug 必须有防回归断言 ───────────────────────
ok('批次角标彻底移除(右上角那个「1」是重复信息)',
+170
View File
@@ -0,0 +1,170 @@
#!/usr/bin/env node
/* album 全屏查看器「真浏览器」冒烟(1.1.2)
*
* 为什么要单独跑:查看器是挂在 document.body 上的全局浮层 + 全局键盘/滚轮监听,
* 静态断言只能证明「代码里有这些字符串」,证明不了点开、切页、Esc/空白关闭真的能跑。
* 这里用 Chromium 装一个合成宿主,加载插件源码本体,走完整交互。
*
* 运行:node album/tools/viewer-e2e.mjs
* 依赖 playwright(宿主仓 node_modules;或 IWB_PLAYWRIGHT_ROOT 指定目录)。
* 不进 npm test:跨仓依赖,CI 上不一定装得齐。
*/
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const ROOT = path.resolve(HERE, '..')
const src = readFileSync(path.join(ROOT, 'src/index.js'), 'utf8')
const css = readFileSync(path.join(ROOT, 'styles.css'), 'utf8')
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT,
'/Users/qiqi/open/github/image-workbench-desktop',
'/Users/qiqi/open/github/image-workbench-web', ROOT]) {
if (!base) continue
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch (e) { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright:请安装,或设 IWB_PLAYWRIGHT_ROOT=/path/to/repo')
process.exit(2)
}
let failed = 0
const ok = (name, cond, extra) => {
if (!cond) failed++
console.log((cond ? '✓ ' : '✗ ') + name + (cond ? '' : (' » ' + (extra == null ? '' : extra))))
}
const browser = await chromium.launch({ headless: true })
const page = await browser.newPage({ viewport: { width: 1100, height: 800 } })
page.on('pageerror', (e) => { failed++; console.log('✗ 页面脚本异常 » ' + e.message) })
await page.setContent('<!doctype html><html><head><meta charset="utf-8"></head><body style="margin:0"><div id="host" style="width:300px;height:470px;position:relative"></div></body></html>')
await page.addStyleTag({ content: css })
await page.evaluate(() => {
const colors = ['#e57373', '#81c784', '#64b5f6', '#ffd54f', '#ba68c8']
window.__urls = colors.map((c) => 'data:image/svg+xml;base64,' + btoa(
'<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" fill="' + c + '"/></svg>'))
window.__items = window.__urls.map((u, i) => ({ src: u, name: '图' + (i + 1) + '.svg', on: true }))
window.IWBPluginHost = {
register (meta, factory) {
window.__meta = meta
const ctx = {
nodes: { register (spec) { window.__spec = spec } },
images: {
canReference: () => false,
dataUrl: async (v) => String(v || ''),
thumb: () => '',
pick: async () => [],
stat: async () => ({ ok: true, exists: true }),
listImages: async () => [],
},
files: { get: async () => ({ ok: false }), put: async () => ({ ok: true }) },
settings: { get: () => true },
}
window.__ctx = ctx
factory(ctx)
},
}
})
await page.addScriptTag({ content: src })
await page.evaluate(() => {
window.__render = (items) => {
// 不清 host:宿主每次重渲染复用同一个容器,插件靠 STATE 增量更新;
// 这里手动清空会把插件的 root 摘掉,STATE 还拿着游离节点 ⇒ 界面空白(测试自身不能造这种场景)
const host = document.getElementById('host')
const node = { id: 'n1', w: 300, h: 470, data: { outKind: 'images', items: items, albumMode: 'per-image', density: 'S', page: 0, onlyPage: false } }
const props = { onUpdate () {}, onSnapshot () {}, onPreview (u) { window.__hostPreview = u } }
window.__spec.render(node, props, host)
}
window.__render(window.__items)
})
try {
await page.waitForFunction(() => document.querySelectorAll('.iwb-album-cell').length >= 5, null, { timeout: 10000 })
} catch (e) {
console.log('DEBUG host =', (await page.evaluate(() => document.getElementById('host').innerHTML)).slice(0, 1200))
console.log('DEBUG meta =', await page.evaluate(() => JSON.stringify(window.__meta)))
console.log('DEBUG spec =', await page.evaluate(() => String(window.__spec && window.__spec.id)))
throw e
}
// 1) 点放大镜 → 全屏查看器
await page.locator('.iwb-album-zoom').first().click({ force: true })
await page.waitForFunction(() => document.querySelectorAll('.iwb-album-fs').length === 1)
ok('点放大镜开出全屏查看器', true)
ok('计数显示 1 / 5', await page.locator('.iwb-album-fs-count').textContent() === '1 / 5')
ok('原图异步换上(不是只显示缩略图)', await page.waitForFunction(
() => { const im = document.querySelector('.iwb-album-fs img'); return !!im && (im.getAttribute('src') || '').indexOf('data:image/svg+xml') === 0 },
null, { timeout: 5000 }).then(() => true).catch(() => false))
ok('左右箭头按钮都渲染出来了', await page.locator('.iwb-album-fs-nav').count() === 2)
// 2) 键盘切换(含首尾循环)
await page.keyboard.press('ArrowRight')
ok('→ 切到第 2 张', await page.locator('.iwb-album-fs-count').textContent() === '2 / 5')
await page.keyboard.press('ArrowLeft')
await page.keyboard.press('ArrowLeft')
ok('← 从第 1 张循环到最后一张', await page.locator('.iwb-album-fs-count').textContent() === '5 / 5')
await page.keyboard.press('ArrowRight')
ok('再从最后一张循环回第 1 张', await page.locator('.iwb-album-fs-count').textContent() === '1 / 5')
// 3) 按钮 / 滚轮切换
await page.locator('.iwb-album-fs-nav.next').click()
ok('下一张按钮生效', await page.locator('.iwb-album-fs-count').textContent() === '2 / 5')
await page.mouse.move(550, 400)
await page.mouse.wheel(0, 120)
await page.waitForTimeout(80)
ok('滚轮向下切一张', await page.locator('.iwb-album-fs-count').textContent() === '3 / 5')
// 3b) 宿主预览原有的「复制 / 下载」能力不能丢
ok('查看器带复制 / 下载按钮', await page.locator('.iwb-album-fs-btn').count() === 2)
await page.locator('.iwb-album-fs-btn').nth(1).click()
ok('点下载不会把查看器关掉', await page.locator('.iwb-album-fs').count() === 1)
await page.locator('.iwb-album-fs-btn').first().click()
await page.waitForTimeout(120)
ok('点复制不会报错 / 不关闭(无剪贴板权限时也只给提示)', await page.locator('.iwb-album-fs').count() === 1)
// 4) 点空白关闭;键盘监听要摘干净(关掉后再按 → 不能影响画布)
await page.mouse.click(8, 8)
ok('点图片外的空白关闭', await page.locator('.iwb-album-fs').count() === 0)
ok('关闭后画布没有被误删格子', await page.locator('.iwb-album-cell').count() === 6)
await page.locator('.iwb-album-zoom').first().click({ force: true })
await page.keyboard.press('Escape')
ok('Esc 关闭', await page.locator('.iwb-album-fs').count() === 0)
await page.keyboard.press('ArrowRight')
ok('关闭后不再残留键盘监听(→ 不报错、不重建浮层)', await page.locator('.iwb-album-fs').count() === 0)
// 5) 只有一张图时不显示左右按钮
await page.evaluate(() => window.__render([window.__items[0]]))
try {
await page.waitForFunction(() => document.querySelectorAll('.iwb-album-cell').length === 2, null, { timeout: 5000 })
} catch (e) {
console.log('DEBUG single host =', (await page.evaluate(() => document.getElementById('host').innerHTML)).slice(0, 600))
console.log('DEBUG cells =', await page.evaluate(() => document.querySelectorAll('.iwb-album-cell').length))
throw e
}
await page.locator('.iwb-album-zoom').first().click({ force: true })
const single = await page.evaluate(() => {
const root = document.querySelector('.iwb-album-fs')
const nav = document.querySelector('.iwb-album-fs-nav')
return { cls: root && root.className, display: nav ? getComputedStyle(nav).display : 'missing' }
})
ok('单图查看器隐藏左右按钮', (single.cls || '').indexOf('single') >= 0 && single.display === 'none', JSON.stringify(single))
ok('单图计数 1 / 1', await page.locator('.iwb-album-fs-count').textContent() === '1 / 1')
await page.mouse.click(8, 8)
// 6) 查看器挂到 body(不是节点里),事件不会穿透到画布
const inBody = await page.evaluate(() => {
window.__render(window.__items)
document.querySelector('.iwb-album-zoom').click()
const root = document.querySelector('.iwb-album-fs')
return !!root && root.parentNode === document.body
})
ok('浮层挂在 document.body(不受节点 transform 影响)', inBody)
ok('开启查看器没有走宿主 props.onPreview', await page.evaluate(() => typeof window.__hostPreview === 'undefined'))
await page.keyboard.press('Escape')
await browser.close()
console.log('\n' + (failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+2 -1
View File
@@ -7,7 +7,8 @@
"validate": "node scripts/validate.mjs",
"build": "node scripts/build-plugin.mjs",
"test": "npm run validate && npm run test:album",
"test:album": "node album/tools/harness.mjs"
"test:album": "node album/tools/harness.mjs",
"test:album:e2e": "node album/tools/viewer-e2e.mjs"
},
"devDependencies": {
"esbuild": "^0.24.2"