Files
iwb-plugins-desktop/style-source/tools/harness.mjs
T
qiqi c3e2625ac8 feat(style-source): 变量改按提示词占位符识别,不再依赖数据声明 (1.0.3)
「有的风格有变量、有的没有」的根因在数据:线上 970 条 variables 里 625 条的值只是
人话描述(没有花括号),旧逻辑拿它当占位符名去找 `{人话}`,永远找不到;
反过来还有 78 个风格提示词里明明有 {xxx} 却一条都没声明。结果是声明了的是摆设、
没声明的干脆不出输入框。

- varKeys 改成「扫 prompt 里的 {占位符}」为准,variables 只负责配标签:
  · 值带花括号(新写法)→ 直接命中
  · 值是描述 / key 带反引号(Vigo 导入数据)→ 拿 key 兜底找占位符,标签剥掉 ` 和 *
  · 两边都对不上 → 照常出输入框,标签退化成占位符名(浅色斜体标记)
- 输入框最多先摆 6 个,其余折进「展开其余 N 个变量」(Vigo 单条提示词最多 24 个占位符)
- harness 新增 6 条:未声明也给输入框 / 反引号剥离 / 不造死输入框 / 声明落空退回占位符名 / 折叠与展开 / 无占位符不摆空框
- README 补「变量」格式规范(花括号、variables 必须是列表、别用 [方括号])
2026-11-02 10:22:18 +08:00

567 lines
29 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.css 抄的关键几条,否则「手动拉过尺寸的节点」这条测不出来 */
.iwb-node{display:flex;flex-direction:column;border:1px solid #d5d9e0;border-radius:14px;position:relative}
.iwb-node-body{padding:8px 10px;flex:1 1 auto;min-height:0}
.iwb-textarea{min-height:56px;overflow-y:auto;width:100%;box-sizing:border-box;resize:none}
.iwb-node-fixed .iwb-node-body{display:flex;flex-direction:column;overflow:visible;min-height:0}
.iwb-node-fixed .iwb-textarea{flex:1 1 auto;max-height:none;min-height:56px;height:auto !important}
</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.3', 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'
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))
// ---- 长提示词:节点内滚动(宿主 autoGrow 把 textarea 撑成 scrollHeight,一条长提示词能拉成一米高) ----
const cap = await page.evaluate(() => {
const st = document.getElementById('iwb-ss-nodecap')
if (!st) return { injected: false }
// 造一个和宿主一致的节点结构,验证 max-height 真能压住内联 height
const wrap = document.createElement('div')
wrap.className = 'iwb-node'
wrap.style.cssText = 'width:280px;display:flex;flex-direction:column'
const ta = document.createElement('textarea')
ta.className = 'iwb-textarea iwb-textarea-plain'
ta.style.height = '1200px' // autoGrow 的产物
ta.value = 'x'.repeat(4000)
wrap.appendChild(ta)
document.getElementById('stage').appendChild(wrap)
const h = Math.round(ta.getBoundingClientRect().height)
const oy = getComputedStyle(ta).overflowY
wrap.remove()
return { injected: true, css: st.textContent, cappedH: h, overflowY: oy }
})
check('注入文本节点高度上限样式', cap.injected && /max-height:\s*240px/.test(String(cap.css)), String(cap.css))
check('内联 height=1200 的文本域被压到 240(节点不再被拉长)', cap.cappedH > 0 && cap.cappedH <= 260, 'h=' + cap.cappedH + '(240 内容 + 边框)')
check('超出部分在文本域内滚动', cap.overflowY === 'auto', cap.overflowY)
// 回归守门:默认只压「自动高」的节点;用户手动拉过尺寸(node.h → .iwb-node-fixed)时不能压,
// 否则节点被拉高一米,文字还卡在 240px,下面留一大片空白
const stretched = await page.evaluate(() => {
const wrap = document.createElement('div')
wrap.className = 'iwb-node iwb-node-fixed' // node.h 有值 → 宿主加这个 class
wrap.style.cssText = 'width:280px;min-height:520px'
const body = document.createElement('div')
body.className = 'iwb-node-body'
const ta = document.createElement('textarea')
ta.className = 'iwb-textarea iwb-textarea-plain'
ta.style.height = '1200px'
ta.value = 'x'.repeat(4000)
body.appendChild(ta)
wrap.appendChild(body)
document.getElementById('stage').appendChild(wrap)
const r = {
nodeH: Math.round(wrap.getBoundingClientRect().height),
taH: Math.round(ta.getBoundingClientRect().height),
cap: getComputedStyle(ta).maxHeight,
}
wrap.remove()
return r
})
check('手动拉高节点后文本域跟着撑满(不再卡在 240)',
stretched.taH > stretched.nodeH * 0.6, 'node=' + stretched.nodeH + ' textarea=' + stretched.taH + ' maxH=' + stretched.cap)
check('手动拉高节点时上限被让开', stretched.cap === 'none', stretched.cap)
// ---- 数据加载 ----
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)
// 回归守门:13 个 chip 不换行,max-content 近 950px,要把祖先容器顶宽(真实宿主窗口只有 680,右侧全被裁)
const ov1 = await page.evaluate(() => {
const r = document.querySelector('#hostA .iwb-ss-root')
return { sw: r.scrollWidth, cw: r.clientWidth }
})
check('窄档无水平溢出(chip max-content 不顶宽容器)', ov1.sw <= ov1.cw + 1, 'scrollW=' + ov1.sw + ' clientW=' + ov1.cw)
// ---- 分类 chips 自适应换行 ----
// 以前 chips 是「单行 + 横向滚动 + scrollbar 隐藏」:面板拖窄时右边几类永远看不见,用户以为只有 7 个分类。
// 现在改 flex-wrap,这里守住两件事:所有 chip 都落在 chips 容器内(不被裁),且容器没有横向滚动条。
const measureChips = () => page.evaluate(() => {
const box = document.querySelector('#hostA .iwb-ss-chips')
const all = Array.from(box.querySelectorAll('.iwb-ss-chip'))
const bb = box.getBoundingClientRect()
const rows = new Set(all.map((c) => Math.round(c.getBoundingClientRect().top))).size
const outside = all.filter((c) => {
const r = c.getBoundingClientRect()
return r.right > bb.right + 1 || r.left < bb.left - 1 || r.bottom > bb.bottom + 1
}).length
const countShown = all[0] ? getComputedStyle(all[0].querySelector('.iwb-ss-chipn')).display !== 'none' : false
return { count: all.length, rows, outside, sw: box.scrollWidth, cw: box.clientWidth, h: Math.round(bb.height), countShown }
})
const chipsNarrow = await measureChips()
check('窄档 chips 全部落在容器内(换行而非横向滚动)',
chipsNarrow.outside === 0 && chipsNarrow.sw <= chipsNarrow.cw + 1,
JSON.stringify(chipsNarrow))
check('窄档 chips 折成多行', chipsNarrow.rows >= 2, 'rows=' + chipsNarrow.rows + ' h=' + chipsNarrow.h)
check('窄档隐藏数量后缀(省一行高度)', chipsNarrow.countShown === false)
// ---- 默认窄档 ----
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)
const ov2 = await page.evaluate(() => {
const r = document.querySelector('#hostA .iwb-ss-root')
return { sw: r.scrollWidth, cw: r.clientWidth }
})
check('宽档无水平溢出', ov2.sw <= ov2.cw + 1, 'scrollW=' + ov2.sw + ' clientW=' + ov2.cw)
const chipsWide = await measureChips()
check('宽档 chips 一行铺完(不再溢出到右侧看不见)',
chipsWide.rows === 1 && chipsWide.outside === 0,
JSON.stringify(chipsWide))
check('宽档恢复显示数量后缀', chipsWide.countShown === true)
// ---- 恢复窄档,测边界: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)
// ---- 变量来源:只认提示词里真实出现的 {占位符} ----
// 线上 970 条 variables 里有 625 条的值只是人话描述(没有花括号),按声明表造输入框时全都对不上号 ⇒
// 「有的有、有的没有」;反过来还有 78 个风格提示词里明明有 {xxx} 却一条都没声明。
// 现在统一从提示词抽,声明表只用来配中文标签(并兼容 key 上带反引号的脏数据)。
const openBySearch = async (q) => {
// 窄档里详情是**覆盖层**,不先关掉会挡住栅格,点不到卡片
await page.evaluate(() => {
const box = window.__hostA.querySelector('.iwb-ss-detail.is-open')
const close = box && box.querySelector('.iwb-ss-dclose')
if (close) close.click()
const all = document.querySelector('#hostA .iwb-ss-chip')
if (all && !all.classList.contains('is-on')) all.click()
})
await page.waitForTimeout(140)
await page.locator('#hostA .iwb-ss-search').fill(q)
await page.waitForTimeout(340)
await page.locator('#hostA .iwb-ss-card').first().click()
await page.waitForTimeout(140)
return page.evaluate(() => {
const box = window.__hostA.querySelector('.iwb-ss-detail')
const inputs = Array.from(box.querySelectorAll('.iwb-ss-varinput'))
const toggle = box.querySelector('.iwb-ss-vartoggle')
const more = box.querySelector('.iwb-ss-varmore')
const preview = (box.querySelector('.iwb-ss-text') || {}).textContent || ''
const names = inputs.map((i) => i.getAttribute('placeholder'))
return {
name: ((box.querySelector('.iwb-ss-dtitle') || {}).textContent || '').trim(),
labels: Array.from(box.querySelectorAll('.iwb-ss-varlabel')).map((e) => e.textContent),
pairs: inputs.map((i) => ({
name: i.getAttribute('placeholder'),
label: (i.parentNode.querySelector('.iwb-ss-varlabel') || {}).textContent || '',
implicit: Boolean(i.parentNode.querySelector('.iwb-ss-varlabel.is-implicit')),
})),
names: names,
visible: inputs.filter((i) => i.getBoundingClientRect().height > 0).length,
dead: names.filter((n) => preview.indexOf('{' + n + '}') < 0).length,
hasVarLabel: Array.from(box.querySelectorAll('.iwb-ss-label')).some((e) => e.textContent.indexOf('变量') >= 0),
toggle: toggle ? toggle.textContent : '',
moreHidden: more ? getComputedStyle(more).display === 'none' : null,
}
})
}
const undeclared = await openBySearch('婚礼喜字影像画报')
check('提示词有占位符、数据没声明的风格也有输入框',
undeclared.names.length === 3 && undeclared.dead === 0, undeclared.name + ' → ' + undeclared.names.join(','))
const vigo = await openBySearch('黄黑漫画食品小志广告风格')
const subj = vigo.pairs.find((p) => p.name === 'SUBJECT')
check('脏 key 的反引号被剥掉,占位符 {SUBJECT} 认回声明过的标签',
Boolean(subj) && subj.label === 'SUBJECT' && !subj.implicit,
subj ? subj.label + ' → {' + subj.name + '}' + (subj.implicit ? '(按未声明处理)' : '') : '没有 SUBJECT 输入框')
check('声明表不会凭空造输入框(每个输入框都能在提示词里找到)',
vigo.dead === 0, 'inputs=' + vigo.names.length + ' dead=' + vigo.dead)
const mondrian = await openBySearch('蒙德里安秩序风')
check('声明与提示词对不上时退回占位符名(不再静默消失)',
mondrian.names.length === 8 && mondrian.pairs.every((p) => p.implicit && p.label.indexOf('`') < 0),
mondrian.pairs.slice(0, 3).map((p) => p.label + '→{' + p.name + '}').join(', '))
check('变量超过 6 个时先给 6 个、其余折叠',
mondrian.visible === 6 && mondrian.names.length > 6 && /展开其余 \d+ 个变量/.test(mondrian.toggle),
'可见=' + mondrian.visible + ' 全部=' + mondrian.names.length + ' / ' + mondrian.toggle)
check('折叠区默认收起', mondrian.moreHidden === true)
const expand = await page.evaluate(() => {
const box = window.__hostA.querySelector('.iwb-ss-detail')
const btn = box.querySelector('.iwb-ss-vartoggle')
if (!btn) return null
btn.click()
const more = box.querySelector('.iwb-ss-varmore')
return {
shown: more ? getComputedStyle(more).display !== 'none' : null,
count: more ? more.querySelectorAll('.iwb-ss-varinput').length : 0,
text: btn.textContent,
}
})
check('点「展开」后其余变量出现', Boolean(expand) && expand.shown === true && expand.count > 0,
expand ? '展开 ' + expand.count + ' 个 / 按钮=' + expand.text : '')
const noVar = await openBySearch('旷野的风')
check('提示词里没有占位符就不摆空输入框',
noVar.names.length === 0 && noVar.hasVarLabel === false, noVar.name + ' inputs=' + noVar.names.length)
await page.locator('#hostA .iwb-ss-search').fill('')
await page.waitForTimeout(200)
// ---- 多容器并存(宿主侧栏 + 放大窗口可能同时渲染同一插件面板) ----
// 早期版本用单个全局 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'
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')
const shotVars = path.resolve(HERE, 'shot-vars.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(() => {})
// 变量区留档:8 个占位符 → 前 6 个 + 「展开其余 2 个」
await page.evaluate(() => { window.__hostA.style.width = '980px'; window.__hostA.style.height = '1180px' })
await page.waitForTimeout(260)
await page.locator('#hostA .iwb-ss-search').fill('黄黑漫画食品小志广告风格')
await page.waitForTimeout(340)
await page.locator('#hostA .iwb-ss-card').first().click()
await page.waitForTimeout(380)
await page.locator('#hostA .iwb-ss-detail').screenshot({ path: shotVars })
console.log('· 截图:' + shotWide)
console.log('· 截图:' + shotNarrow)
console.log('· 截图:' + shotVars)
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)
})