Files
iwb-plugins-desktop/browser/tools/harness.mjs
T
qiqi f7e2b786c7
validate / validate (push) Canceled after 0s
feat(browser)!: 1.4.0 工具栏重做(缩放设定框 + 加载态 + 站内地址回填)
配合宿主 v3.25.29(修好了「网页压住地址栏」与「内容不跟画布缩放」)。

- 工具栏:← → ⟳(加载中变「停止」)、地址栏、− 100% + 缩放设定框(可直接输入
  百分比,双击回 100%,25%~300%)、↗ 独立窗口打开、✕ 关闭网页(paused,⟳ 可恢复)
- 状态回传:监听宿主 document 上的 iwb-cwv-state,站内跳转后地址栏跟随真实地址
- 标题为空时自动用站点名,多个网页节点并排时分得清
- 图标改 SVG(测试桩没有 createElementNS 时退回文字图标)
- 节点默认 560x520,数据新增 zoom / paused
- render 挂 dispose,销毁时清掉事件路由表引用
- harness 62 项(新增缩放框/暂停恢复/状态回填/禁用态断言)
2026-11-19 07:14:06 +08:00

426 lines
20 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.
// 应用内浏览器插件的本地契约测试(纯 node,不依赖 playwright / 真浏览器)。
//
// 用最小 DOM / window stub 跑真实 src/index.js(IIFE),验证:
// manifest 字段 / 面板注册 / CSS 脚本执行时就注入 / URL 补全与校验 /
// 地址栏提交与书签点击都走 open_browser_window 命令 / 命令失败回退 window.open /
// 无 Tauri 回退 / 书签自定义解析 /
// 导航控制按钮的启用-禁用 / 后退走 browser_control / 状态行显示当前网址 /
// 反复 mount 不累积 settings 订阅。
//
// 运行:node browser/tools/harness.mjs (退出码 0 = 全过)
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import vm from 'node:vm'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const ENTRY = path.resolve(HERE, '../src/index.js')
const source = readFileSync(ENTRY, 'utf8')
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
// ---------- 极简 DOM stub(带可触发的事件监听) ----------
function makeNode(tag) {
const node = {
tagName: String(tag || 'div').toUpperCase(),
style: {},
attrs: {},
children: [],
className: '',
_text: '',
_listeners: {},
classList: {
_set: new Set(),
add(c) { this._set.add(c) },
remove(c) { this._set.delete(c) },
contains(c) { return this._set.has(c) },
},
set textContent(v) { this._text = String(v) },
get textContent() { return this._text },
setAttribute(k, v) { this.attrs[k] = String(v) },
getAttribute(k) { return this.attrs[k] },
removeAttribute(k) { delete this.attrs[k] },
appendChild(c) { this.children.push(c); return c },
addEventListener(name, fn) { (this._listeners[name] || (this._listeners[name] = [])).push(fn) },
fire(name, ev) {
const e = Object.assign({ preventDefault() {}, stopPropagation() {}, key: '' }, ev || {})
;(this._listeners[name] || []).forEach((fn) => fn(e))
},
value: '',
focus() { this._focused = true },
blur() { this._focused = false },
select() { this._selected = true },
set innerHTML(v) { if (v === '') this.children = [] }
}
return node
}
function makeDom() {
const styles = new Map()
return {
_styles: styles,
createElement(tag) { return makeNode(tag) },
createTextNode(t) { return { _text: String(t), nodeType: 3 } },
_listeners: {},
activeElement: null,
addEventListener(name, fn) { (this._listeners[name] || (this._listeners[name] = [])).push(fn) },
dispatchEvent(ev) { (this._listeners[ev.type] || []).forEach((fn) => fn(ev)); return true },
getElementById(id) { return styles.get(id) || null },
head: { appendChild(n) { styles.set(n.id, n) } },
documentElement: { appendChild(n) { styles.set(n.id, n) } }
}
}
function runPlugin({ invokeImpl, prefs } = {}) {
const calls = []
const doc = makeDom()
let registered = null
let panel = null
let nodeType = null
const settings = Object.assign({}, prefs || {})
const settingsListeners = []
let unsubscribed = 0
const hostObj = {
IWBPluginHost: {
register(manifest, factory) {
registered = manifest
factory({
log() {},
settings: {
get(k) { return settings[k] },
onChange(fn) {
settingsListeners.push(fn)
return function () { unsubscribed++ }
}
},
ui: {
registerPanel(p) { panel = p }
},
nodes: {
register(v) { nodeType = v; return true }
}
})
}
},
__TAURI__: invokeImpl
? { core: { invoke: (name, args) => { calls.push({ name, args }); return invokeImpl(name, args) } } }
: undefined,
open(url) { calls.push({ name: 'window.open', args: { url } }); return null },
URL
}
const sandbox = {
window: hostObj, globalThis: hostObj,
document: doc, URL, console, Promise, setTimeout, clearTimeout
}
vm.runInNewContext(source, sandbox, { filename: 'browser/src/index.js' })
return {
registered, panel, calls, doc, nodeType,
get unsubscribed() { return unsubscribed },
fireSetting: (name) => settingsListeners.forEach((fn) => fn(name)),
setSetting: (k, v) => { settings[k] = v }
}
}
function mountPanel(panel, doc) {
const root = doc.createElement('div')
panel.mount(root)
return root
}
const findCtrl = (root) => root.children.find((c) => c.className === 'iwb-browser-ctrl')
const navButtons = (root) => findCtrl(root).children.filter((c) => c.tagName === 'BUTTON')
const openCalls = (r) => r.calls.filter((c) => c.name === 'open_browser_window')
const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
// 默认:打开成功、browser_state 报「窗口未打开」
const okInvoke = () => (name) => {
if (name === 'browser_state') return Promise.resolve({ open: false, url: '' })
return Promise.resolve(true)
}
// 已打开状态
const openStateInvoke = (url) => (name) => {
if (name === 'browser_state') return Promise.resolve({ open: true, url })
return Promise.resolve(true)
}
// ---------- manifest / 注册 / CSS ----------
{
const { registered, panel, doc } = runPlugin()
check('manifest id = browser', registered && registered.id === 'browser')
// 版本号只在一处维护(package.json),断言改为一致性检查,免得每次发版手工改测试
const pkgVersion = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
check('manifest version 与 package.json 一致(' + pkgVersion + ')',
registered && registered.version === pkgVersion, registered && registered.version)
check('manifest apiVersion = 1', registered && registered.apiVersion === 1)
check('manifest capabilities = panels + nodeTypes', registered && JSON.stringify(registered.capabilities) === '["panels","nodeTypes"]',
registered && JSON.stringify(registered.capabilities))
check('manifest 声明 bookmarks 设置', registered && !!registered.settings.bookmarks)
check('注册了面板 browser-panel', !!panel && panel.id === 'browser-panel' && typeof panel.mount === 'function')
check('CSS 在脚本执行时就注入(未 mount 已存在)', doc.getElementById('iwb-browser-style') !== null)
}
// ---------- mount 结构 ----------
{
const { panel, doc } = runPlugin()
let mountOk = true
let root
try { root = mountPanel(panel, doc) } catch (e) { mountOk = false; console.error(e) }
check('mount 成功', mountOk)
check('面板含地址栏', !!root && root.children.some((c) => c.className === 'iwb-browser-bar'))
check('面板含导航控制条', !!root && !!findCtrl(root))
const grid = root && root.children.find((c) => c.className === 'iwb-browser-grid')
check('默认渲染 4 个书签', !!grid && grid.children.length === 4, grid ? '实际 ' + grid.children.length : '')
}
// ---------- 地址栏提交:补 https + 调命令 ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const root = mountPanel(r.panel, r.doc)
const bar = root.children.find((c) => c.className === 'iwb-browser-bar')
const inputNode = bar.children.find((c) => c.tagName === 'INPUT')
inputNode.value = 'www.baidu.com'
bar.fire('submit', {})
check('地址栏提交调用 open_browser_window', openCalls(r).length === 1,
JSON.stringify(r.calls))
check('URL 自动补 https 且规范化', openCalls(r)[0] && openCalls(r)[0].args.url === 'https://www.baidu.com/',
openCalls(r)[0] ? openCalls(r)[0].args.url : '')
}
// ---------- 书签点击:调命令 ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const root = mountPanel(r.panel, r.doc)
const grid = root.children.find((c) => c.className === 'iwb-browser-grid')
grid.children[0].fire('click', {})
check('书签点击调用 open_browser_window', openCalls(r).length === 1)
check('书签 URL 是合法 https', openCalls(r)[0] && /^https:\/\//.test(openCalls(r)[0].args.url),
openCalls(r)[0] ? openCalls(r)[0].args.url : '')
}
// ---------- 导航控制:未打开禁用 / 已打开启用 / 状态行 / 后退命令 ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const root = mountPanel(r.panel, r.doc)
await tick()
const btns = navButtons(root)
check('窗口未打开时 4 个导航按钮全部禁用',
btns.length === 4 && btns.every((b) => b.attrs.disabled === 'disabled'),
JSON.stringify(btns.map((b) => b.attrs.disabled)))
const o = runPlugin({ invokeImpl: openStateInvoke('https://example.com/x') })
const oroot = mountPanel(o.panel, o.doc)
await tick()
const obtns = navButtons(oroot)
check('窗口已打开时 4 个导航按钮启用',
obtns.length === 4 && obtns.every((b) => b.attrs.disabled === undefined),
JSON.stringify(obtns.map((b) => b.attrs.disabled)))
const stateText = findCtrl(oroot).children.find((c) => c.className === 'iwb-browser-now')
check('状态行显示当前网址', stateText && stateText._text === 'https://example.com/x',
stateText ? stateText._text : '(missing)')
obtns[0].fire('click', {})
await tick()
const ctrlCalls = o.calls.filter((c) => c.name === 'browser_control')
check('后退按钮调用 browser_control(back)',
ctrlCalls.length === 1 && ctrlCalls[0].args.action === 'back', JSON.stringify(ctrlCalls))
obtns[3].fire('click', {})
await tick()
const closeCalls = o.calls.filter((c) => c.name === 'browser_control' && c.args.action === 'close')
check('关闭按钮调用 browser_control(close)', closeCalls.length === 1)
}
// ---------- 命令失败 -> 回退 window.open ----------
{
const r = runPlugin({ invokeImpl: () => Promise.reject(new Error('command missing')) })
const root = mountPanel(r.panel, r.doc)
const grid = root.children.find((c) => c.className === 'iwb-browser-grid')
grid.children[0].fire('click', {})
// catch 是异步微任务,等一轮
await tick()
check('invoke 失败回退 window.open', r.calls.some((c) => c.name === 'window.open'), JSON.stringify(r.calls))
}
// ---------- 无 Tauri -> 直接 window.open ----------
{
const r = runPlugin() // 无 invokeImpl ⇒ 无 __TAURI__
const root = mountPanel(r.panel, r.doc)
const grid = root.children.find((c) => c.className === 'iwb-browser-grid')
grid.children[0].fire('click', {})
check('无 Tauri 直接 window.open', r.calls.length === 1 && r.calls[0].name === 'window.open', JSON.stringify(r.calls))
check('无 Tauri 时导航按钮保持禁用', navButtons(root).every((b) => b.attrs.disabled === 'disabled'))
}
// ---------- 反复 mount 不累积设置订阅 ----------
{
const r = runPlugin()
mountPanel(r.panel, r.doc)
mountPanel(r.panel, r.doc)
mountPanel(r.panel, r.doc)
check('重复 mount 会解掉上一个设置订阅(3 次 mount ⇒ 解绑 2 次)', r.unsubscribed === 2, '实际 ' + r.unsubscribed)
}
// ---------- 自定义书签解析 ----------
{
const r = runPlugin()
r.setSetting('bookmarks', 'MDN | developer.mozilla.org\n# 注释行\n\nOpenAI|openai.com')
const root = mountPanel(r.panel, r.doc)
const grid = root.children.find((c) => c.className === 'iwb-browser-grid')
check('自定义书签按行解析(跳过注释/空行)', grid.children.length === 2, '实际 ' + grid.children.length)
check('书签自动补协议', grid.children[0].children.some((c) => c._text === 'developer.mozilla.org'),
JSON.stringify(grid.children[0].children.map((c) => c._text)))
}
// ---------- 画布内网页节点 ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const nt = r.nodeType
check('注册了画布节点类型 web', !!nt && nt.id === 'web' && nt.title === '网页')
check('节点类型无端口(网页节点不参与连线)', JSON.stringify(nt.ports) === '{"in":false,"out":false}')
check('节点类型默认数据含 url/zoom/paused',
nt.defaults && 'url' in nt.defaults && nt.defaults.zoom === 1 && nt.defaults.paused === false,
JSON.stringify(nt.defaults))
check('节点类型带自定义渲染函数', typeof nt.render === 'function')
const updates = []
const props = { onUpdate(id, patch) { updates.push({ id, patch }) } }
const host = r.doc.createElement('div')
const node = { id: 'n1', data: { url: '' } }
nt.render(node, props, host)
check('节点体切成 flex 列布局(iwb-cwv-body)', host.classList.contains('iwb-cwv-body'))
const bar = host.children.find((c) => c.className === 'iwb-cwv-bar')
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
check('节点体含工具栏与内容区', !!bar && !!stage)
check('工具栏在内容区之前(原生视图只盖内容区,不会压住按钮)',
host.children.indexOf(bar) === 0 && host.children.indexOf(stage) === 1)
const anchor = stage && stage.children.find((c) => c.className === 'iwb-cwv-anchor')
check('内容区有原生 webview 锚点', !!anchor)
check('锚点带节点 id(宿主据此摆位置)', anchor && anchor.attrs['data-iwb-cwv'] === 'n1',
anchor && JSON.stringify(anchor.attrs))
check('空地址时不写锚点 url', anchor && anchor.attrs['data-iwb-cwv-url'] === undefined)
const input = bar.children.find((c) => c.tagName === 'INPUT')
const navBtns = bar.children.filter((c) => c.tagName === 'BUTTON')
check('工具栏 5 个动作按钮(← → ⟳ ↗ ✕)', navBtns.length === 5, '实际 ' + navBtns.length)
check('地址栏初始禁用全部动作按钮', navBtns.every((b) => b.disabled === true))
// 缩放设定框:− [100%] +,百分比是可输入的
const zoomBox = bar.children.find((c) => c.className === 'iwb-cwv-zoom')
const zpct = zoomBox && zoomBox.children.find((c) => c.tagName === 'INPUT')
const zoomBtns = zoomBox ? zoomBox.children.filter((c) => c.tagName === 'BUTTON') : []
check('工具栏有缩放设定框「− 100% +」',
!!zpct && zpct.value === '100%' && zoomBtns.length === 2, zpct && zpct.value)
check('缩放框排在地址栏之后、关闭按钮之前',
bar.children.indexOf(input) < bar.children.indexOf(zoomBox)
&& bar.children.indexOf(zoomBox) < bar.children.indexOf(navBtns[4]))
check('锚点默认缩放 1', anchor.attrs['data-iwb-cwv-zoom'] === '1', JSON.stringify(anchor.attrs))
// 输入网址回车 → 写节点数据 + 立刻更新锚点(不等 React 重渲染)
input.value = 'baidu.com'
input.fire('keydown', { key: 'Enter' })
check('回车提交写回节点 data.url', updates.length === 1 && updates[0].patch.url === 'https://baidu.com/',
JSON.stringify(updates))
check('空标题时自动用站点名(多个网页节点才分得清)',
updates[0] && updates[0].patch.title === 'baidu.com', JSON.stringify(updates[0] && updates[0].patch))
check('回车后锚点 url 同步(宿主下一帧即可导航)',
anchor.attrs['data-iwb-cwv-url'] === 'https://baidu.com/', JSON.stringify(anchor.attrs))
check('填了网址后动作按钮启用', navBtns.every((b) => b.disabled === false))
// 控制按钮 → 发 canvas_webview_action(不是 browser_control)
navBtns[0].fire('click', {})
const acts = r.calls.filter((c) => c.name === 'canvas_webview_action')
check('后退按钮走 canvas_webview_action(back)',
acts.length === 1 && acts[0].args.action === 'back' && acts[0].args.id === 'n1', JSON.stringify(acts))
// 缩放:+ 按钮一次 +10%,并把值写回节点;锚点属性立刻更新(宿主下一帧推 zoom)
zoomBtns[1].fire('click', {})
check('放大按钮把缩放调到 110%', zpct.value === '110%' && anchor.attrs['data-iwb-cwv-zoom'] === '1.1',
zpct.value + ' / ' + anchor.attrs['data-iwb-cwv-zoom'])
check('缩放值写回节点数据', updates.some((u) => u.patch.zoom === 1.1), JSON.stringify(updates))
zoomBtns[0].fire('click', {})
check('缩小按钮把缩放调回 100%', zpct.value === '100%', zpct.value)
// 直接输入百分比
zpct.value = '150%'
zpct.fire('keydown', { key: 'Enter' })
check('缩放框支持直接输入百分比', anchor.attrs['data-iwb-cwv-zoom'] === '1.5', anchor.attrs['data-iwb-cwv-zoom'])
zpct.value = '900%'
zpct.fire('keydown', { key: 'Enter' })
check('缩放上限 300%', anchor.attrs['data-iwb-cwv-zoom'] === '3', anchor.attrs['data-iwb-cwv-zoom'])
zpct.value = '10%'
zpct.fire('keydown', { key: 'Enter' })
check('缩放下限 25%', anchor.attrs['data-iwb-cwv-zoom'] === '0.25', anchor.attrs['data-iwb-cwv-zoom'])
// ✕ 暂停:写 paused 到锚点与节点数据(宿主要看到它才不会立刻重建视图)
const closeBtn = navBtns[4]
closeBtn.fire('click', {})
check('✕ 把节点标记为 paused(宿主据此关掉视图并保持关闭)',
anchor.attrs['data-iwb-cwv-paused'] === '1'
&& updates.some((u) => u.patch.paused === true), JSON.stringify(anchor.attrs))
check('✕ 之后给出可继续的提示', /已关闭/.test(stage.children.find((c) => c.className === 'iwb-cwv-empty')._text))
// 暂停态点 ⟳:恢复加载(先解除 paused,再让宿主重建)
const beforeResume = r.calls.filter((c) => c.name === 'canvas_webview_action').length
navBtns[2].fire('click', {})
check('暂停态点 ⟳ 恢复加载(不向已关闭的视图发命令)',
anchor.attrs['data-iwb-cwv-paused'] === undefined
&& updates.some((u) => u.patch.paused === false)
&& r.calls.filter((c) => c.name === 'canvas_webview_action').length === beforeResume,
JSON.stringify(updates.slice(-2)))
// 宿主回报状态:站内跳转后的真实地址要回填地址栏,加载中 ⟳ 变成「停止」
r.doc.dispatchEvent({ type: 'iwb-cwv-state', detail: { id: 'n1', loading: true, url: 'https://baidu.com/s?wd=x' } })
check('站内跳转后地址栏跟着页面地址走', input.value === 'https://baidu.com/s?wd=x', input.value)
check('加载中 ⟳ 变「停止」', navBtns[2].getAttribute('data-act') === 'stop',
navBtns[2].getAttribute('data-act'))
r.doc.dispatchEvent({ type: 'iwb-cwv-state', detail: { id: 'n1', loading: false, url: 'https://baidu.com/s?wd=x' } })
check('加载完成 ⟳ 复原', navBtns[2].getAttribute('data-act') === 'reload')
// 重渲染不能覆盖正在编辑的输入框(否则每敲一个字都被顶回去)
node.data.url = 'https://www.baidu.com/'
input.value = 'zhihu.com' // 用户正在输入,还没回车
r.doc.activeElement = input
nt.render(node, props, host)
check('重渲染不覆盖正在编辑的输入', input.value === 'zhihu.com', input.value)
// 非法地址:标红且不写数据
r.doc.activeElement = null
const before = updates.length
input.value = 'javascript:alert(1)'
input.fire('keydown', { key: 'Enter' })
check('非法协议被拒绝且不写回', updates.length === before && input.attrs['aria-invalid'] === 'true',
JSON.stringify(input.attrs))
}
// ---------- 无 Tauri 时节点给出明确提示 ----------
{
const r = runPlugin()
const nt = r.nodeType
const host = r.doc.createElement('div')
nt.render({ id: 'n2', data: { url: 'https://www.baidu.com/' } }, { onUpdate() {} }, host)
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
const empty = stage.children.find((c) => c.className === 'iwb-cwv-empty')
check('网页版节点显示「需要桌面客户端」提示', /桌面客户端/.test(empty._text), empty._text)
}
// ---------- 旧客户端(有 Tauri、但没有画布 webview 引擎)必须提示升级 ----------
{
const r = runPlugin({ invokeImpl: okInvoke() })
const nt = r.nodeType
const host = r.doc.createElement('div')
nt.render({ id: 'n3', data: { url: 'https://www.baidu.com/' } }, { onUpdate() {} }, host)
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
const empty = stage.children.find((c) => c.className === 'iwb-cwv-empty')
check('旧客户端(无 canvas-webview 引擎)提示升级而不是白屏',
/v3\.25\.24|更新客户端/.test(empty._text), empty._text)
}
console.log('\n[harness] ' + (failed === 0 ? '全部通过' : failed + ' 项失败'))
process.exit(failed === 0 ? 0 : 1)