Commit 3430d919 by Lin

fix: 交互样式修改

1 parent a5352202
......@@ -24,8 +24,10 @@ const props = defineProps({
// Emits
const emit = defineEmits(['update:visible', 'close']);
// 缩放比例
// 缩放比例(图片)
const scale = ref(1);
// PDF缩放比例
const pdfScale = ref(1);
// 旋转角度
const rotate = ref(0);
......@@ -44,8 +46,8 @@ const materialType = computed(() => {
return typeMap[type] || 'other';
});
// 计算属性:是否可以缩放(仅图片可缩放)
const canScale = computed(() => materialType.value === 'image');
// 计算属性:是否可以缩放(图片和PDF可缩放)
const canScale = computed(() => materialType.value === 'image' || isPdf.value);
// 计算属性:是否为 docx 文件
const isDocx = computed(() => {
......@@ -82,18 +84,29 @@ const officeViewerUrl = computed(() => {
return `http://view.officeapps.live.com/op/view.aspx?src=${encodedUrl}`;
});
// 计算属性:变换样式
// 计算属性:变换样式(图片)
const transformStyle = computed(() => {
if (!canScale.value) return {};
if (materialType.value !== 'image') return {};
return {
transform: `scale(${scale.value}) rotate(${rotate.value}deg)`,
transition: 'transform 0.3s ease',
};
});
// 计算属性:PDF变换样式
const pdfTransformStyle = computed(() => {
if (!isPdf.value) return {};
return {
transform: `scale(${pdfScale.value})`,
transformOrigin: 'top left',
transition: 'transform 0.3s ease',
};
});
// 重置缩放和旋转
const resetTransform = () => {
scale.value = 1;
pdfScale.value = 1;
rotate.value = 0;
};
......@@ -106,26 +119,46 @@ watch(dialogVisible, (newVal) => {
// 放大
const handleZoomIn = () => {
if (scale.value < 3) {
scale.value = Math.min(scale.value + 0.25, 3);
if (isPdf.value) {
if (pdfScale.value < 3) {
pdfScale.value = Math.min(pdfScale.value + 0.25, 3);
}
} else {
if (scale.value < 3) {
scale.value = Math.min(scale.value + 0.25, 3);
}
}
};
// 缩小
const handleZoomOut = () => {
if (scale.value > 0.5) {
scale.value = Math.max(scale.value - 0.25, 0.5);
if (isPdf.value) {
if (pdfScale.value > 0.5) {
pdfScale.value = Math.max(pdfScale.value - 0.25, 0.5);
}
} else {
if (scale.value > 0.5) {
scale.value = Math.max(scale.value - 0.25, 0.5);
}
}
};
// 重置为 1:1
const handleReset = () => {
scale.value = 1;
if (isPdf.value) {
pdfScale.value = 1;
} else {
scale.value = 1;
}
};
// 适应屏幕
const handleFit = () => {
scale.value = 0.8;
if (isPdf.value) {
pdfScale.value = 0.8;
} else {
scale.value = 0.8;
}
};
// 下载
......@@ -174,18 +207,30 @@ const errorPptxHandler = (error) => {
console.error('PPTX 预览失败:', error);
ElMessage.error('PPTX 预览失败,请尝试下载后查看');
};
// 鼠标滚轮缩放处理(PDF)
const handlePdfWheel = (event) => {
if (!isPdf.value) return;
// 按住Ctrl键时进行缩放
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
const delta = event.deltaY > 0 ? -0.1 : 0.1;
const newScale = Math.max(0.5, Math.min(3, pdfScale.value + delta));
pdfScale.value = newScale;
}
};
</script>
<template>
<el-dialog
v-model="dialogVisible"
:show-close="false"
width="40%"
width="60%"
class="preview-material-dialog"
@close="handleClose"
>
<!-- 关闭按钮 -->
<div class="absolute right-[-49%] top-[-15%] z-50 flex cursor-pointer items-center justify-center rounded-full backdrop-blur-sm transition-all">
<div class="absolute right-[-20%] top-[-15%] z-50 flex cursor-pointer items-center justify-center rounded-full backdrop-blur-sm transition-all">
<img
src="/images/icon-preview-close.png"
alt="关闭"
......@@ -220,22 +265,24 @@ const errorPptxHandler = (error) => {
<!-- 文档预览 -->
<div v-else-if="materialType === 'document'" class="flex flex-1 flex-col overflow-hidden">
<!-- PDF 预览 -->
<div v-if="isPdf" class="overflow-auto bg-white" style="width: 640px; height: 640px; margin: 0 auto;">
<VueOfficePdf
:src="material?.filePath"
style="height: 100%;"
@rendered="() => console.log('PDF 渲染完成')"
@error="(error) => {
console.error('PDF 预览失败:', error);
ElMessage.error('PDF 预览失败,请尝试下载后查看');
}"
/>
<div v-if="isPdf" class="relative h-full w-full overflow-auto bg-white" @wheel="handlePdfWheel">
<div class="pdf-container" :style="pdfTransformStyle">
<VueOfficePdf
:src="material?.filePath"
style="width: 100%; height: 100%;"
@rendered="() => console.log('PDF 渲染完成')"
@error="(error) => {
console.error('PDF 预览失败:', error);
ElMessage.error('PDF 预览失败,请尝试下载后查看');
}"
/>
</div>
</div>
<!-- docx 预览 -->
<div v-else-if="isDocx" class="overflow-auto bg-white" style="width: 640px; height: 640px; margin: 0 auto;">
<div v-else-if="isDocx" class="h-full w-full overflow-auto bg-white">
<VueOfficeDocx
:src="material?.filePath"
style="height: 100%;"
style="width: 100%; height: 100%;"
@rendered="() => console.log('docx 渲染完成')"
@error="(error) => {
console.error('docx 预览失败:', error);
......@@ -298,10 +345,10 @@ const errorPptxHandler = (error) => {
<!-- 放大 -->
<button
v-if="canScale"
:disabled="scale >= 3"
:disabled="isPdf ? pdfScale >= 3 : scale >= 3"
:class="[
'flex h-9 w-9 items-center justify-center rounded-lg border-none text-sm transition-all duration-200',
scale >= 3
(isPdf ? pdfScale >= 3 : scale >= 3)
? 'cursor-not-allowed bg-[#F5F5F5] text-[#CCCCCC] opacity-50'
: 'cursor-pointer bg-[#F5F5F5] text-[#666666] hover:bg-[#E5E5E5] hover:text-[#1956FE] active:scale-95'
]"
......@@ -313,10 +360,10 @@ const errorPptxHandler = (error) => {
<!-- 缩小 -->
<button
v-if="canScale"
:disabled="scale <= 0.5"
:disabled="isPdf ? pdfScale <= 0.5 : scale <= 0.5"
:class="[
'flex h-9 w-9 items-center justify-center rounded-lg border-none text-sm transition-all duration-200',
scale <= 0.5
(isPdf ? pdfScale <= 0.5 : scale <= 0.5)
? 'cursor-not-allowed bg-[#F5F5F5] text-[#CCCCCC] opacity-50'
: 'cursor-pointer bg-[#F5F5F5] text-[#666666] hover:bg-[#E5E5E5] hover:text-[#1956FE] active:scale-95'
]"
......@@ -384,5 +431,14 @@ const errorPptxHandler = (error) => {
opacity: 0.8 !important;
background: #000000 !important;
}
/* PDF 容器样式 */
.pdf-container {
width: 100%;
height: 100%;
display: flex;
align-items: flex-start;
justify-content: flex-start;
}
</style>
......@@ -48,7 +48,7 @@ const routes: RouteRecordRaw[] = [
name: 'AssistantEdit',
component: () => import('@/views/Assistant/addUpdate.vue'),
meta: {
title: '编辑智能体',
title: '编辑',
},
},
{
......
......@@ -311,7 +311,7 @@ const handleFileChange = async (file) => {
validation: {
allowedTypes: ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
allowedExtensions: ['pdf', 'doc', 'docx'],
maxSize: 10 * 1024 * 1024, // 10MB
maxSize: 50 * 1024 * 1024, // 50MB
errorMessage: '文件格式错误,仅支持 PDF、Word 格式',
},
onSuccess: (url) => {
......@@ -489,7 +489,7 @@ const cancel = () => {
class="w-[776px]"
v-model="formData.personaPromptDetail"
type="textarea"
:rows="6"
:rows="4"
maxlength="5000"
show-word-limit
placeholder="请输入人设提示词."
......@@ -536,7 +536,7 @@ const cancel = () => {
>
<el-button icon="Upload"> <el-icon><Upload /></el-icon> 选择文件</el-button>
</el-upload>
<div class="mt-[5px] text-xs text-[#909399]">支持pdf, word格式,大小在10M以内</div>
<div class="mt-[5px] text-xs text-[#909399]">支持pdf, word格式,大小在50M以内</div>
<!-- 已上传文件显示 -->
<div v-if="fileInfo.name" class="mt-2 flex items-center gap-2">
<el-icon class="text-[#409eff]"><Document /></el-icon>
......
......@@ -179,6 +179,7 @@ const handleCurrentChange = (val) => {
placeholder="请输入"
clearable
style="width: 220px"
maxlength="50"
@keyup.enter="handleSearch"
/>
</el-form-item>
......
......@@ -81,7 +81,7 @@
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ref, reactive, computed, toRaw } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { inspectionRuleList, addInspectionRule as addInspectionRuleApi, addInspectionTemplate as addInspectionTemplateApi, updateInspectionRule as updateInspectionRuleApi, updateInspectionTemplate as updateInspectionTemplateApi } from '@/api/agentic'
......@@ -115,19 +115,30 @@ const rules = reactive<FormRules>({
{ required: true, message: '请输入规则名称', trigger: 'blur' }
],
description: [
{ required: true, message: '请输入规则详细描述', trigger: 'blur' }
{
required: true,
validator: (_rule, _value, callback) => {
if (!formData.description || formData.description.trim() === '') {
const message = screenType.value === 'template' ? '请输入模板说明' : '请输入规则详细描述'
callback(new Error(message))
} else {
callback()
}
},
trigger: 'blur'
}
],
materials: [
{
validator: (_rule, value, callback) => {
// 当 screenTitle !== 'rule' 时(即为模版时),materials 必传
// 当 screenType !== 'rule' 时(即为模版时),materials 必传
if (screenType.value !== 'rule' && (!value || value.length === 0)) {
callback(new Error('请选择质检规则'))
} else {
callback()
}
},
trigger: 'change'
trigger: ['change', 'blur']
}
]
})
......
......@@ -244,6 +244,44 @@ const fileInfo = ref({
size: '',
status: true,
});
// 上传文件类型与大小限制(单位 MB)
const fileConstraints = {
document: { extensions: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'], maxSizeMB: 50 },
video: { extensions: ['mp4', 'mov'], maxSizeMB: 100 },
image: { extensions: ['jpg', 'jpeg', 'png'], maxSizeMB: 10 }
};
/**
* 校验文件类型与大小
*/
const validateFile = (file) => {
const raw = file.raw || file;
if (!raw) {
return { valid: false, message: '文件不存在' };
}
const name = raw.name || file.name || '';
const extension = name.split('.').pop()?.toLowerCase() || '';
const size = raw.size || 0;
let constraintKey = '';
if (fileConstraints.document.extensions.includes(extension)) {
constraintKey = 'document';
} else if (fileConstraints.video.extensions.includes(extension)) {
constraintKey = 'video';
} else if (fileConstraints.image.extensions.includes(extension)) {
constraintKey = 'image';
} else {
return { valid: false, message: '仅支持上传 PDF、Word、Excel、PPT、MP4、MOV、JPG、PNG 文件' };
}
const limitMB = fileConstraints[constraintKey].maxSizeMB;
if (size > limitMB * 1024 * 1024) {
return { valid: false, message: `${name} 超出大小限制(最大 ${limitMB}MB)` };
}
return { valid: true };
};
// --- OSS Upload Instance ---
const ossApi = new GlOssApi();
......@@ -344,7 +382,23 @@ const uploadFileToOSS = async (fileObj) => {
const processFiles = async (files) => {
if (!files || files.length === 0) return;
const fileList = Array.from(files).map(file => normalizeFile(file));
const validFiles = [];
for (const file of Array.from(files)) {
const validation = validateFile(file);
if (!validation.valid) {
ElMessage.error(validation.message);
continue;
}
validFiles.push(file);
}
if (validFiles.length === 0) {
formData.files = [];
fileInfo.value = { ...fileInfo.value, status: false };
return;
}
const fileList = validFiles.map(file => normalizeFile(file));
formData.files = fileList;
// 自动上传新文件(已有 URL 的文件不需要上传)
......@@ -353,10 +407,19 @@ const processFiles = async (files) => {
try {
await uploadFileToOSS(fileObj);
ElMessage.success(`${fileObj.name} 上传成功`);
// 清除文件字段的校验提示
if (formRef.value) {
formRef.value.clearValidate('files');
}
} catch (error) {
console.error('文件上传失败:', error);
ElMessage.error(`${fileObj.name} 上传失败: ${error.message || '未知错误'}`);
}
} else if (fileObj.url || fileObj.status === 'success') {
// 如果文件已有 URL 或已上传成功,也清除校验提示
if (formRef.value) {
formRef.value.clearValidate('files');
}
}
}
};
......@@ -365,16 +428,39 @@ const processFiles = async (files) => {
* 文件变化处理
*/
const handleFileChange = (file, fileList) => {
const validation = validateFile(file);
if (!validation.valid) {
ElMessage.error(validation.message);
const filtered = fileList.filter(item => item.uid !== file.uid);
formData.files = filtered;
fileInfo.value = {
...fileInfo.value,
name: file.name || '',
size: '',
status: false,
};
return;
}
formData.files = fileList;
// 如果文件是新添加的且未上传,自动上传
// 已有 URL 的文件(编辑模式)不需要重新上传
if (file.status === 'ready' && file.raw && !file.url) {
uploadFileToOSS(file).then(result => {
console.log("文件上传成功",result);
// 清除文件字段的校验提示
if (formRef.value) {
formRef.value.clearValidate('files');
}
}).catch(error => {
console.error('文件上传失败:', error);
ElMessage.error(`${file.name} 上传失败: ${error.message || '未知错误'}`);
});
} else if (file.url || file.status === 'success') {
// 如果文件已有 URL 或已上传成功,也清除校验提示
if (formRef.value) {
formRef.value.clearValidate('files');
}
}
};
......
......@@ -61,22 +61,33 @@ const getCategoryList = async () => {
};
// 取消所有编辑状态(排他性处理)
const cancelAllEdits = (excludeId = null) => {
categories.value.forEach((category) => {
const toRemove = [];
categories.value.forEach((category, index) => {
// 排除指定 id,避免取消当前正在编辑的项
if (excludeId !== null && category.id === excludeId) {
return;
}
if (category.isEdit) {
const original = originalData.value[category.id];
// 如果是新建的空数据(原始 name 为空),直接移除占位项
if (original && original.name === '') {
toRemove.push(index);
delete originalData.value[category.id];
return;
}
// 恢复原始数据
if (originalData.value[category.id]) {
Object.assign(category, originalData.value[category.id]);
if (original) {
Object.assign(category, original);
delete originalData.value[category.id];
}
// 退出编辑状态
category.isEdit = false;
}
});
// 反向删除,避免索引偏移
toRemove.reverse().forEach((idx) => {
categories.value.splice(idx, 1);
});
};
// 处理分类切换
......@@ -114,6 +125,12 @@ const handleConfirm = async (item, event) => {
return;
}
// 禁止创建名称为"未分组"的子项
if (item.name.trim() === '未分组') {
ElMessage.warning('不能创建名称为"未分组"的分组');
return;
}
// 保存当前id(可能是临时id),用于后续删除originalData
const currentId = item.id;
......@@ -715,6 +732,7 @@ onMounted(() => {
placeholder="请输入分组名称"
size="small"
class="edit-input"
maxlength="10"
@keyup.enter="handleConfirm(item, $event)"
@keyup.esc="handleCancel(item, $event)"
/>
......@@ -766,6 +784,7 @@ onMounted(() => {
<el-input
v-model="filterForm.name"
placeholder="请输入"
maxlength="50"
class="!w-[240px]"
/>
</div>
......
# 动态路由面包屑处理指南
## 概述
本文档说明如何在面包屑中正确处理动态路由(如 `/assistant/edit/:id`)并获取对应的菜单标题。
## 核心功能
系统已经支持以下功能:
1. **动态路由匹配**:`isPathMatch` 函数支持匹配包含参数的路由(如 `/assistant/edit/:id` 可以匹配 `/assistant/edit/123`)
2. **菜单链查找**:`getMenuChain` 函数可以查找动态路由对应的菜单项及其所有父级菜单
3. **动态标题生成**:支持根据路由参数动态生成面包屑标题
## 使用方式
### 方式一:在菜单配置中定义动态路由菜单项
在菜单配置中,可以直接定义包含动态参数的路径:
```typescript
{
id: 'assistant-edit',
title: '编辑智能体',
path: '/assistant/edit/:id', // 注意:路径中包含 :id 参数
meta: {
showInBreadcrumb: true,
}
}
```
当访问 `/assistant/edit/123` 时,系统会:
1. 自动匹配到菜单配置中的 `/assistant/edit/:id`
2. 在面包屑中显示"编辑智能体"
3. 面包屑路径使用实际路径 `/assistant/edit/123`(而不是 `/assistant/edit/:id`)
### 方式二:使用路由元信息配置动态标题
如果菜单配置中没有对应的菜单项,可以在路由配置中使用 `meta.title`:
```typescript
{
path: '/assistant/edit/:id',
name: 'AssistantEdit',
component: () => import('@/views/Assistant/addUpdate.vue'),
meta: {
title: '编辑', // 基础标题
// 可选:自定义标题格式
breadcrumbTitleFormat: '{title} #{param}', // 例如:"编辑 #123"
},
}
```
### 方式三:使用自定义标题生成函数
对于更复杂的场景,可以使用自定义函数生成标题:
```typescript
{
path: '/assistant/edit/:id',
name: 'AssistantEdit',
component: () => import('@/views/Assistant/addUpdate.vue'),
meta: {
title: '编辑',
// 自定义标题生成函数
breadcrumbTitleGenerator: (menuTitle, routeParams, routePath) => {
const id = routeParams.id;
// 可以根据 id 从 store 或其他地方获取详细信息
// 例如:const agent = getAgentById(id);
// return agent ? `编辑 ${agent.name}` : `${menuTitle} #${id}`;
return `${menuTitle} #${id}`;
},
},
}
```
## 实现原理
### 1. 路径匹配算法
`isPathMatch` 函数使用正则表达式匹配动态路由:
```typescript
// 将 /assistant/edit/:id 转换为正则表达式
// /assistant/edit/[^/]+
const pattern = normalizedMenuPath
.replace(/:[^/]+/g, '[^/]+')
.replace(/\//g, '\\/');
const regex = new RegExp(`^${pattern}$`);
```
### 2. 菜单链查找
`getMenuChain` 函数递归查找匹配的菜单项及其所有父级:
```typescript
// 对于路径 /assistant/edit/123
// 会查找并返回:
// [
// { title: '岗位助理配置', path: '/assistant' },
// { title: '编辑智能体', path: '/assistant/edit/:id' }
// ]
```
### 3. 动态标题生成
`getDynamicBreadcrumbTitle` 函数根据以下优先级生成标题:
1. 如果路由元信息中有 `breadcrumbTitleGenerator` 函数,使用该函数
2. 如果路由元信息中有 `breadcrumbTitleFormat` 格式字符串,使用该格式
3. 否则返回原始菜单标题
## 最佳实践
### 1. 菜单配置优先
**推荐**:在菜单配置中定义动态路由菜单项,这样可以:
- 保持菜单和面包屑的一致性
- 支持菜单高亮和展开
- 更好的可维护性
```typescript
// 在菜单配置中
{
id: 'assistant-edit',
title: '编辑智能体',
path: '/assistant/edit/:id',
parentId: 'assistant-list',
}
```
### 2. 路由元信息作为备选
如果菜单配置中没有对应的菜单项,使用路由元信息:
```typescript
// 在路由配置中
{
path: '/assistant/edit/:id',
meta: {
title: '编辑智能体',
},
}
```
### 3. 复杂场景使用自定义函数
当需要根据路由参数获取详细信息时,使用自定义函数:
```typescript
meta: {
breadcrumbTitleGenerator: async (menuTitle, routeParams) => {
const id = routeParams.id;
// 从 API 或 store 获取详细信息
const detail = await fetchAgentDetail(id);
return detail ? `编辑 ${detail.name}` : menuTitle;
},
}
```
## 示例场景
### 场景 1:编辑页面
**路由**:`/assistant/edit/:id`
**菜单配置**:
```typescript
{
path: '/assistant/edit/:id',
title: '编辑智能体',
}
```
**结果**:面包屑显示 "首页 / 岗位助理配置 / 编辑智能体"
### 场景 2:带参数显示
**路由**:`/assistant/edit/123`
**路由配置**:
```typescript
{
path: '/assistant/edit/:id',
meta: {
title: '编辑',
breadcrumbTitleFormat: '{title} #{param}',
},
}
```
**结果**:面包屑显示 "首页 / 岗位助理配置 / 编辑 #123"
### 场景 3:动态名称显示
**路由**:`/assistant/edit/123`
**路由配置**:
```typescript
{
path: '/assistant/edit/:id',
meta: {
title: '编辑',
breadcrumbTitleGenerator: (menuTitle, routeParams) => {
const agent = getAgentFromStore(routeParams.id);
return agent ? `编辑 ${agent.name}` : menuTitle;
},
},
}
```
**结果**:面包屑显示 "首页 / 岗位助理配置 / 编辑 智能体A"
## 注意事项
1. **路径格式**:菜单配置中的动态路由路径必须使用 `:param` 格式(如 `:id`)
2. **路径匹配**:系统会自动处理路径匹配,无需手动转换
3. **面包屑路径**:动态路由的面包屑路径会使用实际路径,而不是菜单配置中的路径(包含 `:id`)
4. **性能考虑**:自定义标题生成函数如果是异步的,建议使用缓存避免重复请求
## 相关文件
- `src/config/menus.ts` - 菜单工具函数(`isPathMatch`, `getMenuChain`)
- `src/layouts/BasicLayout.vue` - 面包屑生成逻辑
- `src/layouts/components/Breadcrumb.vue` - 面包屑组件
......@@ -49,6 +49,7 @@ export interface MenuConfig {
parentId?: string;
path: string;
title: string;
hidden?: boolean;
}>;
title: string;
}>;
......@@ -141,5 +142,6 @@ function transformSidebarMenus(
parentId: menu.parentId,
children: menu.children ? transformSidebarMenus(menu.children) : undefined,
meta: menu.meta,
hidden: menu.hidden,
}));
}
......@@ -48,34 +48,155 @@ export function findMenuItem(menus: MenuItem[], id: string): MenuItem | null {
}
/**
* 获取菜单的所有父级路径
* 检查路径是否匹配(支持动态路由参数)
* @param menuPath 菜单配置的路径(可能包含 :id, :param 等参数)
* @param targetPath 实际路由路径
* @returns 是否匹配
*/
export function isPathMatch(menuPath: string, targetPath: string): boolean {
if (!menuPath || !targetPath) {
return false;
}
// 去掉末尾多余的 /,方便匹配像 /edit/ 与 /edit/2 这类场景
const normalizedMenuPath = menuPath.replace(/\/+$/, '');
const normalizedTargetPath = targetPath.replace(/\/+$/, '');
// 精确匹配
if (normalizedMenuPath === normalizedTargetPath) {
return true;
}
// 如果菜单路径包含参数占位符(如 :id),转换为正则表达式匹配
if (normalizedMenuPath.includes(':')) {
// 将路径中的 :id, :param 等替换为正则表达式的非斜杠字符匹配
// 例如: /assisant/assistant/edit/:id -> /assisant/assistant/edit/[^/]+
const pattern = normalizedMenuPath
.replace(/:[^/]+/g, '[^/]+')
.replace(/\//g, '\\/');
// 匹配完整路径,例如: /assisant/assistant/edit/123 应该匹配 /assisant/assistant/edit/:id
const regex = new RegExp(`^${pattern}$`);
return regex.test(normalizedTargetPath);
}
// 如果目标路径以菜单路径开头,也认为是匹配(用于处理动态路由参数)
// 例如:菜单路径是 /assisant/assistant/edit,实际路径是 /assisant/assistant/edit/123
// 检查菜单路径是否是目标路径的前缀,且目标路径的下一个字符是 / 或结束
if (normalizedTargetPath.startsWith(normalizedMenuPath)) {
const nextChar = normalizedTargetPath[normalizedMenuPath.length];
// 如果下一个字符是 / 或者是 undefined(路径结束),则匹配
if (nextChar === '/' || nextChar === undefined) {
return true;
}
}
return false;
}
/**
* 获取菜单的所有父级路径(包括自身)
* 支持动态路由参数匹配(如 /edit/:id 可以匹配 /edit/123)
* 返回的路径数组按照菜单层级顺序排列(从一级到当前级)
*
* @param menus 菜单列表
* @param targetPath 目标路径
* @returns 路径数组,按层级顺序排列
*/
export function getMenuParentPaths(
menus: MenuItem[],
targetPath: string,
): string[] {
const paths: string[] = [];
const normalizedTargetPath = targetPath.replace(/\/+$/, '');
function findPath(
/**
* 递归查找路径链
* @param items 当前层级的菜单项
* @param target 目标路径
* @param currentPathChain 当前已构建的路径链
* @returns 是否找到匹配项
*/
function findPathChain(
items: MenuItem[],
target: string,
currentPaths: string[],
currentPathChain: string[],
): boolean {
for (const item of items) {
const newPaths = [...currentPaths, item.path];
// 构建新的路径链(包含当前项)
const newPathChain = [...currentPathChain, item.path];
if (item.path === target) {
paths.push(...newPaths);
// 使用路径匹配检查当前项是否匹配目标路径
if (isPathMatch(item.path, target)) {
// 找到匹配项,将完整的路径链添加到结果中
paths.push(...newPathChain);
return true;
}
if (item.children && findPath(item.children, target, newPaths)) {
// 递归查找子菜单
if (item.children && item.children.length > 0) {
if (findPathChain(item.children, target, newPathChain)) {
// 在子菜单中找到匹配项,路径链已经添加到 paths 中
return true;
}
}
}
return false;
}
// 开始查找路径链
findPathChain(menus, normalizedTargetPath, []);
// 返回去重后的路径数组(虽然理论上不应该有重复,但为了安全起见)
return Array.from(new Set(paths));
}
/**
* 查找菜单项及其所有父级菜单项
* 返回的数组按照菜单层级顺序排列(从一级到当前级)
*
* @param menus 菜单列表
* @param targetPath 目标路径
* @returns 菜单项数组,按层级顺序排列
*/
export function getMenuChain(
menus: MenuItem[],
targetPath: string,
): MenuItem[] {
const menuChain: MenuItem[] = [];
const normalizedTargetPath = targetPath.replace(/\/+$/, '');
/**
* 递归查找菜单链
*/
function findMenuChain(
items: MenuItem[],
target: string,
currentChain: MenuItem[],
): boolean {
for (const item of items) {
// 构建新的菜单链(包含当前项)
const newChain = [...currentChain, item];
// 使用路径匹配检查当前项是否匹配目标路径
if (isPathMatch(item.path, target)) {
// 找到匹配项,将完整的菜单链添加到结果中
menuChain.push(...newChain);
return true;
}
// 递归查找子菜单
if (item.children && item.children.length > 0) {
if (findMenuChain(item.children, target, newChain)) {
// 在子菜单中找到匹配项,菜单链已经添加到 menuChain 中
return true;
}
}
}
return false;
}
findPath(menus, targetPath, []);
return paths;
// 开始查找菜单链
findMenuChain(menus, normalizedTargetPath, []);
return menuChain;
}
......@@ -4,7 +4,7 @@ import type { BreadcrumbItem, MenuItem } from '@/types/menu';
import { computed, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { defaultTopMenus, getMenuParentPaths } from '@/config/menus';
import { defaultTopMenus, getMenuChain, getMenuParentPaths } from '@/config/menus';
import { microApps } from '@/qiankun/apps';
import { communicationManager } from '@/qiankun/communication';
import { useMenuStore } from '@/stores';
......@@ -20,7 +20,7 @@ const route = useRoute();
const menuStore = useMenuStore();
// 应用名称(从环境变量读取)
const appName = '汽车销售智能体';
const appName = '超级孪生智能体';
// 展开的菜单项 keys
const expandedKeys = ref<Set<string>>(new Set());
......@@ -28,14 +28,35 @@ const expandedKeys = ref<Set<string>>(new Set());
// 当前激活的顶级菜单 ID
const activeTopMenuId = ref<string>('');
// 侧边栏折叠状态
const isCollapsed = ref<boolean>(false);
// 侧边栏折叠状态(从本地存储恢复)
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
......@@ -55,6 +76,7 @@ const allMenus = computed(() => {
menus.push(...topMenu.sidebarMenus);
}
});
return menus;
});
......@@ -68,46 +90,137 @@ const getActiveTopMenuId = (path: string): string => {
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 !== '/') {
const paths = getMenuParentPaths(allMenus.value, route.path);
// 根据路径找到对应的菜单项
paths.forEach((path) => {
const menu = findMenuByPath(allMenus.value, path);
if (menu) {
crumbs.push({ title: menu.title, path: menu.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) {
// 避免重复添加相同的路径
if (!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
});
}
});
// 如果没有找到匹配的菜单,使用路由元信息
if (crumbs.length === 1 && route.meta.title) {
crumbs.push({ title: route.meta.title as string, path: route.path });
}
}
return crumbs;
});
// 递归查找菜单项
function findMenuByPath(menus: MenuItem[], path: string): MenuItem | null {
for (const menu of menus) {
if (menu.path === path) {
return menu;
}
if (menu.children) {
const found = findMenuByPath(menu.children, path);
if (found) return found;
}
}
return null;
}
// 菜单点击事件
const handleMenuClick = (menu: MenuItem) => {
// 判断是否为微应用路由
......
<script setup lang="ts">
import type { BreadcrumbItem } from '@/types/menu';
// import { useRouter } from 'vue-router';
import { useRouter } from 'vue-router';
defineProps<{
breadcrumbs: BreadcrumbItem[];
}>();
// const router = useRouter();
const router = useRouter();
const handleBreadcrumbClick = (
crumb: BreadcrumbItem,
index: number,
breadcrumbs: BreadcrumbItem[],
) => {
console.log('handleBreadcrumbClick', crumb, index, breadcrumbs);
// if (crumb.path && index < breadcrumbs.length - 1) {
// router.push(crumb.path);
// }
// 只有非最后一项且有路径的面包屑项可以点击
if (crumb.path && index < breadcrumbs.length - 1) {
router.push(crumb.path);
}
};
</script>
......@@ -31,9 +31,9 @@ const handleBreadcrumbClick = (
}"
@click="handleBreadcrumbClick(crumb, index, breadcrumbs)"
>
{{ crumb.title }}
{{ crumb.title }}
</span>
<span v-if="index < breadcrumbs.length - 1" class="breadcrumb-separator"
<span v-if="index < breadcrumbs.length - 1" class="breadcrumb-separator"
>/</span
>
</template>
......@@ -56,13 +56,13 @@ const handleBreadcrumbClick = (
.breadcrumb-item.clickable {
color: #969aa3;
cursor: default;
cursor: pointer;
transition: color 0.3s;
}
/* .breadcrumb-item.clickable:hover {
.breadcrumb-item.clickable:hover {
color: #2f3133;
} */
}
.breadcrumb-separator {
margin: 0 8px;
......
......@@ -28,9 +28,12 @@ const showPopover = ref<boolean>(false);
const menuItemRef = ref<HTMLElement | null>(null);
const popoverTop = ref<number>(0);
// 是否有子菜单
// 是否有子菜单(只计算非隐藏的子菜单)
const hasChildren = computed(() => {
return props.menu.children && props.menu.children.length > 0;
return (
props.menu.children &&
props.menu.children.filter((child) => !child.hidden).length > 0
);
});
// 是否展开
......@@ -117,6 +120,7 @@ const handleChildClick = (child: MenuItem) => {
<template>
<div
v-if="!menu.hidden"
ref="menuItemRef"
class="sidebar-menu-item"
:class="{ collapsed: collapsed }"
......@@ -188,7 +192,7 @@ const handleChildClick = (child: MenuItem) => {
class="submenu"
>
<SidebarMenuItem
v-for="child in menu.children"
v-for="child in menu.children?.filter(c => !c.hidden)"
:key="child.id"
:menu="child"
:active-path="activePath"
......@@ -211,7 +215,7 @@ const handleChildClick = (child: MenuItem) => {
<div class="popover-content">
<div class="popover-menu-list">
<div
v-for="child in menu.children"
v-for="child in menu.children?.filter(c => !c.hidden)"
:key="child.id"
class="popover-menu-item"
:class="{ active: checkChildActive(child) }"
......
......@@ -25,14 +25,23 @@
"build:filter": "node scripts/build/buildToRoot.mjs",
"build:docs": "pnpm run build --filter=@venus/docs",
"changeset": "pnpm exec changeset",
"check": "pnpm run check:circular && pnpm run check:dep && pnpm run check:type && pnpm check:cspell",
"check:circular": "vsh check-circular",
"check:cspell": "cspell lint **/*.ts **/README.md .changeset/*.md --no-progress",
"check:dep": "vsh check-dep",
"check:type": "turbo run typecheck",
"clean": "node ./scripts/clean.mjs",
"commit": "powershell -ExecutionPolicy Bypass -File ./scripts/commit.ps1",
"format": "vsh lint --format",
"lint": "vsh lint",
"postinstall": "pnpm -r run stub --if-present",
"prepare": "husky",
"preinstall": "npx only-allow pnpm",
"preview": "turbo-run preview",
"publint": "vsh publint",
"reinstall": "pnpm clean --del-lock && pnpm install",
"test:unit": "vitest run --dom",
"test:e2e": "turbo run test:e2e",
"update:deps": "npx taze -r -w",
"version": "pnpm exec changeset version && pnpm install --no-frozen-lockfile",
"catalog": "pnpx codemod pnpm/catalog",
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!