Files
iwb-plugins-desktop/style-source/tools/harness.mjs
T
qiqi 38a34ff533 feat(style-source): 风格库插件(资源库面板浏览 310 个 AI 绘画风格)
- 直连 malongan.github.io 的 styles.json 与预览图(CORS *),无后端、不改宿主 CSP
- 面板宽度自适应:网格 auto-fill 列数,详情按 480px 拐点切「覆盖 body / 右侧栏」
  判定用 ResizeObserver(拖侧栏时视口不变,@media 不响应)
- 按容器建实例:宿主侧栏与放大窗口可同时渲染同一面板,各自独立 RO,数据走模块级共享
- 变量替换:{占位符} 按 variables 字段生成输入框,留空保留原占位符
- 插入:预览图 blob→dataURL→createImageNode(ref);提示词 createNode('prompt') 插选中节点右侧
- 修 grid-auto-rows 默认 auto 导致图片未加载时卡片塌成横条的坑(显式 max-content)
- 加 tools/harness.mjs(离线合成宿主)与 tools/e2e-real.mjs(真实网络冒烟)
- 已发布 KV:plugin-style-source.fd634473ee66.js(v1.0.0,integrity 校验通过)
2026-11-02 09:18:05 +08:00

373 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 风格库插件本地端到端(开发用,不进 CI)。
//
// 为什么需要它:面板布局随宽度变化、变量替换、插图(blob → dataURL → createImageNode)都是浏览器行为,node 侧测不了。
// 这里装一个合成宿主(可注入的 ctx + 面板容器),addScriptTag 加载插件源码本体,在真实 Chromium 里验证:
// 注册 / 面板注册 / 数据加载 / 分批渲染 / 窄宽两态布局 / ResizeObserver 切档 / 搜索 / 分类 / 变量替换 / 两个插入动作 / 重复 mount 幂等
//
// 网络完全本地化:page.route 拦截 GitHub Pages,styles.json 读本地文件,预览图返回 1×1 PNG。
// 所以这里测不到真实 CORS(数据源是 *,已在方案阶段用 curl 实测过)。
//
// 运行:
// node style-source/tools/harness.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import { createServer } from 'node:http'
import path from 'node:path'
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 PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
const STYLES_JSON = '/Users/qiqi/open/github/style-source/data/styles.json'
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 style-source/tools/harness.mjs')
process.exit(2)
}
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const poll = async (fn, timeout = 15000, step = 80) => {
const end = Date.now() + timeout
for (;;) {
const v = await fn()
if (v) return v
if (Date.now() > end) return null
await new Promise((r) => setTimeout(r, step))
}
}
const PNG_1PX = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
'base64',
)
const PAGE_HTML = `<!doctype html><html><head><meta charset="utf-8">
<style>html,body{margin:0;height:100%;font-family:system-ui,sans-serif}
#stage{display:flex;align-items:stretch;height:100vh;padding:0}</style></head>
<body><div id="stage"></div></body></html>`
async function main() {
const stylesRaw = readFileSync(STYLES_JSON, 'utf8')
const stylesCount = JSON.parse(stylesRaw).styles.length
console.log('· 本地 styles.json:' + stylesCount + ' 条')
const server = createServer((req, res) => {
if (req.url === '/' || req.url.startsWith('/?')) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
res.end(PAGE_HTML)
return
}
res.writeHead(404); res.end('not found')
})
await new Promise((r) => server.listen(0, '127.0.0.1', r))
const port = server.address().port
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1280, height: 900 } })
let dataHits = 0
// 拦截上游静态资源:json 用本地文件,图片用 1×1 png(保证离线可复现)
await page.route('https://malongan.github.io/style-source/**', async (route) => {
const url = route.request().url()
const cors = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET,HEAD',
'cache-control': 'no-store',
}
if (url.includes('/data/styles.json')) {
dataHits++
await route.fulfill({ status: 200, headers: { ...cors, 'content-type': 'application/json' }, body: stylesRaw })
return
}
await route.fulfill({ status: 200, headers: { ...cors, 'content-type': 'image/png' }, body: PNG_1PX })
})
const errors = []
page.on('pageerror', (e) => errors.push(String(e)))
await page.goto(`http://127.0.0.1:${port}/`)
// ---- 合成宿主 ----
await page.evaluate(() => {
window.__calls = { nodes: [], images: [], panels: [], manifests: [], setups: 0 }
window.__nodes = [
{ id: 'n_prompt', type: 'prompt', x: 100, y: 120, data: { text: '原有提示词' } },
{ id: 'n_ref', type: 'ref', x: 520, y: 120, data: { name: '参考图' } },
]
window.__sel = { id: 'n_prompt', type: 'prompt', name: '原有提示词' }
window.IWBPluginHost = {
register(manifest, setup) {
window.__calls.manifests.push(manifest)
window.__calls.setups++
window.__manifest = manifest
window.__setup = setup
},
}
})
await page.addScriptTag({ path: PLUGIN_ENTRY })
const registered = await page.evaluate(() => Boolean(window.__setup))
check('插件调用 IWBPluginHost.register', registered)
if (!registered) { await finish(); return }
const manifest = await page.evaluate(() => {
const m = window.__manifest
return { id: m.id, name: m.name, version: m.version, apiVersion: m.apiVersion, caps: m.capabilities, hasDataUrl: Boolean(m.settings && m.settings.dataUrl) }
})
check('manifest id/version 正确', manifest.id === 'style-source' && manifest.version === '1.0.0', JSON.stringify({ id: manifest.id, version: manifest.version }))
check('capabilities 含 panels+canvas+canvasWrite',
['panels', 'canvas', 'canvasWrite'].every((c) => manifest.caps.includes(c)), manifest.caps.join(','))
check('settings 暴露 dataUrl', manifest.hasDataUrl)
// ---- 建面板(窄:320) ----
const mounted = await page.evaluate(() => {
const ctx = {
id: window.__manifest.id,
settings: { get: (k) => (window.__manifest.settings[k] || {}).default },
storage: null,
ui: { registerPanel: (p) => { window.__calls.panels.push(p) } },
canvas: {
getNodes: () => window.__nodes,
getSelectedNode: () => window.__sel,
createNode: (type, x, y, data) => { window.__calls.nodes.push({ type, x, y, data }); return 'n_new_' + window.__calls.nodes.length },
createImageNode: (payload) => { window.__calls.images.push(payload); return 'n_img_' + window.__calls.images.length },
},
}
window.__setup(ctx)
const panel = window.__calls.panels[0]
const stage = document.getElementById('stage')
const host = document.createElement('div')
host.id = 'hostA'
host.style.cssText = 'width:320px;height:640px;display:flex;min-width:0'
stage.appendChild(host)
panel.mount(host)
window.__hostA = host
return { panelId: panel && panel.id, title: panel && panel.title, icon: panel && panel.icon }
})
check('注册面板「风格库」+ palette 图标', mounted.title === '风格库' && mounted.icon === 'palette', JSON.stringify(mounted))
// ---- 数据加载 ----
const loaded = await poll(async () => {
const txt = await page.locator('.iwb-ss-status').innerText().catch(() => '')
return /共 \d+ 个风格/.test(txt) ? txt : null
})
check('数据加载完成并显示总数', Boolean(loaded), loaded || '超时')
check('styles.json 只拉了一次', dataHits === 1, 'hits=' + dataHits)
const cards = await page.locator('#hostA .iwb-ss-card').count()
check('分批渲染首批卡片(' + cards + ' 张,应为 PAGE_SIZE=90)', cards === 90, 'cards=' + cards)
const chipCount = await page.locator('#hostA .iwb-ss-chip').count()
check('分类 chips = 全部 + 12 类', chipCount === 13, 'chips=' + chipCount)
// 回归守门:grid-auto-rows 默认 auto 会让图片未加载时的行高塌成一行文字,卡片被裁成横杠
const geom = await page.evaluate(() => {
const card = document.querySelector('#hostA .iwb-ss-card')
const img = card.querySelector('.iwb-ss-thumb')
const name = card.querySelector('.iwb-ss-cardname')
const h = (e) => Math.round(e.getBoundingClientRect().height)
return { cardH: h(card), imgH: h(img), nameH: h(name), name: name.textContent }
})
check('卡片高度容纳图片 + 文字(grid-auto-rows 守门)', geom.cardH >= geom.imgH + 20,
'card=' + geom.cardH + ' img=' + geom.imgH)
check('卡片名称可见', geom.nameH >= 10 && geom.name.length > 0, geom.name + ' / h=' + geom.nameH)
// ---- 默认窄档 ----
const layoutNarrow = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
check('320px 初始为 narrow', layoutNarrow === 'narrow', String(layoutNarrow))
// ---- 选中第一张卡:窄档详情应为覆盖层 ----
await page.locator('#hostA .iwb-ss-card').first().click()
await page.waitForTimeout(120)
const narrowDetail = await page.evaluate(() => {
const root = window.__hostA.querySelector('.iwb-ss-root')
const d = root.querySelector('.iwb-ss-detail')
const cs = getComputedStyle(d)
const rb = root.getBoundingClientRect()
const db = d.getBoundingClientRect()
return { open: d.classList.contains('is-open'), position: cs.position, display: cs.display, coverW: Math.round(db.width), rootW: Math.round(rb.width) }
})
check('窄档选中后详情为覆盖层', narrowDetail.open && narrowDetail.position === 'absolute' && narrowDetail.display === 'flex',
JSON.stringify(narrowDetail))
check('覆盖层宽度等于面板宽度', Math.abs(narrowDetail.coverW - narrowDetail.rootW) <= 1, narrowDetail.coverW + ' vs ' + narrowDetail.rootW)
// ---- 变量替换 ----
const varResult = await page.evaluate(() => {
const inputs = Array.from(window.__hostA.querySelectorAll('.iwb-ss-varinput'))
if (!inputs.length) return { hasVars: false }
const first = inputs[0]
const name = first.getAttribute('placeholder')
first.value = '测试角色ABC'
first.dispatchEvent(new Event('input', { bubbles: true }))
const preview = window.__hostA.querySelector('.iwb-ss-text').textContent
return { hasVars: true, name, preview, replaced: preview.includes('测试角色ABC'), stillHasPlaceholder: preview.includes('{' + name + '}') }
})
check('详情渲染变量输入框', varResult.hasVars, varResult.name ? '第一个变量:{' + varResult.name + '}' : '')
check('填变量后预览实时替换', Boolean(varResult.replaced))
check('已填变量不再残留占位符', varResult.hasVars && !varResult.stillHasPlaceholder)
// ---- 插提示词 ----
await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').nth(1).click()
await page.waitForTimeout(120)
const promptCall = await page.evaluate(() => window.__calls.nodes[0] || null)
check('插入提示词调用 createNode', Boolean(promptCall) && promptCall.type === 'prompt', promptCall ? 'type=' + promptCall.type : '未调用')
check('提示词带变量替换结果', Boolean(promptCall) && String(promptCall.data.text).includes('测试角色ABC'))
check('提示词插在选中节点右侧', Boolean(promptCall) && promptCall.x === 480 && promptCall.y === 120,
promptCall ? '(' + promptCall.x + ',' + promptCall.y + ') 期望 (480,120)' : '')
// ---- 插参考图(blob → dataURL) ----
await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').first().click()
const imgCall = await poll(() => page.evaluate(() => window.__calls.images[0] || null), 8000)
check('插入参考图调用 createImageNode', Boolean(imgCall))
check('传入的是 data: URL(宿主只认这个)', Boolean(imgCall) && /^data:image\//.test(String(imgCall.dataUrl)), imgCall ? String(imgCall.dataUrl).slice(0, 24) + '…' : '')
check('节点名带风格编号', Boolean(imgCall) && /^ST\d+_/.test(String(imgCall.name)), imgCall ? imgCall.name : '')
// ---- 拉宽到 980:详情应切成右侧栏 ----
await page.evaluate(() => { window.__hostA.style.width = '980px' })
const wideLayout = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'wide' ? v : null
})
check('拉宽到 980 后 data-layout=wide(ResizeObserver 生效)', Boolean(wideLayout))
const wideDetail = await page.evaluate(() => {
const root = window.__hostA.querySelector('.iwb-ss-root')
const d = root.querySelector('.iwb-ss-detail')
const cs = getComputedStyle(d)
const rb = root.getBoundingClientRect()
const db = d.getBoundingClientRect()
return { position: cs.position, flexBasis: cs.flexBasis, ratio: db.width / rb.width, cols: getComputedStyle(root.querySelector('.iwb-ss-grid')).gridTemplateColumns.split(' ').length }
})
check('宽档详情为右侧栏(非 absolute)', wideDetail.position !== 'absolute', wideDetail.position)
check('宽档详情占比约 46%', wideDetail.ratio > 0.3 && wideDetail.ratio < 0.5, wideDetail.ratio.toFixed(2))
check('宽档网格列数增加', wideDetail.cols >= 4, 'cols=' + wideDetail.cols)
// ---- 恢复窄档,测边界:479/480 ----
await page.evaluate(() => { window.__hostA.style.width = '479px' })
const at479 = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'narrow' ? v : null
})
await page.evaluate(() => { window.__hostA.style.width = '480px' })
const at480 = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'wide' ? v : null
})
check('拐点精确:479=narrow / 480=wide', Boolean(at479) && Boolean(at480))
// ---- 搜索 ----
await page.evaluate(() => { window.__hostA.style.width = '320px' })
await page.locator('#hostA .iwb-ss-search').fill('Y3K')
await page.waitForTimeout(320)
const searchState = await page.evaluate(() => ({
status: window.__hostA.querySelector('.iwb-ss-status').firstChild.textContent,
cards: window.__hostA.querySelectorAll('.iwb-ss-card').length,
}))
check('搜索「Y3K」过滤生效', /找到 \d+ 个/.test(searchState.status) && searchState.cards > 0 && searchState.cards < 90,
searchState.status + ' / ' + searchState.cards + ' 张')
// ---- 分类筛选 ----
await page.locator('#hostA .iwb-ss-search').fill('')
await page.waitForTimeout(280)
const clickCat = await page.evaluate(() => {
const chips = Array.from(window.__hostA.querySelectorAll('.iwb-ss-chip'))
const target = chips.find((c) => c.textContent.startsWith('电商'))
if (!target) return null
target.click()
return target.textContent
})
await page.waitForTimeout(160)
const catState = await page.evaluate(() => ({
on: (window.__hostA.querySelector('.iwb-ss-chip.is-on') || {}).textContent || '',
status: window.__hostA.querySelector('.iwb-ss-status').firstChild.textContent,
}))
check('点分类「电商」后 chips 高亮切换', Boolean(clickCat) && catState.on.startsWith('电商'), clickCat + ' → ' + catState.on)
check('分类筛选改变了结果数', /找到 \d+ 个/.test(catState.status), catState.status)
// ---- 多容器并存(宿主侧栏 + 放大窗口可能同时渲染同一插件面板) ----
// 早期版本用单个全局 dom 指针,第二个容器一挂载就把第一个容器的 RO 断掉 —— 这里专门守住这条
const dual = await page.evaluate(() => {
const stage = document.getElementById('stage')
const hostB = document.createElement('div')
hostB.id = 'hostB'
hostB.style.cssText = 'width:920px;height:600px;display:flex;min-width:0'
stage.appendChild(hostB)
window.__calls.panels[0].mount(hostB)
window.__hostB = hostB
return {
rootsA: window.__hostA.querySelectorAll('.iwb-ss-root').length,
rootsB: hostB.querySelectorAll('.iwb-ss-root').length,
cardsB: hostB.querySelectorAll('.iwb-ss-card').length,
layoutB: hostB.querySelector('.iwb-ss-root').getAttribute('data-layout'),
}
})
check('两个容器各有且仅有一份根节点', dual.rootsA === 1 && dual.rootsB === 1, JSON.stringify({ a: dual.rootsA, b: dual.rootsB }))
check('第二个容器复用缓存(不重拉就有卡片)', dual.cardsB > 0, 'cards=' + dual.cardsB)
// 首帧同步判定,第二容器应该挂载即 wide(不该先闪一帧 narrow)
check('第二个容器 920px 挂载即判定 wide', dual.layoutB === 'wide', String(dual.layoutB))
check('styles.json 总计仍只请求过一次', dataHits === 1, 'hits=' + dataHits)
// hostB 挂载后,hostA 的 ResizeObserver 必须仍然有效(这是被抢指针时最先坏掉的地方)
await page.evaluate(() => { window.__hostA.style.width = '700px' })
const aStillAlive = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'wide' ? v : null
})
check('hostB 存在时 hostA 仍响应宽度变化', Boolean(aStillAlive))
// ---- 截图留档(先移除 hostB,否则 flex 会把 hostA 压缩、截不到真实宽度) ----
const shotWide = path.resolve(HERE, 'shot-wide.png')
const shotNarrow = path.resolve(HERE, 'shot-narrow.png')
await page.evaluate(() => {
if (window.__hostB) window.__hostB.remove()
window.__hostA.style.width = '980px'
window.__hostA.style.height = '720px'
})
const shotLayout = await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'wide' ? v : null
})
check('截图前 hostA 已回到 wide', Boolean(shotLayout))
await page.waitForTimeout(400)
await page.locator('#hostA').screenshot({ path: shotWide }).catch(() => {})
await page.evaluate(() => { window.__hostA.style.width = '320px'; window.__hostA.style.height = '640px' })
await poll(async () => {
const v = await page.evaluate(() => window.__hostA.querySelector('.iwb-ss-root').getAttribute('data-layout'))
return v === 'narrow' ? v : null
})
await page.waitForTimeout(400)
await page.locator('#hostA').screenshot({ path: shotNarrow }).catch(() => {})
console.log('· 截图:' + shotWide)
console.log('· 截图:' + shotNarrow)
check('无页面 JS 异常', errors.length === 0, errors.slice(0, 2).join(' | '))
await finish()
async function finish() {
await browser.close()
server.close()
console.log('')
console.log(failed === 0 ? '全部通过' : failed + ' 项失败')
process.exit(failed === 0 ? 0 : 1)
}
}
main().catch(async (error) => {
console.error('harness 崩溃:', error)
process.exit(1)
})