优化导航菜单

This commit is contained in:
biss committed 2026-10-20 21:15:27 +08:00
1 parent 4360280aee
commit 23fdbf422f
13 files changed
+10595 -19

No files matched your search

+334 -9
View File
@@ -2,7 +2,8 @@
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Bell, Operation } from '@element-plus/icons-vue'
import http from '../api/http'
import { ElMessage } from 'element-plus'
import http, { apiErrorMessage } from '../api/http'
import { branding } from '../config/branding'
import { useAuthStore } from '../stores/auth'
import { usePluginStore } from '../stores/plugins'
@@ -17,6 +18,7 @@ async function pollUnread() {
}
interface NavigationItem {
id?: string
path: string
label: string
}
@@ -28,11 +30,78 @@ interface NavigationGroup {
items: NavigationItem[]
}
const stableNavigationIds: Record<string, string> = {
'/dashboard': 'dashboard',
'/academic-calendar': 'academic-calendar',
'/statistics': 'statistics',
'/experiments': 'experiments',
'/experiment-grades': 'experiment-grades',
'/base-data/organization': 'base-data.organization',
'/base-data/terms': 'base-data.terms',
'/base-data/facilities': 'base-data.facilities',
'/teachers': 'teachers',
'/students': 'students',
'/users': 'users',
'/plugins': 'plugins',
'/operations': 'operations',
'/base-data/course-categories': 'base-data.course-categories',
'/courses': 'courses',
'/teaching-preferences': 'teaching-preferences',
'/curriculum': 'curriculum',
'/course-equivalency-rules': 'course-equivalency-rules',
'/my-curriculum': 'my-curriculum',
'/teaching-tasks': 'teaching-tasks',
'/schedules': 'schedules',
'/my-timetable': 'my-timetable',
'/free-classrooms': 'free-classrooms',
'/venue-displays': 'venue-displays',
'/class-timetable': 'class-timetable',
'/classroom-reservations': 'classroom-reservations',
'/campus-registrations': 'campus-registrations',
'/campus-wallets': 'campus-wallets',
'/tuition': 'tuition',
'/classroom-repairs': 'classroom-repairs',
'/dormitory-services': 'dormitory-services',
'/dormitory-overview': 'dormitory-overview',
'/dormitory-buildings': 'dormitory-buildings',
'/dormitory-allocation': 'dormitory-allocation',
'/dormitory-applications': 'dormitory-applications',
'/dormitory-hygiene-scores': 'dormitory-hygiene-scores',
'/course-selections': 'course-selections',
'/course-enrollments': 'course-enrollments',
'/teacher-attendance': 'teacher-attendance',
'/my-attendance': 'my-attendance',
'/evaluations': 'evaluations',
'/teacher-roster': 'teacher-roster',
'/grades': 'grades',
'/academic-overview': 'academic-overview',
'/grade-analytics': 'grade-analytics',
'/event-analytics': 'event-analytics',
'/other-exams': 'other-exams',
'/exams': 'exams',
'/makeup-exams': 'makeup-exams',
'/physical-fitness': 'physical-fitness',
'/my-profile': 'my-profile',
'/student-status-changes': 'student-status-changes',
'/official-documents': 'official-documents',
'/approvals': 'approvals',
'/warnings': 'warnings',
'/academic-planning': 'academic-planning',
'/graduation-audits': 'graduation-audits',
'/degree-awards': 'degree-awards',
'/graduation-clearance': 'graduation-clearance',
}
const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const plugins = usePluginStore()
const mobileMenu = ref(false)
const favoritesDialog = ref(false)
const savingFavorites = ref(false)
const draftFavoriteIds = ref<string[]>([])
const draggedFavoriteId = ref('')
const favoriteLimit = 12
const roles = computed(() => auth.user?.roles ?? [])
const isStudent = computed(() => roles.value.includes('Student'))
@@ -71,7 +140,12 @@ function isNavigationItemEnabled(item: NavigationItem) {
return !owner || owner.isEnabled
}
const navigationGroups = computed<NavigationGroup[]>(() => [
function navigationItemId(item: NavigationItem) {
return item.id ?? stableNavigationIds[item.path]
?? item.path.replace(/^\//, '').replaceAll('/', '.')
}
const availableNavigationGroups = computed<NavigationGroup[]>(() => [
{
key: 'overview',
label: '教务总览',
@@ -342,12 +416,55 @@ const navigationGroups = computed<NavigationGroup[]>(() => [
}))
.filter((group) => group.items.length > 0))
const allNavigationItems = computed(() =>
availableNavigationGroups.value.flatMap((group) => group.items),
)
const defaultFavoriteIds = computed(() => {
if (isStudent.value) return ['my-timetable', 'grades', 'exams', 'approvals']
if (isTeacher.value) return ['my-timetable', 'teacher-attendance', 'grades', 'exams']
if (isTeachingAdmin.value) return ['dashboard', 'teaching-tasks', 'schedules', 'grades']
return ['dashboard', 'notifications']
})
const configuredFavoriteIds = computed(() => {
const preference = auth.user?.navigationPreference
return preference?.isCustomized
? preference.favoriteItemIds
: defaultFavoriteIds.value
})
const favoriteItems = computed(() => {
const byId = new Map(
allNavigationItems.value.map((item) => [navigationItemId(item), item]),
)
return configuredFavoriteIds.value
.map((id) => byId.get(id))
.filter((item): item is NavigationItem => Boolean(item))
})
const navigationGroups = computed<NavigationGroup[]>(() => [
...(favoriteItems.value.length
? [{ key: 'favorites', label: '常用', items: favoriteItems.value }]
: []),
...availableNavigationGroups.value,
])
const activeGroupKey = computed(
() => navigationGroups.value.find((group) =>
() => availableNavigationGroups.value.find((group) =>
group.items.some((item) => item.path === route.path),
)?.key ?? '',
)
const currentNavigationItem = computed(() =>
allNavigationItems.value.find((item) => item.path === route.path),
)
const isCurrentFavorite = computed(() => {
const item = currentNavigationItem.value
return Boolean(item && configuredFavoriteIds.value.includes(navigationItemId(item)))
})
const workspaceLabel = computed(() => {
if (roles.value.includes('SuperAdmin')) return '系统全域管理'
if (roles.value.includes('AcademicAdmin')) return '校级教务管理'
@@ -373,6 +490,97 @@ function signOut() {
router.push('/login')
}
function handleNavigationSelect(index: string) {
const path = index.startsWith('favorite:') ? index.slice('favorite:'.length) : index
mobileMenu.value = false
if (path !== route.path) router.push(path)
}
function openFavoritesDialog() {
draftFavoriteIds.value = favoriteItems.value.map(navigationItemId)
favoritesDialog.value = true
}
function toggleDraftFavorite(item: NavigationItem) {
const id = navigationItemId(item)
const index = draftFavoriteIds.value.indexOf(id)
if (index >= 0) {
draftFavoriteIds.value.splice(index, 1)
return
}
if (draftFavoriteIds.value.length >= favoriteLimit) {
ElMessage.warning(`常用功能最多添加 ${favoriteLimit} 项。`)
return
}
draftFavoriteIds.value.push(id)
}
function moveDraftFavorite(id: string, offset: number) {
const index = draftFavoriteIds.value.indexOf(id)
const target = index + offset
if (index < 0 || target < 0 || target >= draftFavoriteIds.value.length) return
const next = [...draftFavoriteIds.value]
;[next[index], next[target]] = [next[target], next[index]]
draftFavoriteIds.value = next
}
function dropDraftFavorite(targetId: string) {
const sourceId = draggedFavoriteId.value
draggedFavoriteId.value = ''
if (!sourceId || sourceId === targetId) return
const next = [...draftFavoriteIds.value]
const sourceIndex = next.indexOf(sourceId)
const targetIndex = next.indexOf(targetId)
if (sourceIndex < 0 || targetIndex < 0) return
next.splice(sourceIndex, 1)
next.splice(targetIndex, 0, sourceId)
draftFavoriteIds.value = next
}
async function saveFavorites(ids = draftFavoriteIds.value, closeDialog = true) {
savingFavorites.value = true
try {
await auth.updateNavigationPreference(ids)
if (closeDialog) favoritesDialog.value = false
ElMessage.success('常用功能已保存。')
} catch (error) {
ElMessage.error(apiErrorMessage(error))
} finally {
savingFavorites.value = false
}
}
async function toggleCurrentFavorite() {
const item = currentNavigationItem.value
if (!item || savingFavorites.value) return
const id = navigationItemId(item)
const next = favoriteItems.value.map(navigationItemId)
const index = next.indexOf(id)
if (index >= 0) next.splice(index, 1)
else {
if (next.length >= favoriteLimit) {
ElMessage.warning(`常用功能最多添加 ${favoriteLimit} 项。`)
return
}
next.push(id)
}
await saveFavorites(next, false)
}
async function resetFavorites() {
savingFavorites.value = true
try {
await auth.resetNavigationPreference()
draftFavoriteIds.value = favoriteItems.value.map(navigationItemId)
favoritesDialog.value = false
ElMessage.success('已恢复当前角色的默认常用功能。')
} catch (error) {
ElMessage.error(apiErrorMessage(error))
} finally {
savingFavorites.value = false
}
}
onMounted(() => {
auth.refresh().catch(() => undefined)
plugins.load().catch(() => undefined)
@@ -406,7 +614,21 @@ onMounted(() => {
<div class="workspace-context">
<span>{{ workspaceLabel }}</span>
<b>{{ pageTitle }}</b>
<div class="page-title-row">
<b>{{ pageTitle }}</b>
<button
v-if="currentNavigationItem"
type="button"
class="favorite-page-button"
:class="{ 'is-favorite': isCurrentFavorite }"
:title="isCurrentFavorite ? '从常用中移除' : '添加到常用'"
:aria-label="isCurrentFavorite ? '从常用中移除' : '添加到常用'"
:disabled="savingFavorites"
@click="toggleCurrentFavorite"
>
{{ isCurrentFavorite ? '★' : '☆' }}
</button>
</div>
</div>
<div class="user-block">
@@ -418,6 +640,7 @@ onMounted(() => {
<b>{{ auth.user?.displayName ?? '系统管理员' }}</b>
<span>{{ auth.user?.roles?.[0] ?? '教务人员' }}</span>
</div>
<el-button class="desktop-account-action" text @click="openFavoritesDialog">管理常用</el-button>
<el-button class="desktop-account-action" text @click="router.push('/account')">个人账户</el-button>
<el-button class="desktop-account-action" text @click="signOut">退出</el-button>
</div>
@@ -425,13 +648,13 @@ onMounted(() => {
<nav class="desktop-navigation desktop-only" aria-label="主导航">
<el-menu
router
mode="horizontal"
menu-trigger="hover"
unique-opened
:default-active="route.path"
:ellipsis="false"
class="horizontal-menu"
@select="handleNavigationSelect"
>
<template v-for="group in navigationGroups" :key="group.key">
<el-menu-item v-if="group.direct" :index="group.items[0].path">
@@ -447,7 +670,7 @@ onMounted(() => {
<el-menu-item
v-for="item in group.items"
:key="item.path"
:index="item.path"
:index="group.key === 'favorites' ? `favorite:${item.path}` : item.path"
>
{{ item.label }}
</el-menu-item>
@@ -477,12 +700,11 @@ onMounted(() => {
</div>
<el-menu
router
:default-active="route.path"
:default-openeds="activeGroupKey ? [activeGroupKey] : []"
unique-opened
class="mobile-nav-menu"
@select="mobileMenu = false"
@select="handleNavigationSelect"
>
<template v-for="group in navigationGroups" :key="group.key">
<el-menu-item v-if="group.direct" :index="group.items[0].path">
@@ -493,7 +715,7 @@ onMounted(() => {
<el-menu-item
v-for="item in group.items"
:key="item.path"
:index="item.path"
:index="group.key === 'favorites' ? `favorite:${item.path}` : item.path"
>
{{ item.label }}
</el-menu-item>
@@ -502,6 +724,10 @@ onMounted(() => {
</el-menu>
<div class="mobile-account-actions">
<button type="button" @click="openFavoritesDialog(); mobileMenu = false">
<span>管理常用</span>
<small>收藏与调整常用功能顺序</small>
</button>
<button type="button" @click="router.push('/account'); mobileMenu = false">
<span>个人账户</span>
<small>{{ auth.user?.displayName ?? '当前用户' }}</small>
@@ -520,5 +746,104 @@ onMounted(() => {
<RouterView />
</section>
</main>
<el-dialog
v-model="favoritesDialog"
title="管理常用功能"
width="min(880px, calc(100vw - 24px))"
class="favorites-dialog"
:close-on-click-modal="!savingFavorites"
:close-on-press-escape="!savingFavorites"
>
<p class="favorites-intro">
最多添加 {{ favoriteLimit }} 项。左侧可拖动排序,右侧选择你有权限使用的功能。
</p>
<div class="favorites-editor">
<section class="selected-favorites" aria-label="已选择的常用功能">
<header>
<b>已选择</b>
<span>{{ draftFavoriteIds.length }}/{{ favoriteLimit }}</span>
</header>
<div v-if="!draftFavoriteIds.length" class="favorites-empty">
暂未添加常用功能,可以从右侧选择。
</div>
<div
v-for="(id, index) in draftFavoriteIds"
:key="id"
class="favorite-sort-row"
draggable="true"
@dragstart="draggedFavoriteId = id"
@dragend="draggedFavoriteId = ''"
@dragover.prevent
@drop.prevent="dropDraftFavorite(id)"
>
<span class="drag-handle" aria-hidden="true">⋮⋮</span>
<span>{{ allNavigationItems.find(item => navigationItemId(item) === id)?.label ?? id }}</span>
<div class="favorite-row-actions">
<button type="button" :disabled="index === 0" aria-label="上移" @click="moveDraftFavorite(id, -1)">↑</button>
<button type="button" :disabled="index === draftFavoriteIds.length - 1" aria-label="下移" @click="moveDraftFavorite(id, 1)">↓</button>
<button type="button" aria-label="移除" @click="draftFavoriteIds.splice(index, 1)">×</button>
</div>
</div>
</section>
<section class="available-favorites" aria-label="可添加的功能">
<header><b>全部可用功能</b><span>按业务分组</span></header>
<div v-for="group in availableNavigationGroups" :key="group.key" class="favorite-option-group">
<strong>{{ group.label }}</strong>
<div>
<button
v-for="item in group.items"
:key="navigationItemId(item)"
type="button"
class="favorite-option"
:class="{ 'is-selected': draftFavoriteIds.includes(navigationItemId(item)) }"
@click="toggleDraftFavorite(item)"
>
<span>{{ draftFavoriteIds.includes(navigationItemId(item)) ? '★' : '☆' }}</span>
{{ item.label }}
</button>
</div>
</div>
</section>
</div>
<template #footer>
<el-button :disabled="savingFavorites" @click="resetFavorites">恢复角色默认</el-button>
<el-button :disabled="savingFavorites" @click="favoritesDialog = false">取消</el-button>
<el-button type="primary" :loading="savingFavorites" @click="saveFavorites()">保存常用</el-button>
</template>
</el-dialog>
</div>
</template>
<style scoped>
.page-title-row { display: flex; align-items: center; gap: 7px; }
.favorite-page-button { border: 0; background: transparent; color: rgba(255, 255, 255, .7); cursor: pointer; font-size: 19px; line-height: 1; padding: 2px; }
.favorite-page-button:hover, .favorite-page-button.is-favorite { color: #ffd36a; }
.favorite-page-button:disabled { cursor: wait; opacity: .55; }
.favorites-intro { margin: -4px 0 16px; color: #64748b; font-size: 13px; }
.favorites-editor { display: grid; grid-template-columns: minmax(260px, .85fr) minmax(360px, 1.35fr); gap: 18px; min-height: 390px; }
.selected-favorites, .available-favorites { border: 1px solid #dfe6ee; border-radius: 12px; padding: 14px; min-width: 0; }
.selected-favorites > header, .available-favorites > header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.selected-favorites > header span, .available-favorites > header span { color: #8492a6; font-size: 12px; }
.favorites-empty { border: 1px dashed #ccd6e0; border-radius: 9px; color: #8492a6; padding: 28px 14px; text-align: center; }
.favorite-sort-row { align-items: center; background: #f7f9fc; border: 1px solid transparent; border-radius: 8px; cursor: grab; display: grid; gap: 8px; grid-template-columns: 20px 1fr auto; margin-bottom: 7px; padding: 8px 9px; }
.favorite-sort-row:hover { border-color: #a8b9d8; }
.drag-handle { color: #8a99aa; letter-spacing: -3px; }
.favorite-row-actions { display: flex; gap: 3px; }
.favorite-row-actions button { background: white; border: 1px solid #d6dee8; border-radius: 5px; cursor: pointer; height: 25px; min-width: 25px; }
.favorite-row-actions button:disabled { cursor: default; opacity: .35; }
.favorite-option-group { border-top: 1px solid #edf0f4; padding: 11px 0; }
.favorite-option-group:first-of-type { border-top: 0; padding-top: 0; }
.favorite-option-group > strong { color: #526174; display: block; font-size: 12px; margin-bottom: 7px; }
.favorite-option-group > div { display: flex; flex-wrap: wrap; gap: 6px; }
.favorite-option { background: #f7f9fc; border: 1px solid #dfe6ee; border-radius: 999px; color: #344054; cursor: pointer; padding: 6px 10px; }
.favorite-option span { color: #9aa6b2; margin-right: 3px; }
.favorite-option.is-selected { background: #edf4ff; border-color: #8fb2e8; color: #234b86; }
.favorite-option.is-selected span { color: #e5a629; }
.available-favorites { max-height: 520px; overflow-y: auto; }
@media (max-width: 720px) {
.favorites-editor { grid-template-columns: 1fr; }
.available-favorites { max-height: none; }
}
</style>
+32
View File
@@ -19,6 +19,13 @@ export interface CurrentUser {
roles: string[]
collegeId?: string
effectiveDataScope: 'Self' | 'Class' | 'College' | 'All'
navigationPreference?: NavigationPreference
}
export interface NavigationPreference {
schemaVersion: number
isCustomized: boolean
favoriteItemIds: string[]
}
export const useAuthStore = defineStore('auth', () => {
@@ -88,6 +95,29 @@ export const useAuthStore = defineStore('auth', () => {
localStorage.setItem(authStorageKeys.user, JSON.stringify(data))
}
async function updateNavigationPreference(favoriteItemIds: string[]) {
const { data } = await http.put<NavigationPreference>(
'/account/navigation-preference',
{ favoriteItemIds },
)
if (user.value) {
user.value = { ...user.value, navigationPreference: data }
localStorage.setItem(authStorageKeys.user, JSON.stringify(user.value))
}
return data
}
async function resetNavigationPreference() {
const { data } = await http.delete<NavigationPreference>(
'/account/navigation-preference',
)
if (user.value) {
user.value = { ...user.value, navigationPreference: data }
localStorage.setItem(authStorageKeys.user, JSON.stringify(user.value))
}
return data
}
function logout() {
const refreshToken = localStorage.getItem(authStorageKeys.refreshToken)
if (refreshToken) void http.post('/auth/logout', { refreshToken }).catch(() => undefined)
@@ -112,6 +142,8 @@ export const useAuthStore = defineStore('auth', () => {
exchangeSso,
bindSso,
refresh,
updateNavigationPreference,
resetNavigationPreference,
logout,
}
})