fix(admin): 折叠时恢复图标栏和右侧悬浮菜单
This commit is contained in:
@@ -1,113 +1,247 @@
|
||||
// Real Vue component, router, and event handlers; the host tree is in memory (not a browser/layout engine).
|
||||
// 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 test = require('node:test')
|
||||
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 } = require('vue')
|
||||
const { createRouter, createMemoryHistory } = require('vue-router')
|
||||
const admin = process.env.ZYT_TEST_ADMIN_SOURCE || path.resolve(__dirname, '..')
|
||||
const treeDir = path.join(admin, 'src/layout/default/components/sidebar')
|
||||
async function components(doc) {
|
||||
const mod = { exports: {} }
|
||||
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 '${treeDir}/dual-sidebar.vue'
|
||||
export { default as Link } from '@/components/app-link/index.vue'`,resolveDir:admin},
|
||||
alias: {'@':path.join(admin,'src')}, bundle:true, write:false, platform:'node',format:'cjs',
|
||||
external:['vue','vue-router','@vue/shared','lodash'],define:{'import.meta.env.MODE':'"live-native"'},
|
||||
plugins:[{name:'mounted-sfc',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.onLoad({filter:/\.vue$/},async a=>{
|
||||
const s=fs.readFileSync(a.path,'utf8'), {descriptor,errors}=parse(s,{filename:a.path})
|
||||
assert.deepEqual(errors,[])
|
||||
let output=compileScript(descriptor,{id:path.basename(a.path),inlineTemplate:true}).content
|
||||
if(a.path.endsWith('app-link/index.vue'))output="import {computed} from 'vue';\n"+output
|
||||
return {contents:output,loader:'ts',resolveDir:path.dirname(a.path)}
|
||||
})
|
||||
}}]
|
||||
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) }
|
||||
})
|
||||
}
|
||||
}]
|
||||
})
|
||||
new Function('require','module','exports','document',outputFiles[0].text)(require,mod,mod.exports,doc)
|
||||
// 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 focus
|
||||
let active
|
||||
class Node {
|
||||
constructor(type,text=''){this.type=type;this.text=text;this.props={};this.children=[];this.parent=null;this.scrollTop=0;markRaw(this)}
|
||||
nodes(){return this.children.flatMap(n=>[n,...n.nodes()])}
|
||||
get childrenText(){return this.text+this.children.map(n=>n.childrenText).join('')}
|
||||
matches(s){
|
||||
s=s.trim()
|
||||
if (s.startsWith('.'))return String(this.props.class||'').split(/\s+/).includes(s.slice(1))
|
||||
if (s.startsWith('[')){const m=s.match(/^\[([\w-]+)(?:=["']?([^"'\]]+)["']?)?\]$/);return !!m && this.props[m[1]]!=null && (m[2]===undefined || String(this.props[m[1]])===m[2])}
|
||||
return this.type===s
|
||||
constructor(type, text = '') {
|
||||
Object.assign(this, { type, text, props: {}, children: [], parent: null, scrollTop: 0, style: {} })
|
||||
markRaw(this)
|
||||
}
|
||||
querySelectorAll(selector){return this.nodes().filter(n=>selector.split(',').some(s=>n.matches(s)))}
|
||||
querySelector(s){return this.querySelectorAll(s)[0]??null}
|
||||
get dataset(){return {key:this.props['data-key']}}
|
||||
getAttribute(k){return this.props[k]??null}
|
||||
getBoundingClientRect(){return {top:0,bottom:40,left:0,right:64,width:64,height:40}}
|
||||
contains(n){return n===this||this.nodes().includes(n)}
|
||||
focus(){focus=this}
|
||||
scrollIntoView(){}
|
||||
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}
|
||||
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:(e,parent,anchor)=>{detach(e);e.parent=parent;const at=parent.children.indexOf(anchor);parent.children.splice(at<0?parent.children.length:at,0,e)},
|
||||
insertStaticContent:(s,p,a)=>{const e=new Node('#static',s);e.parent=p;const i=p.children.indexOf(a);p.children.splice(i<0?p.children.length:i,0,e);return [e,e]}
|
||||
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:new Node('root'),getFocus:()=>focus}
|
||||
return { renderer, root, body, document: {
|
||||
body, addEventListener() {}, get activeElement() { return active || body },
|
||||
getElementById: id => body.nodes().find(el => el.props.id === id)
|
||||
} }
|
||||
}
|
||||
async function settle(){await nextTick();await new Promise(r=>setImmediate(r));await nextTick()}
|
||||
function click(el){
|
||||
assert.ok(el)
|
||||
const e={type:'click',currentTarget:el,target:el,button:0,preventDefault(){this.defaultPrevented=true}, defaultPrevented:false}
|
||||
for (const fn of [].concat(el.props.onClick || [])) fn(e)
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
test('compact groups browse in place and links keep their query; only explicit expansion restores a column',async()=>{
|
||||
const {renderer,root,getFocus} = memoryHost()
|
||||
const {Dual,Link} = await components({body:root,get activeElement(){return getFocus() || root}})
|
||||
const page=(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','报表',[page('one','报表一'),page('two','报表二','?source=menu')]),page('summary','汇总')]),page('/solo','首页'),group('/links','帮助',[page('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})
|
||||
const router=createRouter({history:createMemoryHistory(),routes:['/solo','/stats/reports/one','/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)
|
||||
app.component('app-link',Link);app.component('icon',{render:()=>h('svg')});app.component('image-contain',{render:()=>h('img')});app.use(router)
|
||||
app.mount(root)
|
||||
const controls=()=>root.nodes().filter(n=>n.type==='button'||n.type==='a')
|
||||
const named=(name)=>controls().find(n=>n.props['aria-label']===name || n.props.title===name || n.childrenText.trim()===name)
|
||||
const fixedPane=()=>root.nodes().some(n=>n.type==='nav'&&n.props['aria-label']==='二级菜单')
|
||||
appStore.toggleCollapsed(true);await settle()
|
||||
click(named('数据统计'));await settle()
|
||||
assert.deepEqual({collapsed:appStore.isCollapsed,path:router.currentRoute.value.fullPath,pane:fixedPane()},
|
||||
{collapsed:true,path:'/solo',pane:false},'a compact directory should neither expand nor navigate')
|
||||
assert.equal(getFocus(),named('报表'),'focus enters the first child')
|
||||
click(named('报表'));await settle();assert.ok(named('报表一'));assert.ok(named('报表二'))
|
||||
click(named('报表二'));await settle()
|
||||
assert.equal(router.currentRoute.value.fullPath,'/stats/reports/two?source=menu')
|
||||
assert.ok(named('报表一'),'sibling remains reachable');assert.equal(appStore.isCollapsed,true)
|
||||
click(named('返回上一级'));await settle();assert.equal(getFocus(),named('报表'),'back restores focus to the directory');assert.ok(named('汇总'));assert.ok(named('报表'));assert.equal(fixedPane(),false)
|
||||
click(named('返回上一级'));await settle();assert.ok(named('首页'));assert.ok(named('数据统计'))
|
||||
assert.equal(router.currentRoute.value.fullPath,'/stats/reports/two?source=menu','back is menu-only')
|
||||
click(named('帮助'));await settle()
|
||||
assert.equal(router.currentRoute.value.fullPath,'/stats/reports/two?source=menu')
|
||||
assert.equal(named('使用说明').props.href,'https://example.invalid/help')
|
||||
// Change the permission-projected tree in place; no orphaned group or link survives.
|
||||
routes.pop();await settle();assert.ok(!named('使用说明'));assert.ok(!named('返回上一级'))
|
||||
click(named('首页'));await settle();assert.equal(router.currentRoute.value.path,'/solo')
|
||||
assert.equal(appStore.isCollapsed,true)
|
||||
click(named('数据统计'));await settle();click(named('报表'));await settle()
|
||||
await router.push('/stats/summary');await settle();assert.ok(named('汇总'));assert.ok(!named('报表二'))
|
||||
assert.equal(appStore.isCollapsed,true)
|
||||
appStore.toggleCollapsed(false);await settle();assert.equal(fixedPane(),true)
|
||||
app.unmount()
|
||||
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')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user