Files
image-workbench-desktop/tests/ui-lib-sidebar-test.js
T

238 lines
11 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.
'use strict'
// src/ui-lib-sidebar.js 的行为测试(此前该组件无测试,P2-9 抽取后仅被少量源码文本断言覆盖)。
//
// 用 vm + 极简 React/ReactDOM 假体驱动组件:右键提示词卡片 → groupMenu 置位 → 重渲染 →
// ReactDOM.createPortal 渲染「移动到分组」菜单 → 点「未分组」→ onPromptsChange/onFlash 被调用。
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const vm = require('vm')
const root = path.resolve(__dirname, '..')
const loadComp = () => {
const states = []
const refs = []
let cursor = 0
let rerender = null
const useHook = (init) => {
const i = cursor++
if (!(i in states)) states[i] = (typeof init === 'function') ? init() : init
return [states[i], (v) => { states[i] = (typeof v === 'function') ? v(states[i]) : v; if (rerender) rerender() }]
}
const fakeReact = {
createElement: (type, props, ...children) => ({ __el: true, type, props: props || {}, children: children.flat() }),
useState: useHook,
useEffect: () => {},
useLayoutEffect: () => {},
useMemo: (fn) => fn(),
useRef: (init) => { const i = cursor++; if (!(i in refs)) refs[i] = { current: init === undefined ? null : init }; return refs[i] },
}
const portals = []
const fakeReactDOM = { createPortal: (child, container) => { portals.push({ child, container }); return { __el: true, type: '__portal__', props: {}, children: [child] } } }
const store = {}
const sandbox = {
React: fakeReact,
ReactDOM: fakeReactDOM,
document: { body: { __body: true }, addEventListener: () => {}, removeEventListener: () => {} },
innerWidth: 1600,
innerHeight: 900,
navigator: { clipboard: { writeText: () => Promise.resolve() } },
localStorage: {
getItem: (k) => (k in store ? store[k] : null),
setItem: (k, v) => { store[k] = String(v) },
removeItem: (k) => { delete store[k] },
},
confirm: () => true,
console,
}
sandbox.window = sandbox // 组件用 bare window.innerWidth / window.addEventListener
vm.runInNewContext(fs.readFileSync(path.join(root, 'src', 'ui-lib-sidebar.js'), 'utf8'), sandbox)
const Comp = sandbox.IWBUILibSidebar
let tree = null
const render = (props) => { cursor = 0; render.props = props; tree = Comp(props) }
rerender = () => render(render.props)
return { render: (props) => render(props), portals, getTree: () => tree, store, sandbox }
}
const walk = (node, fn) => {
if (!node || typeof node !== 'object') return
if (Array.isArray(node)) { node.forEach((n) => walk(n, fn)); return }
if (node.__el) { fn(node); (node.children || []).forEach((c) => walk(c, fn)) }
}
const saved = []
const flashed = []
const app = loadComp()
app.render({
I: () => null,
api: () => Promise.resolve(),
uid: (p) => String(p) + '-x',
useTextDialog: () => ({ open: () => {} }),
TextDialog: () => null,
promptGroupsOf: (prompts, groups) => groups || [],
PluginHost: { list: () => [], on: () => () => {} },
wPluginPanels: [],
prompts: [{ id: 'p1', name: 'P1', text: 'hello', group: '' }],
groups: [{ id: 'g1', name: '分组1' }],
onPromptsChange: (list) => saved.push(list),
onGroupsChange: () => {},
onFlash: (m) => flashed.push(m),
onInsertPrompt: () => {},
resTab: 'prompts',
resOpen: false,
})
assert.ok(app.getTree(), '组件应返回元素树')
assert.strictEqual(app.portals.length, 0, '未右键时不应渲染「移动到分组」菜单')
// 右键提示词卡片 → 打开分组菜单(portal)
let card = null
walk(app.getTree(), (n) => { if (!card && n.props.onContextMenu && typeof n.props.className === 'string' && n.props.className.indexOf('iwb-pcard') === 0) card = n })
assert.ok(card, '应能定位到提示词卡片')
card.props.onContextMenu({ preventDefault() {}, stopPropagation() {}, clientX: 30, clientY: 40 })
assert.strictEqual(app.portals.length, 1, '右键后应经 ReactDOM.createPortal 渲染菜单')
assert.ok(app.portals[0].container && app.portals[0].container.__body === true, 'portal 容器应为 document.body')
// 菜单里点「未分组」→ 与分组解绑并回调(只在 portal 子树里找,避免撞上分类芯片)
let menuBtn = null
walk(app.portals[0].child, (n) => { if (!menuBtn && n.type === 'button' && n.children[0] === '未分组') menuBtn = n })
assert.ok(menuBtn, '菜单应含「未分组」按钮')
menuBtn.props.onClick()
assert.strictEqual(saved.length, 1, 'assignPromptGroup 应触发 onPromptsChange')
assert.strictEqual(saved[0][0].group, '', '应把该提示词移到未分组')
assert.strictEqual(flashed.join(','), '已移动到未分组')
// M1 回归:删除分组后,分组缓存(iwb_lib_groups_cache)必须是「新分组」,不得被 saveList 的
// 陈旧闭包用旧分组覆盖回去(否则刷新后分组回退、提示词与分组不一致)。
app.render({
I: () => null,
api: () => Promise.resolve(),
uid: (p) => String(p) + '-x',
useTextDialog: () => ({ open: () => {} }),
TextDialog: () => null,
promptGroupsOf: (prompts, groups) => groups || [],
PluginHost: { list: () => [], on: () => () => {} },
wPluginPanels: [],
prompts: [{ id: 'p1', name: 'P1', text: 'hello', group: '分组1' }],
groups: [{ id: 'g1', name: '分组1' }],
onPromptsChange: () => {},
onGroupsChange: () => {},
onFlash: () => {},
onInsertPrompt: () => {},
resTab: 'prompts',
resOpen: false,
})
let mgmt = null
walk(app.getTree(), (n) => { if (!mgmt && n.type === 'button' && typeof n.props.title === 'string' && n.props.title.indexOf('管理分组') >= 0) mgmt = n })
assert.ok(mgmt, '应能找到「管理分组」按钮')
mgmt.props.onClick()
let delBtn = null
for (const p of app.portals) walk(p.child, (n) => { if (!delBtn && n.type === 'button' && n.children[0] === '删除') delBtn = n })
assert.ok(delBtn, '管理分组弹窗应含「删除」按钮')
delBtn.props.onClick()
const cached = JSON.parse(app.store['iwb_lib_groups_cache'] || '[]')
assert.ok(!cached.some((g) => g && g.name === '分组1'), '删除分组后缓存不得仍含旧分组(saveList 不得用旧闭包覆盖)')
// ── 失败必须可见(2026-11-12):api() 失败是 resolve({ok:false}),不是 reject ──────────
// 背景:`api('prompts', …)` 在配额不足时 **resolve** { ok:false, error:'提示词库保存失败:…' },
// 历史上组件里写 `.catch(() => {})` ⇒ 这句话连同错误一起被丢掉,用户以为存好了,刷新后数据消失。
// 这里把「组件 → onFlash(文案, 'err')」钉住;app.js 侧再把 'err' 渲染成红色 toast/状态栏。
const baseProps = (over) => Object.assign({
I: () => null,
api: () => Promise.resolve(),
uid: (p) => String(p) + '-x',
useTextDialog: () => ({ open: () => {} }),
TextDialog: () => null,
promptGroupsOf: (prompts, groups) => groups || [],
PluginHost: { list: () => [], on: () => () => {} },
wPluginPanels: [],
prompts: [{ id: 'p1', name: 'P1', text: 'hello', group: '分组1' }],
groups: [{ id: 'g1', name: '分组1' }],
onPromptsChange: () => {},
onGroupsChange: () => {},
onFlash: () => {},
onInsertPrompt: () => {},
resTab: 'prompts',
resOpen: false,
}, over || {})
const tick = () => new Promise((r) => setTimeout(r, 0))
;(async () => {
// ① 保存失败(resolve {ok:false})→ onFlash 收到 'err'
{
const flashes = []
const a = loadComp()
a.render(baseProps({
api: () => Promise.resolve({ ok: false, error: '提示词库保存失败:浏览器本地存储空间不足。' }),
onFlash: (m, ty) => flashes.push([m, ty]),
}))
let card = null
walk(a.getTree(), (n) => { if (!card && n.props.onContextMenu && typeof n.props.className === 'string' && n.props.className.indexOf('iwb-pcard') === 0) card = n })
card.props.onContextMenu({ preventDefault() {}, stopPropagation() {}, clientX: 10, clientY: 10 })
let btn = null
for (const p of a.portals) walk(p.child, (n) => { if (!btn && n.type === 'button' && n.children[0] === '未分组') btn = n })
btn.props.onClick()
await tick()
assert.ok(flashes.some((f) => f[1] === 'err' && /保存失败/.test(f[0])),
'保存失败必须给出可见的 err 级提示(实际:' + JSON.stringify(flashes) + ')')
}
// ② 保存抛错(真 reject)→ 同样给 err 提示,且文案是通用兜底
{
const flashes = []
const a = loadComp()
a.render(baseProps({ api: () => Promise.reject(new Error('boom')), onFlash: (m, ty) => flashes.push([m, ty]) }))
let card = null
walk(a.getTree(), (n) => { if (!card && n.props.onContextMenu && typeof n.props.className === 'string' && n.props.className.indexOf('iwb-pcard') === 0) card = n })
card.props.onContextMenu({ preventDefault() {}, stopPropagation() {}, clientX: 10, clientY: 10 })
let btn = null
for (const p of a.portals) walk(p.child, (n) => { if (!btn && n.type === 'button' && n.children[0] === '未分组') btn = n })
btn.props.onClick()
await tick()
assert.ok(flashes.some((f) => f[1] === 'err' && /保存失败/.test(f[0])),
'reject 也要给 err 提示(实际:' + JSON.stringify(flashes) + ')')
}
// ③ 「复制全文」被浏览器拒绝 → err 提示(此前是 .catch(() => {}) 完全静默)
{
const flashes = []
const a = loadComp()
a.sandbox.navigator.clipboard.writeText = () => Promise.reject(new Error('NotAllowedError'))
a.render(baseProps({ onFlash: (m, ty) => flashes.push([m, ty]) }))
// 「复制全文」只在卡片展开后出现:先点正文展开(iwb-ptext 的 onClick 就是展开/收起)
let textEl = null
walk(a.getTree(), (n) => { if (!textEl && typeof n.props.className === 'string' && n.props.className.indexOf('iwb-ptext') === 0 && n.props.onClick) textEl = n })
assert.ok(textEl, '应能点到提示词正文以展开卡片')
textEl.props.onClick({ stopPropagation() {} })
let copyBtn = null
walk(a.getTree(), (n) => { if (!copyBtn && n.type === 'button' && n.props.title === '复制全文') copyBtn = n })
assert.ok(copyBtn, '展开后应能找到「复制全文」按钮')
copyBtn.props.onClick({ stopPropagation() {} })
await tick()
assert.ok(flashes.some((f) => f[1] === 'err' && /复制失败/.test(f[0])),
'剪贴板被拒必须给 err 提示(实际:' + JSON.stringify(flashes) + ')')
}
// ④ 剪贴板不存在(旧浏览器 / 非安全上下文)→ 也要 err 提示,不能抛
{
const flashes = []
const a = loadComp()
a.sandbox.navigator.clipboard = undefined
a.render(baseProps({ onFlash: (m, ty) => flashes.push([m, ty]) }))
let textEl4 = null
walk(a.getTree(), (n) => { if (!textEl4 && typeof n.props.className === 'string' && n.props.className.indexOf('iwb-ptext') === 0 && n.props.onClick) textEl4 = n })
textEl4.props.onClick({ stopPropagation() {} })
let copyBtn = null
walk(a.getTree(), (n) => { if (!copyBtn && n.type === 'button' && n.props.title === '复制全文') copyBtn = n })
copyBtn.props.onClick({ stopPropagation() {} })
await tick()
assert.ok(flashes.some((f) => f[1] === 'err' && /复制失败/.test(f[0])),
'无剪贴板 API 时也要给 err 提示(实际:' + JSON.stringify(flashes) + ')')
}
console.log('ui-lib-sidebar checks passed')
})().catch((e) => { console.error('❌ ' + ((e && e.stack) || e)); process.exit(1) })