BasicLayout.vue 16.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
<script setup lang="ts">
// 类型导入
import type { BreadcrumbItem, MenuItem } from "@/types/menu";

import { computed, ref, watch } from "vue";
// Vue 核心
import { useRoute, useRouter } from "vue-router";

// 项目配置和工具
import { defaultTopMenus, getMenuChain, getMenuParentPaths } from "@/config/menus";
import { microApps } from "@/qiankun/apps";
import { communicationManager } from "@/qiankun/communication";
import { useMenuStore } from "@/stores";

import Breadcrumb from "./components/Breadcrumb.vue";
// 组件导入
import SidebarMenuItem from "./components/SidebarMenuItem.vue";
import UserInfo from "./components/UserInfo.vue";

const router = useRouter();
const route = useRoute();
const menuStore = useMenuStore();

// 应用名称(从环境变量读取)
const appName = "超级孪生智能体";

// 展开的菜单项 keys
const expandedKeys = ref<Set<string>>(new Set());

// 当前激活的顶级菜单 ID
const activeTopMenuId = ref<string>("");

// 侧边栏折叠状态(从本地存储恢复)
const COLLAPSE_STORAGE_KEY = "basicLayout:isCollapsed";
const storedCollapse = (() => {
	try {
		return localStorage.getItem(COLLAPSE_STORAGE_KEY);
	} catch {
		return null;
	}
})();
const isCollapsed = ref<boolean>(storedCollapse === "true");

// 切换折叠状态
const toggleCollapse = () => {
	isCollapsed.value = !isCollapsed.value;
};

// 缓存折叠状态,避免刷新后丢失
watch(
	isCollapsed,
	(val) => {
		try {
			localStorage.setItem(COLLAPSE_STORAGE_KEY, String(val));
		} catch {
			// ignore storage errors
		}
	},
	{ immediate: true },
);

// 获取顶部菜单(优先使用动态菜单,如果没有则使用默认菜单)
const topMenus = computed(() => {
	return menuStore.isMenusLoaded && menuStore.topMenus.length > 0
		? menuStore.topMenus
		: defaultTopMenus;
});

// 获取所有菜单(用于面包屑和路由查找)
const allMenus = computed(() => {
	// 优先使用 store 中的菜单,如果没有则使用默认菜单
	if (menuStore.isMenusLoaded && menuStore.topMenus.length > 0) {
		return menuStore.getAllMenus();
	}
	const menus: MenuItem[] = [];
	defaultTopMenus.forEach((topMenu) => {
		if (topMenu.sidebarMenus) {
			menus.push(...topMenu.sidebarMenus);
		}
	});
  
	return menus;
});

// 根据当前路由判断激活的顶级菜单
const getActiveTopMenuId = (path: string): string => {
	for (const topMenu of topMenus.value) {
		if (path.startsWith(topMenu.path)) {
			return topMenu.id;
		}
	}
	return "";
};

/**
 * 根据路由参数动态生成面包屑标题
 * 支持从路由参数中提取信息来增强标题显示
 * @param menuTitle 菜单配置的标题
 * @param menuPath 菜单配置的路径(可能包含 :id 等参数)
 * @param routePath 实际路由路径
 * @param routeParams 路由参数对象
 * @param routeMeta 路由元信息
 * @returns 增强后的标题
 */
const getDynamicBreadcrumbTitle = (
	menuTitle: string,
	menuPath: string,
	routePath: string,
	routeParams: Record<string, string | string[]>,
	routeMeta: Record<string, any>,
): string => {
	// 如果路由元信息中有动态标题生成函数,优先使用
	if (routeMeta?.breadcrumbTitleGenerator && typeof routeMeta.breadcrumbTitleGenerator === "function") {
		return routeMeta.breadcrumbTitleGenerator(menuTitle, routeParams, routePath);
	}

	// 如果菜单路径包含动态参数(如 :id),尝试从路由参数中提取并增强标题
	if (menuPath.includes(":")) {
		// 提取路径中的参数名(如 :id, :param)
		const paramNames = menuPath.match(/:[^/]+/g) || [];
    
		// 尝试从路由参数中获取值并增强标题
		for (const paramName of paramNames) {
			const key = paramName.slice(1); // 去掉 : 号
			const paramValue = routeParams[key];
      
			if (paramValue) {
				const value = Array.isArray(paramValue) ? paramValue[0] : paramValue;
				// 如果参数值存在,可以增强标题(例如:"编辑" -> "编辑 #123")
				// 这里可以根据实际需求调整格式
				if (routeMeta?.breadcrumbTitleFormat) {
					// 如果路由元信息中定义了标题格式,使用该格式
					return routeMeta.breadcrumbTitleFormat.replace("{title}", menuTitle).replace("{param}", String(value));
				}
				// 默认格式:在标题后追加参数值(可以根据需要调整)
				// return `${menuTitle} #${value}`;
			}
		}
	}
	console.log("menuTitle", menuTitle);
  
	// 返回原始菜单标题
	return menuTitle;
};

