validate / validate (push) Canceled after 0s
根因不是样式写错,是注入点太晚 + 上一版没真正上线: 1.3.0 只在 mount() 注入 ⇒ 从存档直接进画布(面板从不 mount)时节点体无样式, < img class=iwb-ssn-thumb > 按原图尺寸铺满节点。1.3.1 把注入提前到 setup, 但发布时 KV 只换了字节、清单仍指 1.3.0,线上等于没修。 - ensureStyle() 在 CSS 常量之后立刻调用(脚本执行即注入),setup / renderStyleNode 继续兜底 - 缩略图加行内 width/height:56px + object-fit:cover 兜底,样式表失效也不会撑爆节点 - harness 新增闸门:宿主 stub 不调 setup 时 #iwb-ss-style 必须已存在
978 lines
55 KiB
JavaScript
978 lines
55 KiB
JavaScript
// 风格库插件本地端到端(开发用,不进 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 stylesParsed = JSON.parse(readFileSync(STYLES_JSON, 'utf8'))
|
||
const stylesCount = stylesParsed.styles.length
|
||
console.log('· 本地 styles.json:' + stylesCount + ' 条')
|
||
|
||
// 线上数据已经 100% 声明变量,真实风格里再没有「有占位符但没声明」的样本。
|
||
// 那条降级分支仍然必须覆盖(宿主可能拿到旧版 / 第三方数据),所以克隆一条探针风格注入,
|
||
// 只改 id/name/prompt/variables —— 其余字段沿用真实数据,卡片渲染逻辑不特殊化。
|
||
const probe = JSON.parse(JSON.stringify(stylesParsed.styles[0]))
|
||
probe.id = '__probe_undeclared'
|
||
probe.code = ''
|
||
probe.number = ''
|
||
probe.name = '探针:未声明占位符'
|
||
probe.summary = 'harness 注入的探针风格,用来覆盖「有占位符但没声明」的降级分支'
|
||
probe.prompt = 'probe {alpha_desc} / {beta_desc} / {gamma_desc}'
|
||
probe.variables = []
|
||
delete probe.variable_descs
|
||
|
||
// 第二个探针:一半变量有 desc、一半没有。整改后线上数据已经「有就全有、没就全没」,
|
||
// 拿真实风格测不到「没 desc 降级成占位符名」这条分支。
|
||
const probe2 = JSON.parse(JSON.stringify(stylesParsed.styles[0]))
|
||
probe2.id = '__probe_desc_mix'
|
||
probe2.code = ''
|
||
probe2.number = ''
|
||
probe2.name = '探针:desc 混合'
|
||
probe2.summary = 'harness 注入的探针风格,一半变量带 desc、一半不带'
|
||
probe2.prompt = 'probe2 {主体} {标题}'
|
||
// 注意:styles.json 里 variables 是 {kv_var: style_var} 的字典,不是数组
|
||
probe2.variables = { 主体: '{主体}', 标题: '{标题}' }
|
||
probe2.variable_descs = { 主体: '如:一只猫、一台相机' }
|
||
const stylesRaw = JSON.stringify({ ...stylesParsed, styles: [...stylesParsed.styles, probe, probe2] })
|
||
|
||
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, variants: [] }
|
||
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: '原有提示词' }
|
||
// 宿主 findSpot 的最小复刻:视口 1280×900,从中心向外按环形扫,返回第一个不与已有节点相交的格子
|
||
window.__mockFindSpot = () => {
|
||
const CW = 1280, CH = 900, W = 320, H = 216, PAD = 20
|
||
const boxes = (window.__nodes || []).map((n) => ({ x: n.x, y: n.y, w: 320, h: 216 }))
|
||
const hit = (x, y) => boxes.some((b) => x < b.x + b.w && x + W > b.x && y < b.y + b.h && y + H > b.y)
|
||
const cx = CW / 2 - W / 2, cy = CH / 2 - H / 2
|
||
for (let ring = 0; ring <= 6; ring++) {
|
||
for (let dy = -ring; dy <= ring; dy++) {
|
||
for (let dx = -ring; dx <= ring; dx++) {
|
||
if (Math.max(Math.abs(dx), Math.abs(dy)) !== ring) continue
|
||
const x = Math.round(cx + dx * (W + PAD)), y = Math.round(cy + dy * (H + PAD))
|
||
if (!hit(x, y)) return { x, y, noOverlap: true }
|
||
}
|
||
}
|
||
}
|
||
return { x: Math.round(cx), y: Math.round(cy), noOverlap: false }
|
||
}
|
||
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) }
|
||
})
|
||
// 版本号从 package.json 读,不写死:写死时改版本忘了同步 manifest,CI 会报错但这里不会
|
||
const pkgVersion = JSON.parse(readFileSync(path.resolve(HERE, '../package.json'), 'utf8')).version
|
||
check('manifest id/version 与 package.json 一致',
|
||
manifest.id === 'style-source' && manifest.version === pkgVersion,
|
||
JSON.stringify({ id: manifest.id, manifest: manifest.version, pkg: pkgVersion }))
|
||
check('capabilities 含 panels+canvas+canvasWrite+nodeTypes',
|
||
['panels', 'canvas', 'canvasWrite', 'nodeTypes'].every((c) => manifest.caps.includes(c)), manifest.caps.join(','))
|
||
check('settings 暴露 dataUrl', manifest.hasDataUrl)
|
||
|
||
// v1.3.2 回归闸门:样式表必须在**脚本执行时**就已注入 —— 不依赖 setup,更不依赖面板 mount。
|
||
// 反面教材(2026-11-14,连续两次报障):1.3.0 只在 mount() 里注入,从存档直接进画布时面板
|
||
// 从不 mount ⇒ 节点体是无样式裸 DOM,`<img class="iwb-ssn-thumb">` 按原图尺寸铺满整个节点,
|
||
// 用户看到的就是「图片都跑出来了」「样式全坏了」。上面的宿主 stub 刻意**不调用 setup**,
|
||
// 所以这条 check 通过 = 注入点足够早。
|
||
const bootStyle = await page.evaluate(() => {
|
||
const s = document.getElementById('iwb-ss-style')
|
||
return { exists: Boolean(s), hasThumbRule: s ? s.textContent.indexOf('.iwb-ssn-thumb') >= 0 : false, len: s ? s.textContent.length : 0 }
|
||
})
|
||
check('样式表在脚本执行时就已注入(不开面板、不跑 setup 也在)',
|
||
bootStyle.exists && bootStyle.hasThumbRule, JSON.stringify(bootStyle))
|
||
|
||
// ---- 建面板(窄: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) } },
|
||
// v1.3.0:样式节点变体注册。宿主的能力名是 nodeTypes,但挂在 ctx 上的 key 是 `nodes`
|
||
//(plugin-host.js 的 CAPABILITY_API_KEYS),这里如实复刻,写错 key 插件那边会静默跳过
|
||
nodes: { register: (v) => { window.__calls.variants.push(v); return true } },
|
||
canvas: {
|
||
getNodes: () => window.__nodes,
|
||
getSelectedNode: () => window.__sel,
|
||
// 模拟宿主新语义:x/y 为 null/undefined ⇒ 走 findSpot(视口中心起螺旋找空位、避开已有节点)
|
||
createNode: (type, x, y, data) => {
|
||
const auto = x === null || x === undefined || y === null || y === undefined
|
||
const rec = { type, x, y, data, auto }
|
||
if (auto) {
|
||
const s = window.__mockFindSpot()
|
||
rec.x = s.x
|
||
rec.y = s.y
|
||
rec.noOverlap = s.noOverlap
|
||
}
|
||
window.__calls.nodes.push(rec)
|
||
return 'n_new_' + window.__calls.nodes.length
|
||
},
|
||
createImageNode: (payload) => { window.__calls.images.push(payload); return 'n_img_' + window.__calls.images.length },
|
||
// 模拟宿主新能力(2026-11-02):屏幕坐标 → 世界坐标。
|
||
// 视口口径:画布容器左上角 (320,0),平移 (100,-50),缩放 0.5
|
||
screenToWorld: (clientX, clientY) => ({ x: (clientX - 320 - 100) / 0.5, y: (clientY - 0 + 50) / 0.5, scale: 0.5 }),
|
||
},
|
||
}
|
||
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)
|
||
|
||
// ---- 插提示词 ----
|
||
// v1.3.0 起 footer 有三颗(样式节点 / 插入参考图 / 插入提示词),按下标取会随顺序飘 —— 改用文案定位
|
||
const btnPromptSel = page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '插入提示词' })
|
||
await btnPromptSel.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('提示词坐标交给宿主(插件不自己算,拿不到 pan/zoom)',
|
||
Boolean(promptCall) && promptCall.auto === true,
|
||
promptCall ? 'auto=' + promptCall.auto + ' raw=(' + promptCall.x + ',' + promptCall.y + ')' : '未调用')
|
||
check('宿主定位结果不压在已有节点上',
|
||
Boolean(promptCall) && promptCall.noOverlap === true,
|
||
promptCall ? '(' + promptCall.x + ',' + promptCall.y + ')' : '')
|
||
|
||
// ---- 拖拽插入:按住「插入提示词」拖到画布上松手 ⇒ 节点落在松手点 ----
|
||
await page.evaluate(() => {
|
||
// 造一块 .iwb-canvas(插件靠 elementFromPoint + closest('.iwb-canvas') 判断「是否在画布上」)
|
||
const cv = document.createElement('div')
|
||
cv.className = 'iwb-canvas'
|
||
cv.id = 'fakeCanvas'
|
||
cv.style.cssText = 'position:fixed;left:320px;top:0;width:900px;height:640px;z-index:1;background:#eee'
|
||
document.body.appendChild(cv)
|
||
window.__calls.nodes.length = 0
|
||
})
|
||
const btnBox = await btnPromptSel.boundingBox()
|
||
const dropX = 700
|
||
const dropY = 300
|
||
await page.mouse.move(btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2)
|
||
await page.mouse.down()
|
||
await page.mouse.move(dropX - 60, dropY - 40, { steps: 6 })
|
||
const ghost = await page.evaluate(() => {
|
||
const g = document.querySelector('.iwb-ss-ghost')
|
||
return g ? { text: g.textContent, over: g.classList.contains('is-over'), pe: getComputedStyle(g).pointerEvents } : null
|
||
})
|
||
check('拖拽中出现跟随光标的幽灵卡片', Boolean(ghost), ghost ? ghost.text : '未出现')
|
||
check('幽灵卡片 pointer-events:none(不挡 elementFromPoint)', Boolean(ghost) && ghost.pe === 'none', ghost ? ghost.pe : '')
|
||
check('拖到画布上时幽灵提示「松手放这里」', Boolean(ghost) && ghost.over === true, ghost ? ghost.text : '')
|
||
await page.mouse.move(dropX, dropY, { steps: 4 })
|
||
await page.mouse.up()
|
||
await page.waitForTimeout(150)
|
||
const dragCall = await page.evaluate(() => window.__calls.nodes[0] || null)
|
||
const expectX = (dropX - 320 - 100) / 0.5
|
||
const expectY = (dropY + 50) / 0.5
|
||
check('拖拽松手 ⇒ createNode 带显式坐标(不再交给宿主猜)',
|
||
Boolean(dragCall) && dragCall.auto === false, dragCall ? 'auto=' + dragCall.auto : '未调用')
|
||
check('落点 = 松手点换算出的世界坐标',
|
||
Boolean(dragCall) && Math.abs(dragCall.x - expectX) < 1 && Math.abs(dragCall.y - expectY) < 1,
|
||
dragCall ? '(' + dragCall.x + ',' + dragCall.y + ') 期望 (' + expectX + ',' + expectY + ')' : '未调用')
|
||
check('拖拽只插入一次(松手后的 click 被抑制)',
|
||
await page.evaluate(() => window.__calls.nodes.length === 1),
|
||
'调用次数=' + await page.evaluate(() => window.__calls.nodes.length))
|
||
// 松手在面板里(不在画布上)⇒ 取消,不建节点
|
||
await page.mouse.move(btnBox.x + btnBox.width / 2, btnBox.y + btnBox.height / 2)
|
||
await page.mouse.down()
|
||
await page.mouse.move(btnBox.x + 40, btnBox.y - 60, { steps: 4 })
|
||
await page.mouse.up()
|
||
await page.waitForTimeout(150)
|
||
check('松手点不在画布上 ⇒ 不建节点', await page.evaluate(() => window.__calls.nodes.length === 1),
|
||
'调用次数=' + await page.evaluate(() => window.__calls.nodes.length))
|
||
await page.evaluate(() => { const cv = document.getElementById('fakeCanvas'); if (cv) cv.remove(); window.__calls.nodes.length = 0 })
|
||
|
||
// ---- 插参考图(blob → dataURL) ----
|
||
// 拖拽用例松手时会设 justDragged 抑制 400ms 内的 click(防「松手回到按钮上又插一次」),
|
||
// 这里必须等过那个窗口,否则 click 被吞、偶发「未调用 createImageNode」(实测 3 次里 1 次)。
|
||
await page.waitForTimeout(460)
|
||
await page.locator('#hostA .iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '插入参考图' }).click()
|
||
// 15000 而不是 8000:这条要等一次真实 fetch(blob → FileReader → dataURL),慢机器上 8s 会偶发超时
|
||
const imgCall = await poll(() => page.evaluate(() => window.__calls.images[0] || null), 15000)
|
||
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 preview = (box.querySelector('.iwb-ss-text') || {}).textContent || ''
|
||
// 占位符名一律从 data-var-name 取:placeholder 现在可能是 desc 说明文字,
|
||
// 拿它反推槽位名会把「有 desc 的风格」全判成声明落空
|
||
const varNameOf = (i) => i.getAttribute('data-var-name') || i.getAttribute('placeholder')
|
||
const names = inputs.map(varNameOf)
|
||
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: varNameOf(i),
|
||
label: (i.parentNode.querySelector('.iwb-ss-varlabel') || {}).textContent || '',
|
||
placeholder: i.getAttribute('placeholder') || '',
|
||
title: i.getAttribute('title') || '',
|
||
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),
|
||
hasToggle: Boolean(box.querySelector('.iwb-ss-vartoggle')),
|
||
}
|
||
})
|
||
}
|
||
|
||
const undeclared = await openBySearch('探针:未声明占位符')
|
||
check('提示词有占位符、数据没声明的风格也有输入框',
|
||
undeclared.names.length === 3 && undeclared.dead === 0, undeclared.name + ' → ' + undeclared.names.join(','))
|
||
check('每个输入框都有可读标签(不是空串/裸花括号)',
|
||
undeclared.pairs.length === 3 &&
|
||
undeclared.pairs.every((p) => p.label.trim().length > 0 && !/[{}]/.test(p.label)),
|
||
undeclared.pairs.map((p) => p.label + '→{' + p.name + '}').join(', '))
|
||
check('没声明的槽位按「未声明」处理(标签回退成占位符名)',
|
||
undeclared.pairs.every((p) => p.implicit && p.label === p.name.replace(/[_-]+/g, ' ')),
|
||
undeclared.pairs.map((p) => p.label + (p.implicit ? '(implicit)' : '') ).join(', '))
|
||
|
||
// 线上 1411 条声明已全部中文化,{SUBJECT} 这类脏 key 现在能认得中文标签「画面主体」
|
||
const vigo = await openBySearch('黄黑漫画食品小志广告风格')
|
||
const subj = vigo.pairs.find((p) => p.name === 'SUBJECT')
|
||
check('脏 key 的反引号被剥掉,占位符 {SUBJECT} 认回声明过的中文标签',
|
||
Boolean(subj) && subj.label === '画面主体' && !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('中英文混写的 kv_var 都能对上声明(8 个全部 declared)',
|
||
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('变量全部平铺:8 个输入框全可见,且没有折叠按钮',
|
||
mondrian.names.length === 8 && mondrian.visible === 8 && mondrian.hasToggle === false,
|
||
'全部=' + mondrian.names.length + ' 可见=' + mondrian.visible + ' 折叠按钮=' + mondrian.hasToggle)
|
||
|
||
const noVar = await openBySearch('旷野的风')
|
||
check('提示词里没有占位符就不摆空输入框',
|
||
noVar.names.length === 0 && noVar.hasVarLabel === false, noVar.name + ' inputs=' + noVar.names.length)
|
||
|
||
// desc(variable_descs):有说明的变量用中文说明当灰色提示,没有的降级成占位符名
|
||
const withDesc = await openBySearch('东方花茶香氛海报')
|
||
const hasDesc = withDesc.pairs.filter((p) => p.placeholder && p.placeholder !== p.name)
|
||
check('desc 全覆盖的风格:每个输入框都拿到了说明',
|
||
hasDesc.length === withDesc.pairs.length && hasDesc.length > 0,
|
||
'inputs=' + withDesc.pairs.length + ' 带 desc=' + hasDesc.length)
|
||
const descMix = await openBySearch('探针:desc 混合')
|
||
const noDesc = descMix.pairs.filter((p) => p.placeholder === p.name)
|
||
check('带 desc 的变量用 desc 做 placeholder,而不是英文占位符名',
|
||
hasDesc.length > 0 && hasDesc.every((p) => /[\u4e00-\u9fa5]/.test(p.placeholder)),
|
||
hasDesc.slice(0, 3).map((p) => p.label + ' → 「' + p.placeholder.slice(0, 22) + '」').join(' | '))
|
||
check('完整 desc 同时挂在 title 上(长说明能看全)',
|
||
hasDesc.length > 0 && hasDesc.every((p) => p.title === p.placeholder),
|
||
hasDesc[0] ? '样例:' + hasDesc[0].title : '没有带 desc 的变量')
|
||
check('没有 desc 的变量降级成占位符名,不留空 placeholder',
|
||
noDesc.length === 1 && noDesc[0].placeholder === '标题' && descMix.pairs.length === 2,
|
||
descMix.pairs.map((p) => p.label + '→' + p.placeholder).join(', '))
|
||
check('加了 desc 后仍能正确算出未填数量(不把提示文字当成已填内容)',
|
||
withDesc.names.length === withDesc.pairs.length && withDesc.dead === 0,
|
||
'inputs=' + withDesc.names.length + ' dead=' + withDesc.dead)
|
||
|
||
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)
|
||
|
||
// ---- 回归守门:宿主资源中心的容器是 flex 子项,插件容器不能「按内容宽度收缩」 ----
|
||
// 真实宿主:.iwb-full-main{display:flex} > .iwb-full-panel-plugin(裸 div,无 width)。
|
||
// 之前只给了 min-width:0,容器按内容算出 664px,而父容器 1040 ⇒ 右侧留一大片空白。
|
||
const flexFill = await page.evaluate(() => {
|
||
const stage = document.getElementById('stage')
|
||
const wrap = document.createElement('div')
|
||
// position:fixed 让它脱离 stage 的 flex 布局(stage 已被 hostA/hostB 占满,放进去会被 shrink 压窄);
|
||
// pointer-events:none 防止它盖住 hostA 导致后续点击超时。
|
||
// 尺寸按用户实际场景取:总宽 1360 - 左栏 320 = 面板 1040
|
||
wrap.style.cssText = 'display:flex;position:fixed;left:0;top:0;width:1360px;height:640px;z-index:9999;background:#fff;pointer-events:none'
|
||
const left = document.createElement('div')
|
||
left.style.cssText = 'flex:0 0 320px'
|
||
const hostC = document.createElement('div')
|
||
hostC.id = 'hostC'
|
||
wrap.appendChild(left)
|
||
wrap.appendChild(hostC)
|
||
stage.appendChild(wrap)
|
||
window.__hostC = hostC
|
||
window.__calls.panels[0].mount(hostC)
|
||
const r = hostC.querySelector('.iwb-ss-root')
|
||
const grid = hostC.querySelector('.iwb-ss-grid')
|
||
return {
|
||
hostW: Math.round(hostC.getBoundingClientRect().width),
|
||
rootW: Math.round(r.getBoundingClientRect().width),
|
||
gridW: Math.round(grid.getBoundingClientRect().width),
|
||
avail: 1360 - 320,
|
||
}
|
||
})
|
||
check('flex 父容器下插件容器撑满剩余宽度(不再按内容宽度收缩)',
|
||
Math.abs(flexFill.rootW - flexFill.avail) <= 2 && Math.abs(flexFill.hostW - flexFill.avail) <= 2,
|
||
'host=' + flexFill.hostW + ' root=' + flexFill.rootW + ' 可用=' + flexFill.avail)
|
||
// 选中一个风格再量:宽档是「左栅格 + 右详情」常驻两栏,两栏之和必须等于容器宽,否则右边就是空白
|
||
await page.evaluate(() => {
|
||
const c = window.__hostC.querySelector('.iwb-ss-card')
|
||
if (c) c.click()
|
||
})
|
||
await page.waitForTimeout(320)
|
||
const flexCols = await page.evaluate(() => {
|
||
const hostC = window.__hostC
|
||
const q = (s) => Math.round(hostC.querySelector(s).getBoundingClientRect().width)
|
||
const cards = Array.from(hostC.querySelectorAll('.iwb-ss-card'))
|
||
const first = cards[0]
|
||
const det = hostC.querySelector('.iwb-ss-detail')
|
||
const foot = hostC.querySelector('.iwb-ss-dfoot')
|
||
const btn = hostC.querySelectorAll('.iwb-ss-dfoot .iwb-ss-btn')
|
||
// 同一行的卡片数 = 与第一张 top 相同的卡片数;卡片宽度用来确认「拉宽只加列、不撑宽卡片」
|
||
return {
|
||
root: q('.iwb-ss-root'),
|
||
grid: q('.iwb-ss-grid'),
|
||
detail: q('.iwb-ss-detail'),
|
||
detailSW: det ? det.scrollWidth : 0,
|
||
footW: foot ? Math.round(foot.getBoundingClientRect().width) : 0,
|
||
footSW: foot ? foot.scrollWidth : 0,
|
||
btnW: btn.length ? Array.from(btn).map((b) => Math.round(b.getBoundingClientRect().width)) : [],
|
||
btnSW: btn.length ? Array.from(btn).map((b) => b.scrollWidth) : [],
|
||
btnFs: btn.length ? Array.from(btn).map((b) => getComputedStyle(b).fontSize) : [],
|
||
bodyW: hostC.querySelector('.iwb-ss-dbody') ? Math.round(hostC.querySelector('.iwb-ss-dbody').getBoundingClientRect().width) : 0,
|
||
bodySW: hostC.querySelector('.iwb-ss-dbody') ? hostC.querySelector('.iwb-ss-dbody').scrollWidth : 0,
|
||
cardW: first ? Math.round(first.getBoundingClientRect().width) : 0,
|
||
perRow: cards.filter((c) => Math.abs(c.getBoundingClientRect().top - first.getBoundingClientRect().top) < 2).length,
|
||
}
|
||
})
|
||
check('宽档两栏横向无空白(栅格 + 详情 = 容器宽)',
|
||
Math.abs(flexCols.grid + flexCols.detail - flexCols.root) <= 2,
|
||
'grid=' + flexCols.grid + ' detail=' + flexCols.detail + ' root=' + flexCols.root)
|
||
check('面板 1040 时栅格一行 ≥4 张,且卡片不被撑宽(越宽只加列)',
|
||
flexCols.perRow >= 4 && flexCols.cardW > 90 && flexCols.cardW <= 150,
|
||
'每行=' + flexCols.perRow + ' 卡片宽=' + flexCols.cardW)
|
||
check('详情栏内部不横向溢出(按钮/长标签不撑出右边缘)',
|
||
flexCols.detailSW <= flexCols.detail + 1 && flexCols.footSW <= flexCols.footW + 1,
|
||
'detail=' + flexCols.detail + '/sw' + flexCols.detailSW + ' body=' + flexCols.bodyW + '/sw' + flexCols.bodySW +
|
||
' foot=' + flexCols.footW + '/sw' + flexCols.footSW + ' btn=' + JSON.stringify(flexCols.btnW) +
|
||
'/sw' + JSON.stringify(flexCols.btnSW) + '/fs' + JSON.stringify(flexCols.btnFs))
|
||
await page.locator('#hostC').screenshot({ path: path.resolve(HERE, 'shot-fill.png') }).catch(() => {})
|
||
await page.locator('#hostC .iwb-ss-detail').screenshot({ path: path.resolve(HERE, 'shot-detail.png') }).catch(() => {})
|
||
|
||
// 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 个占位符全部平铺
|
||
await page.evaluate(() => { window.__hostA.style.width = '980px'; window.__hostA.style.height = '1180px' })
|
||
await page.waitForTimeout(260)
|
||
// 变量特写拍「东方花茶香氛海报」:它同时有 19 个变量(平铺压力)和 4 条 desc(填写提示),
|
||
// 一张图能覆盖 desc 渲染 + 无 desc 降级两种形态
|
||
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)
|
||
|
||
// ---- 样式节点(v1.3.0 / 2026-11-14)----
|
||
// 用户要求:样式节点只负责「把变量填进模板」,节点上不放生成按钮;能连生图 / 组合 / 批量 / 做事二次编辑。
|
||
// 插件侧这一半要验的是:变体参数、节点体结构、变量写回语义、参考图开关、以及「重渲染不重建 DOM」。
|
||
const variant = await page.evaluate(() => {
|
||
const v = (window.__calls.variants || [])[0]
|
||
if (!v) return null
|
||
return {
|
||
id: v.id, title: v.title, ports: v.ports, height: v.height,
|
||
hasRun: typeof v.run === 'function', hasRender: typeof v.render === 'function',
|
||
hasDispose: typeof v.render === 'function' && typeof v.render.dispose === 'function',
|
||
}
|
||
})
|
||
check('注册 style 变体:只出不入端口、无 run(节点上不会有生成按钮)、带 render',
|
||
Boolean(variant) && variant.id === 'style' && variant.ports && variant.ports.in === false &&
|
||
variant.ports.out === true && !variant.hasRun && variant.hasRender,
|
||
JSON.stringify(variant))
|
||
|
||
// 建一个和宿主同构的容器(宿主给的是 .iwb-node-body.iwb-plugin-node-body,内部由插件自己画)
|
||
const nodeBody = await page.evaluate(() => {
|
||
const v = (window.__calls.variants || [])[0]
|
||
if (!v || typeof v.render !== 'function') return { built: false }
|
||
const host = document.createElement('div')
|
||
host.className = 'iwb-node-body iwb-plugin-node-body'
|
||
host.id = 'ssnHost'
|
||
// 独立浮到 hostA 右侧拍留档图,避免被面板遮住(hostA 宽 980,视口 1280)
|
||
host.style.cssText = 'width:264px;background:#fff;position:fixed;left:1000px;top:20px;z-index:9999'
|
||
document.getElementById('stage').appendChild(host)
|
||
window.__ssnHost = host
|
||
window.__updates = []
|
||
window.__ssnProps = { nodes: [], edges: [], editingBody: false, setEditingBody: () => {}, onUpdate: (id, patch) => window.__updates.push({ id: id, patch: patch }) }
|
||
const node = {
|
||
id: 'n_style1', type: 'plugin:style-source:style', x: 0, y: 0, data: {
|
||
variant: 'style', styleId: 'st1', name: 'Vigo 银调夜景', code: 'VIGO-08', outKind: 'prompt',
|
||
promptTpl: 'a {角色} in {场景}, {留空变量}',
|
||
varMeta: [
|
||
{ n: '角色', l: '角色', d: '如:银发少女', x: 1 },
|
||
{ n: '场景', l: '场景', d: '', x: 1 },
|
||
{ n: '留空变量', l: '留空变量', d: '', x: 0 },
|
||
],
|
||
vars: { 角色: '银发少女' }, text: 'a 银发少女 in {场景}, {留空变量}',
|
||
preview: 'https://malongan.github.io/style-source/previews/probe.webp',
|
||
refOn: true, refUrl: 'https://example.com/s.png', refName: 'style.png', collapsed: false,
|
||
},
|
||
}
|
||
window.__ssnNode = node
|
||
v.render(node, window.__ssnProps, host)
|
||
const q = (s) => host.querySelector(s)
|
||
const rows = [...host.querySelectorAll('.iwb-ssn-row')]
|
||
return {
|
||
built: true,
|
||
name: q('.iwb-ssn-name') ? q('.iwb-ssn-name').textContent : '',
|
||
code: q('.iwb-ssn-code') ? q('.iwb-ssn-code').textContent : '',
|
||
rowCount: rows.length,
|
||
labels: rows.map((r) => r.querySelector('label').textContent),
|
||
implicit: rows.map((r) => r.querySelector('label').className),
|
||
placeholders: rows.map((r) => r.querySelector('input').placeholder),
|
||
values: rows.map((r) => r.querySelector('input').value),
|
||
refChecked: q('.iwb-ssn-ref input') ? q('.iwb-ssn-ref input').checked : null,
|
||
refText: q('.iwb-ssn-ref span') ? q('.iwb-ssn-ref span').textContent : '',
|
||
foot: q('.iwb-ssn-foot') ? q('.iwb-ssn-foot').textContent : '',
|
||
hasRunBtn: [...host.querySelectorAll('button')].some((b) => /运行|生成/.test(b.textContent)),
|
||
thumbShown: (() => { const t = q('.iwb-ssn-thumb'); return Boolean(t) && t.style.display !== 'none' && t.getBoundingClientRect().width > 20 })(),
|
||
rowH: rows.length ? Math.round(rows[0].getBoundingClientRect().height) : 0,
|
||
}
|
||
})
|
||
check('样式节点体:名称 / 编号 / 变量行齐备,变量全部露出(不折叠)',
|
||
nodeBody.built && nodeBody.name === 'Vigo 银调夜景' && nodeBody.code === 'VIGO-08' && nodeBody.rowCount === 3,
|
||
JSON.stringify(nodeBody))
|
||
check('变量行是单行布局(28px 级),不是「label 一行 + 输入一行」的 56px',
|
||
nodeBody.built && nodeBody.rowH > 20 && nodeBody.rowH <= 32, 'rowH=' + nodeBody.rowH)
|
||
check('样式节点上没有「运行 / 生成」按钮(出图交给下游生图节点)',
|
||
nodeBody.built && nodeBody.hasRunBtn === false, 'hasRunBtn=' + nodeBody.hasRunBtn)
|
||
check('未填变量用 {原样} 当 placeholder(不是空白框),已填的值回填,未声明的变量标签弱化',
|
||
nodeBody.built && nodeBody.placeholders[1] === '{场景}' && nodeBody.placeholders[2] === '{留空变量}' &&
|
||
nodeBody.values[0] === '银发少女' && nodeBody.values[1] === '' && /is-implicit/.test(nodeBody.implicit[2]),
|
||
JSON.stringify({ ph: nodeBody.placeholders, val: nodeBody.values, cls: nodeBody.implicit }))
|
||
check('缩略图占 56px 方块并显示(无预览图时整块不占位,名称不会无缘无故右移)',
|
||
nodeBody.built && nodeBody.thumbShown === true, 'thumbShown=' + nodeBody.thumbShown)
|
||
check('默认勾选「示例图作参考」,文案写明会带上这张图',
|
||
nodeBody.built && nodeBody.refChecked === true && nodeBody.refText === '示例图作参考',
|
||
JSON.stringify({ checked: nodeBody.refChecked, text: nodeBody.refText }))
|
||
// 留档:节点体实际长什么样(3 个变量 + 参考图开关 + 底栏提示)
|
||
await page.locator('#ssnHost').screenshot({ path: path.resolve(HERE, 'shot-style-node.png') }).catch(() => {})
|
||
console.log('· 截图:' + path.resolve(HERE, 'shot-style-node.png'))
|
||
|
||
const varCommit = await page.evaluate(async () => {
|
||
const host = window.__ssnHost
|
||
const inputs = [...host.querySelectorAll('.iwb-ssn-row input')]
|
||
window.__updates.length = 0
|
||
inputs[1].value = '霓虹街头'
|
||
inputs[1].dispatchEvent(new Event('input', { bubbles: true }))
|
||
const duringDebounce = window.__updates.length
|
||
await new Promise((r) => setTimeout(r, 420))
|
||
const last = window.__updates[window.__updates.length - 1]
|
||
return {
|
||
duringDebounce: duringDebounce,
|
||
count: window.__updates.length,
|
||
vars: last && last.patch.vars,
|
||
text: last && last.patch.text,
|
||
sameCall: Boolean(last && last.patch && last.patch.vars && typeof last.patch.text === 'string'),
|
||
}
|
||
})
|
||
check('变量输入 300ms 防抖后才提交(不是每敲一个字就刷一次图缓存与撤销历史)',
|
||
varCommit.duringDebounce === 0 && varCommit.count >= 1, JSON.stringify(varCommit))
|
||
check('vars 与 text 在同一次 onUpdate 写回;新值已替换、留空的仍保留 {原样}',
|
||
varCommit.sameCall && varCommit.vars['场景'] === '霓虹街头' &&
|
||
String(varCommit.text).includes('霓虹街头') && String(varCommit.text).includes('{留空变量}'),
|
||
JSON.stringify({ vars: varCommit.vars, text: varCommit.text }))
|
||
|
||
const refToggle = await page.evaluate(() => {
|
||
const host = window.__ssnHost
|
||
const chk = host.querySelector('.iwb-ssn-ref input')
|
||
window.__updates.length = 0
|
||
chk.checked = false
|
||
chk.dispatchEvent(new Event('change', { bubbles: true }))
|
||
const off = window.__updates[0]
|
||
chk.checked = true
|
||
chk.dispatchEvent(new Event('change', { bubbles: true }))
|
||
const on = window.__updates[1]
|
||
return {
|
||
offPatch: off && off.patch, onPatch: on && on.patch,
|
||
label: host.querySelector('.iwb-ssn-ref span').textContent,
|
||
tone: host.querySelector('.iwb-ssn-ref').className,
|
||
}
|
||
})
|
||
check('参考图开关只改 refOn 一个字段(不增删节点 ⇒ 取消勾选不会在画布上留孤儿)',
|
||
refToggle.offPatch && refToggle.offPatch.refOn === false && Object.keys(refToggle.offPatch).length === 1 &&
|
||
refToggle.onPatch && refToggle.onPatch.refOn === true,
|
||
JSON.stringify(refToggle))
|
||
|
||
// 关键回归:宿主 onUpdate 之后会再调一次 render。若插件每次重建 DOM,输入框就会失焦
|
||
//(表现是「敲一个字光标就跳走」)。这里直接对比渲染前后是不是同一个 input 元素,
|
||
// 并把「用户正在输入、还没提交」的值设成和数据里不同的字符串 —— 渲染后必须原样保留。
|
||
const rerender = await page.evaluate(() => {
|
||
const host = window.__ssnHost
|
||
const v = window.__calls.variants[0]
|
||
const input = host.querySelectorAll('.iwb-ssn-row input')[1]
|
||
input.focus()
|
||
input.value = '正在输入中'
|
||
const node = JSON.parse(JSON.stringify(window.__ssnNode))
|
||
node.data.vars = Object.assign({}, node.data.vars, { 场景: '霓虹街头' })
|
||
v.render(node, window.__ssnProps, host)
|
||
const after = host.querySelectorAll('.iwb-ssn-row input')[1]
|
||
return {
|
||
sameEl: input === after,
|
||
keptTyping: after.value,
|
||
rows: host.querySelectorAll('.iwb-ssn-row').length,
|
||
focusKept: document.activeElement === after,
|
||
}
|
||
})
|
||
check('二次渲染复用同一批 DOM:输入框没被重建,正在编辑的值不被 data 覆盖(不失焦不跳字)',
|
||
rerender.sameEl && rerender.rows === 3 && rerender.keptTyping === '正在输入中' && rerender.focusKept,
|
||
JSON.stringify(rerender))
|
||
|
||
const collapse = await page.evaluate(() => {
|
||
const host = window.__ssnHost
|
||
const btn = host.querySelector('.iwb-ssn-toggle')
|
||
window.__updates.length = 0
|
||
btn.click()
|
||
return { patch: window.__updates[0] && window.__updates[0].patch, text: btn.textContent }
|
||
})
|
||
check('收起变量只写回 collapsed,不动节点高度(高度由宿主实测,写 h 会把自动高度锁死)',
|
||
collapse.patch && collapse.patch.collapsed === true && !('h' in collapse.patch),
|
||
JSON.stringify(collapse))
|
||
|
||
const footBtns = await page.evaluate(() => {
|
||
const btns = [...document.querySelectorAll('#hostA .iwb-ss-dfoot .iwb-ss-btn')]
|
||
return {
|
||
texts: btns.map((b) => b.textContent),
|
||
widths: btns.map((b) => Math.round(b.getBoundingClientRect().width)),
|
||
clipped: btns.filter((b) => b.scrollWidth > b.clientWidth + 1).length,
|
||
rows: new Set(btns.map((b) => Math.round(b.getBoundingClientRect().top))).size,
|
||
}
|
||
})
|
||
check('详情页底部三颗按钮(新增「样式节点」,原「参考图 / 提示词」保持原名)单行均分',
|
||
footBtns.texts.length === 3 && footBtns.texts[0] === '样式节点' &&
|
||
footBtns.texts[1] === '插入参考图' && footBtns.texts[2] === '插入提示词' &&
|
||
footBtns.rows === 1 && footBtns.clipped === 0 &&
|
||
Math.max(...footBtns.widths) - Math.min(...footBtns.widths) <= 2,
|
||
JSON.stringify(footBtns))
|
||
|
||
await page.evaluate(() => { if (window.__ssnHost) { window.__ssnHost.remove(); window.__ssnHost = null } })
|
||
|
||
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)
|
||
})
|