'use strict' // 图库插件渲染回归(防止「缩略图异步却当同步用」导致整墙"图片已丢失") // // 2026-11-20 真实事故:ctx.gallery.thumb() 返回 Promise,插件把 Promise 当字符串判空 ⇒ 7 张全丢。 const assert = require('assert') const fs = require('fs') const path = require('path') const { JSDOM } = require('jsdom') const root = path.resolve(__dirname, '..') const src = fs.readFileSync(path.join(root, '..', 'iwb-plugins-desktop', 'gallery', 'src', 'index.js'), 'utf8') const dom = new JSDOM('
', { pretendToBeVisual: true }) const { window } = dom global.window = window global.document = window.document let mounted = null const host = { plugins: [], register (manifest, factory) { host.plugins.push({ manifest, factory }) }, } window.IWBPluginHost = host // 插件用到的浏览器 API window.ResizeObserver = class { observe () {} disconnect () {} } window.confirm = () => true ;(async () => { // 在 vm 里跑插件源码(它直接用 window/document) const vm = require('vm') const sandbox = { window, document: window.document, console, setTimeout, clearTimeout, Promise, Object, Array, JSON, Math } vm.runInNewContext(src, sandbox) assert.strictEqual(host.plugins.length, 1, '插件应注册一次') const { manifest, factory } = host.plugins[0] assert.strictEqual(manifest.id, 'gallery') assert.ok(manifest.capabilities.indexOf('gallery') >= 0, '应声明 gallery 能力') const calls = { list: 0, thumb: 0 } const ctx = { ui: { registerPanel (p) { mounted = p.mount } }, data: { read: async () => ({ cfg: { tile: 130 } }), patch: async () => true }, gallery: { list: async () => { calls.list++; return { items: [{ name: 'a.png', w: 200, h: 300 }, { name: 'b.png', w: 200, h: 120 }], total: 2 } }, thumb: async (n) => { calls.thumb++; return 'data:image/svg+xml;utf8,' + encodeURIComponent('') }, preview: () => {}, download: async () => ({ ok: true }), insert: async () => ({ ok: true }), remove: async () => ({ ok: true }), }, } factory(ctx) assert.ok(mounted, '应注册面板 mount') const node = window.document.getElementById('host') mounted(node) // 等 list + 2 次 thumb 的微任务跑完 for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 10)) const imgs = Array.from(node.querySelectorAll('.iwb-history-item img')) const missing = Array.from(node.querySelectorAll('.iwb-history-missing')).map((x) => x.textContent).filter((t) => t !== '加载中…') assert.strictEqual(calls.list, 1, '应只拉一次列表') assert.strictEqual(calls.thumb, 2, '每张图各取一次缩略图') assert.strictEqual(imgs.length, 2, '两张图都应渲染出 img,实际 ' + imgs.length) assert.ok(imgs.every((i) => String(i.getAttribute('src')).indexOf('data:image/svg') === 0), 'img.src 应来自 thumb()') assert.strictEqual(missing.length, 0, '不应出现「图片已丢失」:' + missing.join(',')) console.log('plugin-gallery checks passed(异步缩略图 / 2 张图渲染 / 无丢失)') })().catch((e) => { console.error(e); process.exit(1) })