Files

284 lines
15 KiB
JavaScript
Raw Permalink 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.
// 真机验收:**测试站上「宿主新接口 + 本插件」端到端**跑通(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)