feat(plugin): 同步 gallery 1.6.0(搜索/失败统计/右键菜单/多选拖拽)+ 交互回归

This commit is contained in:
qiqi committed 2026-11-20 14:20:53 +08:00
1 parent 999dbf7fd9
commit f8ecb2cfba
7 files changed
+299 -16

No files matched your search

+1 -1
View File
@@ -41,7 +41,7 @@ build esbuild 打包到 dist/(单 dist/app.js = src/ 模块按序
node --check app.js 与 dist/app.js 语法
check-dist.js 产物体检
lint ESLint(src/ + app.js,正确性规则)
test:unit 107 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test:unit 108 个单测文件(jsdom 契约测试;2026-11-07 新增 sync-facts-guard(事实一致性)/ _helpers/source(统一源文本);2026-11-12 新增 provider-ping(测速 no-cors 兜底))
test relay-task-graph-fixture + iwb-v32-web-test
test:facts 事实基线守门(见 §5)
typecheck 渐进类型检查(tsc --noEmit;范围 = src/*.js,不含 app.js)
+1 -1
View File
@@ -10,7 +10,7 @@
"app:build": "tauri build",
"lint": "eslint src app.js",
"test": "node tests/relay-task-graph-fixture-test.js && node tests/plugin-style-node-test.js && node tests/inherit-text-test.js",
"test:unit": "node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js",
"test:unit": "node tests/unit-test.js && node tests/canvas-actions-test.js && node tests/canvas-performance-test.js && node tests/canvas-drag-performance-test.js && node tests/resize-observer-performance-test.js && node tests/node-drag-jank-test.js && node tests/edge-graph-performance-test.js && node tests/persistence-export-images-test.js && node tests/settings-hotkeys-size-presets-test.js && node tests/custom-size-validation-test.js && node tests/image-node-performance-test.js && node tests/drag-frame-performance-test.js && node tests/canvas-edge-memo-test.js && node tests/canvas-node-transform-test.js && node tests/canvas-dot-zoom-test.js && node tests/duplicate-ws-fresh-source-test.js && node tests/single-canvas-shell-test.js && node tests/navigation-layout-test.js && node tests/home-canvas-library-test.js && node tests/left-resource-layout-test.js && node tests/interface-hierarchy-test.js && node tests/three-page-layout-test.js && node tests/page-chrome-regression-test.js && node tests/task-cache-test.js && node tests/storage-config-shape-test.js && node tests/storage-zip-test.js && node tests/canvas-node-factory-test.js && node tests/runtime-error-test.js && node tests/runtime-lifecycle-test.js && node tests/runtime-fetch-test.js && node tests/runtime-channel-test.js && node tests/runtime-boundary-test.js && node tests/runtime-record-test.js && node tests/runtime-recovery-test.js && node tests/runtime-diagnostic-record-test.js && node tests/runtime-metrics-test.js && node tests/runtime-run-context-test.js && node tests/runtime-execution-context-test.js && node tests/storage-gc-canvas-refs-test.js && node tests/storage-health-test.js && node tests/generation-state-test.js && node tests/canvas-store-test.js && node tests/storage-result-test.js && node tests/storage-local-test.js && node tests/storage-domain-test.js && node tests/storage-runtime-test.js && node tests/storage-indexeddb-test.js && node tests/generation-scheduler-test.js && node tests/gallery-query-test.js && node tests/gallery-hydration-test.js && node tests/image-blob-store-test.js && node tests/image-preview-derive-test.js && node tests/image-format-test.js && node tests/clipboard-graph-test.js && node tests/clipboard-graph-fallback-test.js && node tests/image-admit-test.js && node tests/image-dedupe-test.js && node tests/clipboard-kind-test.js && node tests/clipboard-paste-test.js && node tests/clipboard-copy-test.js && node tests/paste-once-test.js && node tests/list-e2e-specs-test.js && node tests/desktop-csp-loopback-test.js && node tests/architecture-boundary-guard-test.js && node tests/plugin-host-test.js && node tests/plugin-data-test.js && node tests/plugin-loader-test.js && node tests/plugin-bundle-test.js && node tests/plugin-install-test.js && node tests/plugin-gallery-render-test.js && node tests/plugin-gallery-recovery-test.js && node tests/plugin-gallery-ux-test.js && node tests/plugin-grouplib-render-test.js && node tests/plugin-promptlib-render-test.js && node tests/image-compress-test.js && node tests/storage-fallback-indexeddb-test.js && node tests/canvas-normalize-test.js && node tests/canvas-geometry-test.js && node tests/canvas-history-test.js && node tests/canvas-ops-test.js && node tests/canvas-text-test.js && node tests/history-store-test.js && node tests/plugin-integrity-test.js && node tests/workspace-sessions-store-test.js && node tests/workspace-list-test.js && node tests/workspace-purge-test.js && node tests/provider-ping-test.js && node tests/runtime-diagnostics-hotpath-test.js && node tests/storage-log-failure-test.js && node tests/storage-convergence-test.js && node tests/swallow-wiring-test.js && node tests/workbench-logic-test.js && node tests/storage-autobackup-test.js && node tests/storage-outputs-mutate-test.js && node tests/sync-facts-guard-test.js && node tests/e2e-fixed-waits-ratchet-test.js && node tests/shell-render-behavior-test.js && node tests/canvas-meta-notice-behavior-test.js && node tests/source-text-ratchet-test.js && node tests/prompt-md-roundtrip-test.js && node tests/generation-results-store-test.js && node tests/out-groups-order-test.js && node tests/ui-workbench-hooks-test.js",
"test:diagnostics": "node tests/runtime-diagnostics-hotpath-test.js",
"test:facts": "node tests/architecture-facts-guard-test.js && node tests/release-records-test.js",
"plugins:gc": "node scripts/plugins-publish.mjs --gc",
+127 -7
View File
@@ -83,8 +83,18 @@
var picked = {}
var gridW = 320
var raf = 0
var query = '' // v1.6.0:搜索(名称/标签),不持久化,重开面板即清空
var failed = {} // v1.6.0:缩略图仍失败的 name 集合(据此显示「N 张失败」+ 全部重试)
var head = el('div', { class: 'iwb-gal-head' })
var searchIn = el('input', { class: 'iwb-input iwb-gal-search', placeholder: '搜索图片名…', value: '' })
var searchTimer = 0
searchIn.addEventListener('input', function () {
query = searchIn.value
clearTimeout(searchTimer)
searchTimer = setTimeout(function () { limit = 100; load() }, 220)
})
head.appendChild(searchIn)
var actions = el('div', { class: 'iwb-gal-actions' })
head.appendChild(actions)
@@ -95,6 +105,9 @@
var countEl = el('span', { class: 'iwb-gal-count', text: '0 / 0 张' })
var pickedEl = el('span', { class: 'iwb-gal-sel', text: '' })
var statusEl = el('span', { class: 'iwb-gal-status', text: '' })
var failEl = el('span', { class: 'iwb-gal-fail', text: '' })
failEl.style.display = 'none'
failEl.addEventListener('click', function () { retryAll() })
var refreshBtn = iconBtn('刷新', function (svg) {
svgPath(svg, 'M13.2 6.4A5.4 5.4 0 1 0 13.4 9.4')
svgPath(svg, 'M13.2 2.6v3.8H9.4')
@@ -124,7 +137,7 @@
// v1.4.2:刷新与设置同放右侧工具组(此前刷新在左侧信息区,空间不足时会向右溢出、压住设置图标)
var tools = el('div', { class: 'iwb-gal-tools' }, refreshBtn, setBtn)
var foot = el('div', { class: 'iwb-gal-foot' },
el('div', { class: 'iwb-gal-foot-left' }, countEl, pickedEl, statusEl), tools)
el('div', { class: 'iwb-gal-foot-left' }, countEl, pickedEl, failEl, statusEl), tools)
var wrap = el('div', { class: 'iwb-history-embedded' }, [head, grid, more, empty, foot, settings])
function setOpen (open) {
@@ -142,6 +155,91 @@
host.appendChild(wrap)
function count () { return Object.keys(picked).length }
// ---- v1.6.0 右键菜单:单张操作(插入 / 下载 / 预览 / 复制文件名 / 删除)----
var menuEl = null
function closeMenu () {
if (menuEl && menuEl.parentNode) menuEl.parentNode.removeChild(menuEl)
menuEl = null
document.removeEventListener('pointerdown', onMenuDown, true)
document.removeEventListener('keydown', onMenuKey, true)
}
function onMenuDown (e) { if (menuEl && !menuEl.contains(e.target)) closeMenu() }
function onMenuKey (e) { if (e.key === 'Escape') closeMenu() }
function openMenu (e, it) {
e.preventDefault(); e.stopPropagation()
closeMenu()
var menu = el('div', { class: 'iwb-ctxmenu iwb-gal-menu', style: 'left:' + e.clientX + 'px;top:' + e.clientY + 'px' })
menu.appendChild(el('div', { class: 'iwb-ctx-title', text: it.name }))
function item (label, fn) {
var b = el('button', { class: 'iwb-ctx-item', text: label })
b.addEventListener('click', function (ev) { ev.stopPropagation(); closeMenu(); fn() })
menu.appendChild(b)
}
item('插入画布', function () {
Promise.resolve(ctx.gallery.insert([it.name], { insertK: cfg.insertK || '1k' }))
.then(function () { setStatus('已插入:' + it.name) })
.catch(function () { setStatus('插入失败') })
})
item('下载', function () { doDownload([it.name]) })
item('预览大图', function () { try { ctx.gallery.preview(it.name) } catch (err) { /* ignore */ } })
item('复制文件名', function () {
try {
var p = global.navigator && global.navigator.clipboard && global.navigator.clipboard.writeText(it.name)
if (p && p.then) p.then(function () { setStatus('已复制文件名') }).catch(function () { setStatus('复制失败(剪贴板不可用)') })
else setStatus('复制失败(剪贴板不可用)')
} catch (err) { setStatus('复制失败(剪贴板不可用)') }
})
item('删除这张', function () {
var C = global.IWBUIConfirm
var ask = (C && C.askOrNative) ? C.askOrNative('删除「' + it.name + '」?不可恢复。', { title: '删除图片', okText: '删除' }) : Promise.resolve(global.confirm('删除「' + it.name + '」?'))
ask.then(function (ok) {
if (!ok) return
items = items.filter(function (x) { return x.name !== it.name })
total = Math.max(0, total - 1)
delete picked[it.name]
render()
Promise.resolve(ctx.gallery.remove([it.name])).then(function () { setTimeout(load, 250) }).catch(function () {})
}).catch(function () {})
})
document.body.appendChild(menu)
menuEl = menu
setTimeout(function () {
document.addEventListener('pointerdown', onMenuDown, true)
document.addEventListener('keydown', onMenuKey, true)
}, 0)
}
// ---- v1.6.0 多选拖入画布:宿主 drop 只认单张,这里在捕获阶段接管整批 ----
// 仅当 dataTransfer 带 application/x-iwb-gallery-batch 时生效,其余拖放行为完全不变。
function onDocDrop (e) {
var raw = ''
try { raw = (e.dataTransfer && e.dataTransfer.getData('application/x-iwb-gallery-batch')) || '' } catch (err) { return }
if (!raw) return
var names = []
try { names = JSON.parse(raw) } catch (err) { return }
if (!names || names.length < 2) return
e.preventDefault(); e.stopPropagation()
Promise.resolve(ctx.gallery.insert(names, { insertK: cfg.insertK || '1k' })).then(function (r) {
if (r && r.ok === false) { setStatus('批量插入失败'); return }
setStatus('已插入 ' + names.length + ' 张')
}).catch(function () { setStatus('批量插入失败') })
}
document.addEventListener('drop', onDocDrop, true)
// v1.6.0:失败计数集中在底栏;点它 = 全部重试(整墙重挂,重新向宿主取缩略图)
function updateFail () {
var n = Object.keys(failed).length
if (!n) { failEl.style.display = 'none'; failEl.textContent = ''; return }
failEl.style.display = ''
failEl.textContent = n + ' 张失败 · 重试'
failEl.title = '点击重新加载这 ' + n + ' 张的缩略图'
}
function retryAll () {
failed = {}
updateFail()
setStatus('重试中…')
render()
}
function pickedNames () { return Object.keys(picked) }
function renderHead () {
@@ -156,6 +254,14 @@
}
actions.appendChild(btn('全选', '全选当前筛选结果', function () { for (var i = 0; i < items.length; i++) picked[items[i].name] = 1; render() }))
actions.appendChild(btn('反选', '反选当前筛选结果', function () { for (var i = 0; i < items.length; i++) { var k = items[i].name; if (picked[k]) delete picked[k]; else picked[k] = 1 } render() }))
actions.appendChild(btn('插入', '把选中的图片插入画布(尺寸按「设置 → 插入尺寸」)', function () {
var names = pickedNames()
var k = cfg.insertK || '1k'
Promise.resolve(ctx.gallery.insert(names, { insertK: k })).then(function (r) {
if (r && r.ok === false) { setStatus('插入失败'); return }
setStatus('已插入 ' + names.length + ' 张(' + String(k).toUpperCase() + ')')
}).catch(function () { setStatus('插入失败') })
}, true))
actions.appendChild(btn('下载', '下载选中的图片', function () { doDownload(pickedNames()) }, true))
actions.appendChild(btn('删除', '删除选中的图片(不可恢复)', function () {
var C = global.IWBUIConfirm
@@ -237,7 +343,9 @@
function fail (text) {
holder.textContent = text || '缩略图加载失败(点击重试)'
holder.style.cursor = 'pointer'
holder.onclick = function () { tries = 0; boot() }
holder.onclick = function () { failed[it.name] = 1; tries = 0; boot() }
failed[it.name] = 1
updateFail()
}
function boot () {
holder.style.cursor = ''
@@ -252,6 +360,7 @@
// naturalWidth=0 说明拿到的是坏图(空 data URL / 截断文件):按失败处理,别留白块
if (!img.naturalWidth) { tries++; if (tries <= 2) { setTimeout(boot, 400 * tries); return } if (img.parentNode === box) box.replaceChild(holder, img); fail('缩略图加载失败(点击重试)'); return }
if (holder.parentNode === box) box.replaceChild(img, holder)
if (failed[it.name]) { delete failed[it.name]; updateFail() }
})
img.addEventListener('error', function () {
tries++
@@ -263,8 +372,14 @@
img.addEventListener('dblclick', function () { ctx.gallery.preview(it.name) })
img.addEventListener('dragstart', function (e) {
try {
e.dataTransfer.setData('application/x-iwb-localref', it.name)
e.dataTransfer.setData('application/x-iwb-gallery-orig', it.name)
var names = (picked[it.name] && count() > 1) ? pickedNames() : [it.name]
e.dataTransfer.setData('application/x-iwb-localref', names[0])
e.dataTransfer.setData('application/x-iwb-gallery-orig', names[0])
// 多选:额外带一批名字,由本插件在 document 捕获阶段接管(宿主 drop 只认单张)
if (names.length > 1) {
e.dataTransfer.setData('application/x-iwb-gallery-batch', JSON.stringify(names))
setStatus('拖动 ' + names.length + ' 张')
}
e.dataTransfer.effectAllowed = 'copy'
} catch (err) { /* ignore */ }
})
@@ -276,6 +391,7 @@
}).catch(function () { fail('缩略图加载失败(点击重试)') })
}
boot()
box.addEventListener('contextmenu', function (e) { openMenu(e, it) })
var acts = el('div', { class: 'iwb-history-actions' })
function act (label, title, fn) {
var b = el('button', { class: 'iwb-btn iwb-btn-sm', text: label, title: title })
@@ -313,10 +429,11 @@
function load (force) {
if (force) setStatus('刷新中…')
return Promise.resolve(ctx.gallery.list({ range: cfg.range, limit: limit })).then(function (r) {
return Promise.resolve(ctx.gallery.list({ query: query, range: cfg.range, limit: limit })).then(function (r) {
items = (r && r.items) || []
total = (r && r.total) || items.length
lastLoadAt = Date.now()
failed = {}
render()
}).catch(function () { items = []; total = 0; render() })
}
@@ -365,14 +482,17 @@
return function dispose () {
if (ro) { try { ro.disconnect() } catch (e) { /* ignore */ } }
try { document.removeEventListener('pointerdown', onDocDown, true) } catch (e) { /* ignore */ }
try { document.removeEventListener('pointerdown', onMenuDown, true) } catch (e) { /* ignore */ }
try { document.removeEventListener('keydown', onMenuKey, true) } catch (e) { /* ignore */ }
try { document.removeEventListener('drop', onDocDrop, true) } catch (e) { /* ignore */ }
closeMenu()
}
}
global.IWBPluginHost.register({
id: 'gallery',
name: '图库',
version: '1.5.1',
version: '1.6.0',
apiVersion: 1,
capabilities: ['panels', 'gallery'],
data: { schemaVersion: 1, maxBytes: 65536 },
+3 -3
View File
@@ -1,7 +1,7 @@
{
"id": "gallery",
"name": "图库",
"version": "1.5.1",
"version": "1.6.0",
"apiVersion": 1,
"main": "main.js",
"style": "styles.css",
@@ -13,7 +13,7 @@
"图库"
],
"files": {
"main.js": "83ea7f97379bc9cf9cc70e83b1578b114b37607dccac96fcd729fe8ce0027a42",
"styles.css": "75fb6f379f2c94939e1de98c56082bc5cbef299283e7cc1325e569f3bfdd5f1f"
"main.js": "f8bb08df4ab051ebc21e4b8107c9980078396ab5bd5f7feda9a530f298c02c59",
"styles.css": "3d715b72321497afe23d9f34b2f6461e0b854012bb632b8f62ccd6da642e07c8"
}
}
+10 -1
View File
@@ -66,4 +66,13 @@
.iwb-history-actions .iwb-btn-sm { padding: 1px 6px; font-size: 10px; }
.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; }
.iwb-history-embedded .iwb-hint { font-size: 11px; color: var(--iwb-text2); text-align: center; padding: 12px 6px; }
/* ---- v1.6.0:搜索框 / 失败统计 / 右键菜单标题 ---- */
.iwb-gal-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.iwb-gal-search { flex: 1 1 90px; min-width: 60px; height: 24px; font-size: 12px; }
.iwb-gal-fail {
font-size: 11px; color: var(--iwb-err); cursor: pointer; white-space: nowrap;
text-decoration: underline dotted; text-underline-offset: 2px;
}
.iwb-gal-fail:hover { color: var(--iwb-err); opacity: .85; }
.iwb-gal-menu .iwb-ctx-title { max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+3 -3
View File
@@ -22,10 +22,10 @@
"dir": "gallery",
"main": "main.js",
"style": "styles.css",
"version": "1.5.1",
"version": "1.6.0",
"files": {
"main.js": "83ea7f97379bc9cf9cc70e83b1578b114b37607dccac96fcd729fe8ce0027a42",
"styles.css": "75fb6f379f2c94939e1de98c56082bc5cbef299283e7cc1325e569f3bfdd5f1f"
"main.js": "f8bb08df4ab051ebc21e4b8107c9980078396ab5bd5f7feda9a530f298c02c59",
"styles.css": "3d715b72321497afe23d9f34b2f6461e0b854012bb632b8f62ccd6da642e07c8"
}
},
{
+154
View File
@@ -0,0 +1,154 @@
'use strict'
// 图库插件 1.6.0 交互回归:搜索 / 失败统计+全部重试 / 右键菜单 / 多选拖拽
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const { JSDOM } = require('jsdom')
const src = fs.readFileSync(path.resolve(__dirname, '..', '..', 'iwb-plugins-desktop', 'gallery', 'src', 'index.js'), 'utf8')
const css = fs.readFileSync(path.resolve(__dirname, '..', '..', 'iwb-plugins-desktop', 'gallery', 'styles.css'), 'utf8')
const wait = (ms) => new Promise((r) => setTimeout(r, ms))
const GOOD = 'data:image/svg+xml;utf8,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="2" height="3"/>')
async function boot (opts) {
const dom = new JSDOM('<!doctype html><html><body><div id="host"></div></body></html>', { pretendToBeVisual: true })
const { window } = dom
window.ResizeObserver = class { observe () {} disconnect () {} }
window.confirm = () => true
const copied = []
Object.defineProperty(window.navigator, 'clipboard', { value: { writeText: (t) => { copied.push(t); return Promise.resolve() } }, configurable: true })
let reg = null
window.IWBPluginHost = { register (m, f) { reg = { m, f } } }
const sandbox = { window, document: window.document, console, setTimeout, clearTimeout, Promise, Object, Array, JSON, Math, Date, String, Number }
vm.runInNewContext(src, sandbox)
const style = window.document.createElement('style')
style.textContent = css
window.document.head.appendChild(style)
const calls = { list: [], insert: [], remove: [], preview: [] }
const items = opts.items
const ctx = {
ui: { registerPanel (p) { boot.panel = p } },
data: { read: async () => ({ cfg: {} }), patch: async () => true },
gallery: {
list: async (o) => { calls.list.push(o || {}); return { items: items.slice(), total: items.length } },
thumb: async (n) => opts.thumb(n),
preview: (n) => { calls.preview.push(n) },
insert: async (names, o) => { calls.insert.push([names.slice(), o]); return { ok: true } },
download: async () => ({ ok: true }),
remove: async (names) => { calls.remove.push(names.slice()); return { ok: true } },
},
}
reg.f(ctx)
const host = window.document.getElementById('host')
boot.panel.mount(host)
boot.panel = boot.panel
await wait(80)
return { window, document: window.document, host, calls, copied }
}
;(async () => {
// ---------- ① 搜索:输入 → 带 query 重新拉列表 ----------
{
const env = await boot({
items: [{ name: 'a.png', w: 200, h: 300 }, { name: 'b.png', w: 200, h: 120 }],
thumb: () => GOOD,
})
assert.strictEqual(env.calls.list.length, 1, '初次应拉一次')
assert.strictEqual(env.calls.list[0].query, '', '初次 query 应为空')
const search = env.host.querySelector('.iwb-gal-search')
assert.ok(search, '应有搜索框')
search.value = 'a.'
search.dispatchEvent(new env.window.Event('input', { bubbles: true }))
await wait(320) // 防抖 220ms
assert.strictEqual(env.calls.list.length, 2, '输入后应重新拉列表,实际 ' + env.calls.list.length)
assert.strictEqual(env.calls.list[1].query, 'a.', '应把搜索词传给宿主')
}
// ---------- ② 失败统计 + 全部重试 ----------
{
let broken = true
const env = await boot({
items: [{ name: 'ok.png', w: 200, h: 300 }, { name: 'bad.png', w: 200, h: 300 }],
thumb: (n) => (n === 'bad.png' && broken) ? null : GOOD,
})
const fail = env.host.querySelector('.iwb-gal-fail')
assert.ok(fail, '应有失败统计元素')
assert.notStrictEqual(fail.style.display, 'none', '有失败时应显示')
assert.ok(/1 张失败/.test(fail.textContent), '应显示「1 张失败」,实际 ' + fail.textContent)
broken = false
fail.dispatchEvent(new env.window.MouseEvent('click', { bubbles: true }))
await wait(120)
assert.strictEqual(fail.style.display, 'none', '全部重试成功后统计应消失')
// jsdom 不解码图片(img 一直 display:none 等 load),所以断言「不再有失败占位」而不是「看见图」
const stillFailed = Array.from(env.host.querySelectorAll('.iwb-history-missing')).filter((x) => /失败/.test(x.textContent))
assert.strictEqual(stillFailed.length, 0, '重试后不应再有失败占位,实际 ' + stillFailed.length)
assert.strictEqual(env.host.querySelectorAll('.iwb-history-item img').length, 2, '两张都应重新挂上 img')
}
// ---------- ③ 右键菜单 ----------
{
const env = await boot({ items: [{ name: 'a.png', w: 200, h: 300 }], thumb: () => GOOD })
const box = env.host.querySelector('.iwb-history-item')
box.dispatchEvent(new env.window.MouseEvent('contextmenu', { bubbles: true, clientX: 40, clientY: 40 }))
await wait(20)
const menu = env.document.querySelector('.iwb-gal-menu')
assert.ok(menu, '右键应打开菜单')
const labels = Array.from(menu.querySelectorAll('.iwb-ctx-item')).map((b) => b.textContent)
assert.deepStrictEqual(labels, ['插入画布', '下载', '预览大图', '复制文件名', '删除这张'], '菜单项不符:' + labels.join('|'))
// 复制文件名
const copyBtn = Array.from(menu.querySelectorAll('.iwb-ctx-item')).find((b) => b.textContent === '复制文件名')
copyBtn.dispatchEvent(new env.window.MouseEvent('click', { bubbles: true }))
await wait(30)
assert.strictEqual(JSON.stringify(env.copied), JSON.stringify(['a.png']), '应把文件名写入剪贴板')
assert.strictEqual(env.document.querySelector('.iwb-gal-menu'), null, '点击后菜单应关闭')
// 插入画布:走 capability + 设置里的插入尺寸
box.dispatchEvent(new env.window.MouseEvent('contextmenu', { bubbles: true, clientX: 40, clientY: 40 }))
await wait(20)
const insBtn = Array.from(env.document.querySelectorAll('.iwb-gal-menu .iwb-ctx-item')).find((b) => b.textContent === '插入画布')
insBtn.dispatchEvent(new env.window.MouseEvent('click', { bubbles: true }))
await wait(30)
assert.strictEqual(JSON.stringify(env.calls.insert[0][0]), JSON.stringify(['a.png']), '插入应带文件名')
assert.strictEqual(env.calls.insert[0][1].insertK, '1k', '插入应带默认尺寸档')
}
// ---------- ④ 多选拖拽:拖已选中的一张 = 整批 ----------
{
const env = await boot({
items: [{ name: 'a.png', w: 200, h: 300 }, { name: 'b.png', w: 200, h: 300 }, { name: 'c.png', w: 200, h: 300 }],
thumb: () => GOOD,
})
// jsdom 里 img 一直是 display:none(等 load),交互仍然可点,所以不要按可见性过滤
const imgs = Array.from(env.host.querySelectorAll('.iwb-history-item img'))
assert.strictEqual(imgs.length, 3, '三张都应有 img 节点')
// Shift 单击选中 a、b
imgs[0].dispatchEvent(new env.window.MouseEvent('click', { bubbles: true }))
imgs[1].dispatchEvent(new env.window.MouseEvent('click', { bubbles: true, shiftKey: true }))
await wait(40)
assert.strictEqual(env.host.querySelectorAll('.iwb-history-item.iwb-history-selected').length, 2, '应选中 2 张')
const store = {}
const drag = new env.window.Event('dragstart', { bubbles: true })
drag.dataTransfer = { setData: (k, v) => { store[k] = v }, effectAllowed: '' }
env.host.querySelectorAll('.iwb-history-item img')[0].dispatchEvent(drag)
assert.ok(store['application/x-iwb-gallery-batch'], '多选拖拽应带批量 payload')
assert.strictEqual(JSON.parse(store['application/x-iwb-gallery-batch']).length, 2, '批量 payload 应含 2 张')
// 在 document 捕获阶段被插件接管(宿主 drop 契约不变)
const drop = new env.window.Event('drop', { bubbles: true, cancelable: true })
drop.dataTransfer = { getData: (k) => store[k] || '' }
env.document.dispatchEvent(drop)
await wait(40)
assert.strictEqual(env.calls.insert.length, 1, '应触发一次批量插入')
assert.strictEqual(env.calls.insert[0][0].length, 2, '批量插入应含 2 张,实际 ' + env.calls.insert[0][0].length)
}
console.log('gallery ux checks passed(搜索 query / 失败统计+全部重试 / 右键菜单 5 项 / 多选拖拽批量插入)')
})().catch((e) => { console.error(e); process.exit(1) })