// 面包屑导航
const breadcrumbs = computed<BreadcrumbItem[]>(() => {
	const crumbs: BreadcrumbItem[] = [ { title: "首页", path: "/home" } ];
	const normalizedRoutePath = route.path.replace(/\/+$/, "") || "/";

	// 如果不在首页,添加当前路由的面包屑
	if (route.path !== "/home" && route.path !== "/") {
		// 使用 getMenuChain 直接获取菜单链(包括所有父级和当前菜单项)
		// 这样可以一次性获取完整的菜单层级结构,避免多次查找
		// 注意:getMenuChain 已经支持动态路由匹配(通过 isPathMatch 函数)
		const menuChain = getMenuChain(allMenus.value, normalizedRoutePath);
    
		if (menuChain.length > 0) {
			// 将菜单链转换为面包屑项
			// 注意:隐藏的菜单项(hidden: true)可以选择性包含或不包含
			// 这里我们包含所有菜单项,包括隐藏的,以确保面包屑的完整性
			menuChain.forEach((menu, index) => {
				// 如果菜单项有 meta.showInBreadcrumb 配置,则根据配置决定
				// 否则默认都显示
				const shouldShow = menu.meta?.showInBreadcrumb !== false;
        
				if (shouldShow && // 避免重复添加相同的路径
          !crumbs.some(c => c.path === menu.path)) {
					// 判断是否为最后一个菜单项(当前路由对应的菜单项)
					const isLastMenuItem = index === menuChain.length - 1;
            
					// 如果是最后一个菜单项且是动态路由,尝试动态生成标题
					let breadcrumbTitle = menu.title;
					if (isLastMenuItem && menu.path.includes(":")) {
						breadcrumbTitle = getDynamicBreadcrumbTitle(
							menu.title,
							menu.path,
							normalizedRoutePath,
                route.params as Record<string, string | string[]>,
                route.meta as Record<string, any>,
						);
					}
            
					// 对于动态路由,面包屑路径使用实际路由路径,而不是菜单配置的路径(包含 :id)
					// 这样点击面包屑时可以正确导航
					const breadcrumbPath = menu.path.includes(":") && isLastMenuItem
						? normalizedRoutePath
						: menu.path;
            
					crumbs.push({ 
						title: breadcrumbTitle, 
						path: breadcrumbPath 
					});
				}
			});
		} else {
			// 如果没有找到匹配的菜单链,尝试使用路由元信息作为备选
			// 这对于动态路由特别有用,如果菜单配置中没有对应的菜单项
			if (route.meta?.title) {
				let title = route.meta.title as string;
        
				// 如果路由有参数,尝试增强标题
				if (Object.keys(route.params).length > 0) {
					title = getDynamicBreadcrumbTitle(
						title,
						route.path,
						normalizedRoutePath,
            route.params as Record<string, string | string[]>,
            route.meta as Record<string, any>,
					);
				}
        
				crumbs.push({ 
					title, 
					path: route.path 
				});
			}
		}
	}
  
	return crumbs;
});

// 菜单点击事件
const handleMenuClick = (menu: MenuItem) => {
	// 判断是否为微应用路由
	const isMicroApp = isMicroAppRoute(menu.path);

	// 如果是微应用路由,通过通信管理器传递菜单信息到微应用
	if (isMicroApp) {
		communicationManager.updateCurrentMenu({
			menuId: menu.id,
			menuTitle: menu.title,
			menuPath: menu.path,
			menuIcon: menu.icon,
			menuMeta: menu.meta,
		});
	}

	if (menu.meta?.externalLink) {
		window.open(menu.meta.externalLink, "_blank");
	} else {
		router.push(menu.path);
	}
};

// 菜单展开/收起
const handleMenuToggle = (menuId: string) => {
	if (expandedKeys.value.has(menuId)) {
		expandedKeys.value.delete(menuId);
	} else {
		expandedKeys.value.add(menuId);
	}
};

