Files
aerbim-ht-monitor/frontend/services/navigationService.ts

91 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React from 'react'
import { useRouter } from 'next/navigation'
import useNavigationStore from '@/app/store/navigationStore'
import type { NavigationStore } from '@/app/store/navigationStore'
export enum MainRoutes {
DASHBOARD = '/dashboard',
NAVIGATION = '/navigation',
ALERTS = '/alerts',
REPORTS = '/reports',
OBJECTS = '/objects'
}
export const SIDEBAR_ITEM_MAP = {
1: { type: 'route', value: MainRoutes.DASHBOARD },
2: { type: 'route', value: MainRoutes.NAVIGATION },
8: { type: 'route', value: MainRoutes.ALERTS },
9: { type: 'route', value: MainRoutes.REPORTS }
} as const
export class NavigationService {
private router!: ReturnType<typeof useRouter>
private navigationStore!: NavigationStore
private initialized = false
init(router: ReturnType<typeof useRouter>, navigationStore: NavigationStore) {
if (this.initialized) {
return // Предотвращаем повторную инициализацию
}
this.router = router
this.navigationStore = navigationStore
this.initialized = true
}
isInitialized(): boolean {
return this.initialized
}
navigateToRoute(route: MainRoutes) {
// Убираем суб-меню перед переходом на другую страницу
if (route !== MainRoutes.NAVIGATION) {
this.navigationStore.setCurrentSubmenu(null)
}
this.router.push(route)
}
handleSidebarItemClick(itemId: number, currentPath: string): boolean {
if (!this.initialized) {
console.error('NavigationService not initialized!')
return false
}
const mapping = SIDEBAR_ITEM_MAP[itemId as keyof typeof SIDEBAR_ITEM_MAP]
if (!mapping) {
return false
}
if (mapping.type === 'route') {
this.navigateToRoute(mapping.value as MainRoutes)
return true
}
return false
}
goBack() {
this.navigationStore.goBack()
}
selectObjectAndGoToDashboard(objectId: string, objectTitle: string) {
this.navigationStore.setCurrentObject(objectId, objectTitle)
this.navigateToRoute(MainRoutes.DASHBOARD)
}
}
export const navigationService = new NavigationService()
export function useNavigationService() {
const router = useRouter()
const navigationStore = useNavigationStore()
React.useMemo(() => {
if (!navigationService.isInitialized()) {
navigationService.init(router, navigationStore)
}
}, [router, navigationStore])
return navigationService
}