/** 侧栏菜单路径匹配:最长前缀 + 全局叶子消歧 */ export function normalizePathname(pathname: string): string { if (pathname.length > 1 && pathname.endsWith('/')) { return pathname.slice(0, -1); } return pathname; } export function collectMenuLeafPaths(items: Array<{ path: string; children?: Array<{ path: string }> }>): string[] { const paths: string[] = []; for (const item of items) { if (item.children?.length) { for (const child of item.children) { paths.push(child.path); } } else { paths.push(item.path); } } return paths; } /** * 判断 pathname 是否匹配某菜单路径。 * 短路径前缀匹配时,若全局存在更长的菜单路径也匹配当前页,则不算匹配 * (避免 /orders 误匹配 /orders/bids,尤其当二者分属不同菜单组时)。 */ export function isMenuPathMatch(pathname: string, menuPath: string, allLeafPaths: string[]): boolean { const normalized = normalizePathname(pathname); if (normalized === menuPath) return true; if (!normalized.startsWith(`${menuPath}/`)) return false; return !allLeafPaths.some( (p) => p !== menuPath && p.length > menuPath.length && (normalized === p || normalized.startsWith(`${p}/`)) ); } /** 按最长路径前缀匹配当前子菜单(结合全局叶子路径消歧) */ export function findActiveMenuChild( pathname: string, children: T[], allLeafPaths: string[] ): T | undefined { const normalized = normalizePathname(pathname); let best: T | undefined; for (const child of children) { if (!isMenuPathMatch(normalized, child.path, allLeafPaths)) continue; if (!best || child.path.length > best.path.length) best = child; } return best; } export function isStandaloneMenuActive(pathname: string, itemPath: string): boolean { const normalized = normalizePathname(pathname); return normalized === itemPath || normalized.startsWith(`${itemPath}/`); } export function isActiveInMenuGroup( pathname: string, children: T[], allLeafPaths: string[] ): boolean { return Boolean(findActiveMenuChild(pathname, children, allLeafPaths)); } export function isMenuChildActive( pathname: string, childPath: string, siblings: T[], allLeafPaths: string[] ): boolean { return findActiveMenuChild(pathname, siblings, allLeafPaths)?.path === childPath; } /** 当前分组是否应完全展开(有激活子项且未手动折叠,或用户已点开) */ export function shouldExpandMenuGroup(input: { hasActiveChild: boolean; userCollapsed: boolean; userExpanded: boolean; }): boolean { if (input.userCollapsed) return false; return input.hasActiveChild || input.userExpanded; }