106 lines
2.7 KiB
JavaScript
106 lines
2.7 KiB
JavaScript
// 测试 nav.uts 的 findActiveByCurrentPage 函数
|
||
// 模拟 menu.uts 中 maintain 菜单的结构
|
||
|
||
const maintainMenu = {
|
||
id: "maintain",
|
||
title: "维护",
|
||
groups: [
|
||
{
|
||
id: "dev-config",
|
||
title: "开发配置",
|
||
children: [
|
||
{
|
||
id: "dev-config-category",
|
||
title: "分类配置",
|
||
path: "/pages/mall/admin/maintain/dev-config/category",
|
||
},
|
||
],
|
||
},
|
||
{
|
||
id: "system-info",
|
||
title: "系统信息",
|
||
path: "/pages/mall/admin/maintain/system-info",
|
||
children: [],
|
||
},
|
||
],
|
||
};
|
||
|
||
function normalize(p) {
|
||
if (!p) return "";
|
||
const s = p.startsWith("/") ? p.slice(1) : p;
|
||
const q = s.indexOf("?");
|
||
return q >= 0 ? s.slice(0, q) : s;
|
||
}
|
||
|
||
function findActiveByCurrentPage(menuList, currentPage) {
|
||
const page = currentPage || "";
|
||
|
||
// 1) currentPage 直接是一级 menu id
|
||
const mById = menuList.find((m) => m.id === page);
|
||
if (mById) {
|
||
return { activeMenuId: mById.id, activeSubId: "", note: "命中一级菜单" };
|
||
}
|
||
|
||
// 2) currentPage 是 path(/pages/xxx 或 pages/xxx)
|
||
const pageNorm = normalize(page);
|
||
|
||
for (const m of menuList) {
|
||
const groups = m.groups || [];
|
||
|
||
// group / child / 四级 全部扫描
|
||
for (const g of groups) {
|
||
// group 叶子(可选)- 检查 id
|
||
if (g.id === page) {
|
||
return { activeMenuId: m.id, activeSubId: g.id, note: "命中 group.id" };
|
||
}
|
||
// group 叶子(可选)- 检查 path
|
||
if (g.path && normalize(g.path) === pageNorm) {
|
||
return {
|
||
activeMenuId: m.id,
|
||
activeSubId: g.id,
|
||
note: "命中 group.path",
|
||
};
|
||
}
|
||
|
||
const cs = g.children || [];
|
||
for (const c of cs) {
|
||
// 用 id 命中
|
||
if (c.id === page)
|
||
return {
|
||
activeMenuId: m.id,
|
||
activeSubId: c.id,
|
||
note: "命中 child.id",
|
||
};
|
||
// 用 path 命中
|
||
if (c.path && normalize(c.path) === pageNorm)
|
||
return {
|
||
activeMenuId: m.id,
|
||
activeSubId: c.id,
|
||
note: "命中 child.path",
|
||
};
|
||
}
|
||
}
|
||
}
|
||
|
||
// 3) 找不到:兜底 home
|
||
return { activeMenuId: "home", activeSubId: "", note: "未命中,兜底到 home" };
|
||
}
|
||
|
||
// 测试用例
|
||
const testCases = [
|
||
"system-info",
|
||
"/pages/mall/admin/maintain/system-info",
|
||
"pages/mall/admin/maintain/system-info",
|
||
"dev-config-category",
|
||
];
|
||
|
||
console.log("=== 测试 findActiveByCurrentPage ===\n");
|
||
testCases.forEach((testCase) => {
|
||
const result = findActiveByCurrentPage([maintainMenu], testCase);
|
||
console.log(`输入: "${testCase}"`);
|
||
console.log(
|
||
`结果: activeMenuId="${result.activeMenuId}", activeSubId="${result.activeSubId}"`,
|
||
);
|
||
console.log(`说明: ${result.note}\n`);
|
||
});
|