// 判断是否为微应用路由
const isMicroAppRoute = (path: string): boolean => {
	return microApps.some((app) => {
		const rule = app.activeRule;
		if (typeof rule === "string") {
			return path.startsWith(rule);
		}
		if (typeof rule === "function") {
			return rule(window.location as Location);
		}
		if (Array.isArray(rule)) {
			return rule.some((r: string) => path.startsWith(r));
		}
		return false;
	});
};

// 监听路由变化,自动展开当前激活菜单的父级并激活顶级菜单
watch(
	() => route.path,
	(newPath) => {
		// 更新激活的顶级菜单
		activeTopMenuId.value = getActiveTopMenuId(newPath);

		const paths = getMenuParentPaths(allMenus.value, newPath);

		// 递归展开所有父级菜单
		function expandParents(menus: MenuItem[], targetPath: string) {
			for (const menu of menus) {
				if (menu.children) {
					const hasActiveChild = paths.includes(menu.path);
					if (hasActiveChild) {
						expandedKeys.value.add(menu.id);
						expandParents(menu.children, targetPath);
					}
				}
			}
		}

		expandParents(allMenus.value, newPath);
	},
	{ immediate: true },
);
</script>

<template>
    <div class="basic-layout">
        <!-- 顶部区域 -->
        <header class="layout-top-header">
            <!-- Logo和标题 -->
            <div class="sidebar-header">
                <div class="logo"></div>
                <div class="title">
                    {{ appName }}
                </div>
            </div>
            <!-- 顶部导航 -->
            <div class="layout-header">
                <div class="header-left">
                    <Breadcrumb :breadcrumbs="breadcrumbs" />
                </div>
                <div class="header-right">
                    <!-- <div class="top-tools">
            <el-icon size="16" style="margin-right: 6px"><Download /></el-icon>
            <span>下载中心</span>
          </div> -->
                    <!-- <NotificationCenter /> -->
                    <UserInfo />
                </div>
            </div>
        </header>

        <!-- 主体区域 -->
        <main class="layout-main">
            <!-- 折叠按钮 -->
            <div class="collapse-button"
                 :style="{ left: isCollapsed ? '67px' : '215px' }"
                 @click="toggleCollapse">
                <img v-if="!isCollapsed"
                     alt=""
                     class="collapse-button"
                     src="/images/icon-collapse-left.png"
                     srcset="">
                <img v-else
                     alt=""
                     class="collapse-button"
                     src="/images/icon-collapse.png"
                     srcset="">
            </div>
      
            <!-- 侧边栏 - 显示所有菜单 -->
            <aside class="layout-sidebar" :class="{ collapsed: isCollapsed }">
                <div class="sidebar-menu">
                    <!-- 直接渲染所有侧边栏菜单,不显示 topMenus 分组标题 -->
                    <template v-for="topMenu in topMenus" :key="topMenu.id">
                        <template v-if="topMenu.sidebarMenus && topMenu.sidebarMenus.length > 0">
                            <template v-for="item in topMenu.sidebarMenus" :key="item.id">
                                <!-- 折叠模式下只显示一级菜单 -->
                                <SidebarMenuItem v-if="!isCollapsed || item.level === 1"
                                                 :active-path="route.path"
                                                 :collapsed="isCollapsed"
                                                 :expanded-keys="expandedKeys"
                                                 :menu="item"
                                                 @click="handleMenuClick"
                                                 @toggle="handleMenuToggle" />
                            </template>
                        </template>
                    </template>
                </div>
            </aside>

            <!-- 内容区域 -->
            <section class="layout-content">
                <!-- 微应用内容 -->
                <div class="content-wrapper">
                    <!-- qiankun 微应用容器 - 始终存在,避免时序问题 -->
                    <div id="subapp-container" 
                         class="micro-app-container"
                         :style="{ display: isMicroAppRoute(route.path) ? 'block' : 'none' }">
                    </div>
          
                    <!-- 主应用路由内容 -->
                    <div class="main-app-content"
                         :style="{ display: !isMicroAppRoute(route.path) ? 'block' : 'none' }">
                        <router-view v-slot="{ Component, route: viewRoute }">
                            <!-- 非微应用路由使用过渡动画 -->
                            <transition v-if="!isMicroAppRoute(viewRoute.path)"
                                        mode="out-in"
                                        name="fade">
                                <component :is="Component" />
                            </transition>
                        </router-view>
                    </div>
                </div>
            </section>
        </main>
    </div>
</template>

<style scoped>
.basic-layout {
	display: flex;
	flex-direction: column;
	height: 100vh;
	overflow: hidden;
	background-color: #f0f2f5;
}

