// Real Vue component, router, and event handlers; the host tree is in memory (not a browser/layout engine). const assert = require('node:assert/strict') const test = require('node:test') const fs = require('node:fs') const path = require('node:path') 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 { 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)} }) }}] }) new Function('require','module','exports','document',outputFiles[0].text)(require,mod,mod.exports,doc) return mod.exports } function memoryHost() { let focus 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 } 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(){} } 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]} }) return {renderer,root:new Node('root'),getFocus:()=>focus} } 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) } 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() })