248 lines
13 KiB
JavaScript
248 lines
13 KiB
JavaScript
// Run with node --test. ZYT_TEST_ADMIN_SOURCE can point at an untouched admin source tree.
|
|
// The menu, submenus, menu items, Vue timers and vue-router are real. Only the tooltip
|
|
// painting/positioning layer is replaced; there is no browser, CSS layout or Popper here.
|
|
const assert = require('node:assert/strict')
|
|
const fs = require('node:fs')
|
|
const path = require('node:path')
|
|
const test = require('node:test')
|
|
const { build } = require('esbuild')
|
|
const { parse, compileScript } = require('@vue/compiler-sfc')
|
|
const { createRenderer, reactive, h, nextTick, markRaw, computed, ref, watch, onMounted } = require('vue')
|
|
const { createRouter, createMemoryHistory, useRoute, useRouter } = require('vue-router')
|
|
|
|
const admin = path.resolve(process.env.ZYT_TEST_ADMIN_SOURCE || path.join(__dirname, '..'))
|
|
const menuPackage = path.join(path.dirname(require.resolve('element-plus/package.json')), 'es/components/menu/index.mjs')
|
|
|
|
async function components(document) {
|
|
const { outputFiles } = await build({
|
|
absWorkingDir: admin,
|
|
stdin: {
|
|
contents: `export { default as Dual } from '@/layout/default/components/sidebar/dual-sidebar.vue'
|
|
export { default as Link } from '@/components/app-link/index.vue'
|
|
export { ElMenu, ElSubMenu, ElMenuItem } from ${JSON.stringify(menuPackage)}`,
|
|
resolveDir: admin
|
|
},
|
|
alias: { '@': path.join(admin, 'src') },
|
|
bundle: true, write: false, platform: 'node', format: 'cjs',
|
|
external: ['vue', 'vue-router', '@vue/shared', '@element-plus/icons-vue', 'lodash'],
|
|
define: { 'import.meta.env.MODE': '"live-native"' },
|
|
plugins: [{
|
|
name: 'mounted-sidebar',
|
|
setup(b) {
|
|
b.onResolve({ filter: /^@\/stores\/modules\/(app|setting)$/ }, a => ({
|
|
path: a.path.split('/').pop(), namespace: 'store'
|
|
}))
|
|
b.onLoad({ filter: /.*/, namespace: 'store' }, a => ({
|
|
contents: `import { inject } from 'vue'; export default () => inject('test-${a.path}')`
|
|
}))
|
|
b.onResolve({ filter: /\/tooltip\/index\.mjs$/ }, a => ({ path: a.path, namespace: 'paint' }))
|
|
b.onLoad({ filter: /.*/, namespace: 'paint' }, () => ({
|
|
// Visibility, teleport and placement come from the real ElSubMenu.
|
|
contents: `import { h, Fragment, Teleport } from 'vue'
|
|
export const ElTooltip = {
|
|
inheritAttrs: false, props: ['visible', 'teleported', 'placement', 'persistent'],
|
|
setup(props, {slots}) { return () => h(Fragment, [
|
|
slots.default?.(),
|
|
props.visible || props.persistent ? h(Teleport, {to: 'body', disabled: !props.teleported}, [
|
|
h('section', {hidden: !props.visible, 'data-placement': props.placement}, slots.content?.())
|
|
]) : null
|
|
]) }
|
|
}`
|
|
}))
|
|
b.onLoad({ filter: /\.vue$/ }, a => {
|
|
const { descriptor, errors } = parse(fs.readFileSync(a.path, 'utf8'), { filename: a.path })
|
|
assert.deepEqual(errors, [])
|
|
const { content } = compileScript(descriptor, { id: path.basename(a.path), inlineTemplate: true })
|
|
return { contents: content, loader: 'ts', resolveDir: path.dirname(a.path) }
|
|
})
|
|
}
|
|
}]
|
|
})
|
|
// Make the same auto-imports as Vite available and allow VueUse to start its real
|
|
// hover timers. All document/window references are local to this bundle.
|
|
const bindings = { document, window: { document }, MouseEvent: Event, computed, ref, watch, onMounted, nextTick, useRoute, useRouter }
|
|
const mod = { exports: {} }
|
|
new Function('require', 'module', 'exports', ...Object.keys(bindings), outputFiles[0].text)(
|
|
require, mod, mod.exports, ...Object.values(bindings)
|
|
)
|
|
return mod.exports
|
|
}
|
|
|
|
function memoryHost() {
|
|
let active
|
|
class Node {
|
|
constructor(type, text = '') {
|
|
Object.assign(this, { type, text, props: {}, children: [], parent: null, scrollTop: 0, style: {} })
|
|
markRaw(this)
|
|
}
|
|
nodes() { return this.children.flatMap(n => [n, ...n.nodes()]) }
|
|
get visible() { return !this.props.hidden && (!this.parent || this.parent.visible) }
|
|
hasClass(name) { return String(this.props.class || '').split(/\s+/).includes(name) }
|
|
querySelector(s) { return this.nodes().find(n => n.hasClass(s.slice(1))) }
|
|
getBoundingClientRect() { return { top: 0, bottom: 40 } }
|
|
getAttribute(key) {
|
|
const value = this.props[key] ?? this.props[key.replace(/-([a-z])/g, (_, c) => c.toUpperCase())]
|
|
return value == null ? null : String(value)
|
|
}
|
|
focus() { active = this }
|
|
click() { fire(this, 'click') }
|
|
dispatchEvent(e) { fire(this, e.type) }
|
|
}
|
|
function detach(el) {
|
|
if (el.parent) el.parent.children.splice(el.parent.children.indexOf(el), 1)
|
|
el.parent = null
|
|
}
|
|
function insert(el, parent, anchor) {
|
|
detach(el)
|
|
el.parent = parent
|
|
const at = parent.children.indexOf(anchor)
|
|
parent.children.splice(at < 0 ? parent.children.length : at, 0, el)
|
|
}
|
|
const body = new Node('body')
|
|
const root = new Node('app')
|
|
insert(root, body)
|
|
const renderer = createRenderer({
|
|
createElement: t => new Node(t), createText: t => new Node('#text', t), createComment: t => new Node('#comment', t),
|
|
parentNode: e => e.parent, nextSibling: e => e.parent?.children[e.parent.children.indexOf(e) + 1] ?? null,
|
|
setText: (e, t) => { e.text = t }, setElementText: (e, t) => { e.children = []; e.text = t },
|
|
patchProp: (e, k, old, v) => { e.props[k] = v }, setScopeId() {},
|
|
remove: detach, insert, querySelector: s => s === 'body' ? body : null,
|
|
insertStaticContent: (s, p, a) => { const el = new Node('#static', s); insert(el, p, a); return [el, el] }
|
|
})
|
|
return { renderer, root, body, document: {
|
|
body, addEventListener() {}, get activeElement() { return active || body },
|
|
getElementById: id => body.nodes().find(el => el.props.id === id)
|
|
} }
|
|
}
|
|
|
|
// Click bubbles through the real link + menu item regardless of their nesting order;
|
|
// mouseenter/leave do not bubble. No helper toggles popup state or calls router.push.
|
|
function fire(target, type, key) {
|
|
assert.ok(target, 'event target: ' + type)
|
|
const e = { type, target, key, button: 0, defaultPrevented: false, preventDefault() { this.defaultPrevented = true },
|
|
stopPropagation() { this.stopped = true } }
|
|
const prop = 'on' + type[0].toUpperCase() + type.slice(1)
|
|
for (let el = target; el; el = el.parent) {
|
|
e.currentTarget = el
|
|
for (const fn of [].concat(el.props[prop] || [])) fn(e)
|
|
if (!['click', 'keydown'].includes(type) || e.stopped) break
|
|
}
|
|
}
|
|
async function settle() {
|
|
await nextTick(); await new Promise(resolve => setImmediate(resolve)); await nextTick()
|
|
}
|
|
async function until(check, message) {
|
|
const end = Date.now() + 3000
|
|
while (!check() && Date.now() < end) await new Promise(r => setTimeout(r, 20))
|
|
assert.ok(check(), message)
|
|
}
|
|
|
|
test('collapsed directories fly out on hover without drilling or navigation; leaves retain authorized targets', async t => {
|
|
const { renderer, root, body, document } = memoryHost()
|
|
const { Dual, Link, ElMenu, ElSubMenu, ElMenuItem } = await components(document)
|
|
const leaf = (path, title, query) => ({ path, meta: { title, type: 'C', query } })
|
|
const group = (path, title, children) => ({ path, meta: { title, type: 'M' }, children })
|
|
const routes = reactive([
|
|
group('/stats', '数据统计', [
|
|
group('reports', '报表', [
|
|
leaf('two', '报表二', '?source=menu'),
|
|
{ path: 'hidden', meta: { title: '不可见', type: 'C', hidden: true } },
|
|
{ path: 'edit', meta: { title: '按钮权限', type: 'A' } }
|
|
]),
|
|
leaf('summary', '汇总'),
|
|
group('empty', '无可见页面', [])
|
|
]),
|
|
leaf('/solo', '首页'),
|
|
group('/help', '帮助', [leaf('https://example.invalid/help', '使用说明')])
|
|
])
|
|
const appStore = reactive({ isCollapsed: false, config: {}, toggleCollapsed(v) { this.isCollapsed = v ?? !this.isCollapsed } })
|
|
const settings = reactive({ showLogo: false, sideWidth: 230, isUniqueOpened: true, sideTheme: 'light' })
|
|
const router = createRouter({
|
|
history: createMemoryHistory(),
|
|
routes: ['/solo', '/stats/reports/two', '/stats/summary'].map(path => ({ path, component: { render: () => null } }))
|
|
})
|
|
await router.push('/solo'); await router.isReady()
|
|
const app = renderer.createApp({ render: () => h(Dual, { routes }) })
|
|
app.provide('test-app', appStore); app.provide('test-setting', settings)
|
|
Object.entries({ ElMenu, ElSubMenu, ElMenuItem, AppLink: Link, Icon: { render: () => h('svg') },
|
|
ImageContain: { render: () => h('img') },
|
|
ElScrollbar: { render() { return h('div', this.$slots.default?.()) } }
|
|
}).forEach(([name, component]) => app.component(name, component))
|
|
app.use(router); app.mount(root)
|
|
t.after(() => app.unmount())
|
|
const named = (node, name) => node.props['aria-label'] === name || node.props.title === name
|
|
const find = predicate => body.nodes().find(n => n.visible && predicate(n))
|
|
const submenu = name => find(n => n.hasClass('el-sub-menu') && named(n, name))
|
|
const href = value => find(n => n.type === 'a' && n.props.href === value)
|
|
const column = () => find(n => n.type === 'nav' && named(n, '二级菜单'))
|
|
const unchanged = (path = '/solo') => {
|
|
assert.equal(router.currentRoute.value.fullPath, path)
|
|
assert.equal(appStore.isCollapsed, true)
|
|
assert.equal(column(), undefined, 'no fixed secondary column while folded')
|
|
}
|
|
const hover = async name => {
|
|
const el = submenu(name)
|
|
assert.ok(el, 'missing hoverable collapsed directory: ' + name)
|
|
fire(el, 'mouseenter')
|
|
await until(() => el.hasClass('is-opened'), name + ' should open on hover alone')
|
|
return el
|
|
}
|
|
|
|
appStore.toggleCollapsed(true); await settle()
|
|
const menu = root.querySelector('.el-menu--collapse')
|
|
assert.ok(menu, 'the folded rail must use a collapsed hover menu, not the old click-through list')
|
|
assert.ok(href('/solo')); assert.ok(!href('/stats/summary'))
|
|
const target = '/stats/reports/two?source=menu'
|
|
const keydown = async (el, key) => { fire(el, 'keydown', key); await settle() }
|
|
const directory = submenu('数据统计')
|
|
assert.equal(directory?.getAttribute('tabindex'), '0', 'directory can receive keyboard focus')
|
|
directory.focus()
|
|
await keydown(directory, 'Enter')
|
|
assert.equal(document.activeElement, submenu('报表'), 'Enter focuses the first child in its popup')
|
|
await keydown(document.activeElement, 'ArrowRight')
|
|
assert.equal(document.activeElement, href(target), 'Right opens the nested popup')
|
|
await keydown(document.activeElement, 'Escape')
|
|
assert.equal(document.activeElement, submenu('报表')); assert.ok(!href(target))
|
|
await keydown(document.activeElement, 'ArrowLeft')
|
|
assert.equal(document.activeElement, directory); assert.ok(!href('/stats/summary'))
|
|
unchanged()
|
|
const top = await hover('数据统计')
|
|
unchanged()
|
|
assert.ok(href('/solo'), 'hover leaves the first-level entries in place')
|
|
assert.ok(href('/stats/summary'), 'hover exposes a direct leaf without a click')
|
|
assert.equal(root.querySelector('.el-menu--popup'), undefined, 'first popup is outside the rail')
|
|
assert.ok(find(n => n.props['data-placement'] === 'right-start'), 'submenu requests a right-side popup')
|
|
fire(top.querySelector('.el-sub-menu__title'), 'click'); await settle(); unchanged()
|
|
assert.ok(!submenu('无可见页面'))
|
|
|
|
// Crossing from the rail into the floating panel must keep that panel open.
|
|
fire(top, 'mouseleave')
|
|
fire(find(n => n.hasClass('el-menu--popup-container')), 'mouseenter')
|
|
const nested = await hover('报表')
|
|
assert.ok(href(target)); assert.ok(!href('/stats/reports/hidden')); assert.ok(!href('/stats/reports/edit'))
|
|
unchanged()
|
|
fire(nested.querySelector('.el-sub-menu__title'), 'click'); await settle(); unchanged()
|
|
const link = href(target)
|
|
fire(link.querySelector('.el-menu-item') || link, 'click')
|
|
await settle(); unchanged(target)
|
|
assert.ok(!href(target), 'selecting a leaf dismisses the popup')
|
|
assert.ok(top.hasClass('is-active'), 'the selected route highlights its module')
|
|
|
|
const help = await hover('帮助')
|
|
const external = 'https://example.invalid/help'
|
|
assert.equal(href(external)?.props.target, '_blank')
|
|
assert.match(href(external).props.rel, /noopener/)
|
|
unchanged(target)
|
|
fire(help, 'mouseleave')
|
|
await until(() => !href(external), 'leaving the directory closes the flyout')
|
|
await hover('帮助')
|
|
routes.pop(); await settle()
|
|
assert.ok(!submenu('帮助')); assert.ok(!href(external), 'revoking permissions removes an already-open external link')
|
|
unchanged(target)
|
|
|
|
appStore.toggleCollapsed(false); await settle()
|
|
assert.ok(!root.querySelector('.el-menu--collapse'))
|
|
assert.ok(column(), 'explicit expansion restores the secondary column')
|
|
assert.equal(href(target)?.props['aria-current'], 'page')
|
|
})
|