/* 顶部区域 */
.layout-top-header {
	z-index: 100;
	display: flex;
	flex-shrink: 0;
	align-items: center;
	height: 56px;
	background: #fff;
	border-bottom: 1px solid #f2f4f7;
}

/* Logo和标题 */
.sidebar-header {
	display: flex;
	flex-shrink: 0;
	gap: 8px;
	align-items: center;
	width: 228px;
	height: 55px;
	padding-left: 24px;
	font-size: 20px;
	font-weight: 600;
	color: #0d162a;
	background: #fff;
	border-right: 1px solid #f2f4f7;
	transition: all 0.3s ease;

	.title {
		overflow: hidden;
		white-space: nowrap;
	}

	&.collapsed {
		justify-content: center;
		width: 80px;
		padding-left: 0;
	}
}

/* 头部样式 */
.layout-header {
	display: flex;
	flex: 1;
	align-items: center;
	justify-content: space-between;
	height: 56px;
	padding: 0 24px;
	background: #fff;
	border-bottom: 1px solid #F2F4F7;
}

/* 主体区域 */
.layout-main {
	position: relative;
	display: flex;
	flex: 1;
	flex-direction: row;
	min-width: 0;
	min-height: 0;
	overflow: hidden;
}

/* 折叠按钮 */
.collapse-button {
	position: fixed;
	top: 30%;
	z-index: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	width: 24px;
	height: 24px;
	color: #666;
	cursor: pointer;
	background: #fff;
	border-radius: 50%;
	transition: all 0.3s ease;

	&:hover {
		color: #1956fe;
		background: #f0f4ff;
		border-color: #b5c9ff;
	}
}

/* 侧边栏样式 */
.layout-sidebar {
	position: relative;
	display: flex;
	flex-shrink: 0;
	flex-direction: column;
	width: 228px;
	overflow: hidden auto;
	font-size: 14px;
	background: #f7f8f9;
	border-radius: 4px;
	box-shadow: 0 2px 8px rgb(0 0 0 / 6%);
	transition: width 0.3s ease;

	&.collapsed {
		width: 80px;
	}

	.sidebar-menu {
		flex: 1;
		padding-top: 18px;
		overflow: hidden auto;
	}
}

.header-left {
	flex: 0 0 auto;
}

.logo-icon {
	font-size: 24px;
}

.header-right {
	display: flex;
	flex: 0 0 auto;
	gap: 16px;
	align-items: center;
}

.layout-sidebar::-webkit-scrollbar,
.sidebar-menu::-webkit-scrollbar {
	width: 6px;
}

.layout-sidebar::-webkit-scrollbar-thumb,
.sidebar-menu::-webkit-scrollbar-thumb {
	background-color: rgb(0 0 0 / 20%);
	border-radius: 3px;
}

.layout-sidebar::-webkit-scrollbar-track,
.sidebar-menu::-webkit-scrollbar-track {
	background-color: transparent;
}

/* .sidebar-menu {
  padding: 8px 0;
} */

.menu-group:last-child {
	margin-bottom: 0;
}

.menu-group-title {
	display: flex;
	gap: 8px;
	align-items: center;
	padding: 12px 16px 8px;
	font-size: 14px;
	font-weight: 600;
	color: #666;
	cursor: pointer;
	user-select: none;
	background-color: #fafafa;
	border-left: 3px solid transparent;
	transition: all 0.3s ease;
}

.menu-group-title:hover {
	color: #1890ff;
	background-color: #e6f7ff;
}

.menu-group-title.active {
	color: #1956fe;
}

.group-icon {
	font-size: 16px;
}

/* 内容区域 */
.layout-content {
	display: flex;
	flex: 1;
	flex-direction: column;
	min-width: 0;
	min-height: 0;
	overflow-y: auto;
}

.content-wrapper {
	position: relative;
	flex: 1;
	min-height: 0;
	overflow-y: auto;
	background: #fff;
	border-radius: 4px;
	box-shadow: 0 2px 8px rgb(0 0 0 / 6%);
}

/* 微应用容器样式 */
.micro-app-container {
	width: 100%;
	height: 100%;
	min-height: 500px;
}

/* 主应用内容区域 */
.main-app-content {
	width: 100%;
	height: 100%;
	min-height: 500px;
}

.top-tools {
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 16px;
	font-size: 12px;
	cursor: pointer;
	border-radius: 50%;
	transition: background-color 0.2s;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
	transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
	opacity: 0;
}
</style>