useService.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { useCallback, useMemo } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { matchPath, useLocation } from 'react-router-dom';
  4. import { getNavMenuItems, type NavMenuItem } from '@/utils/navUtils';
  5. /**
  6. * Topbar 业务逻辑 Hook
  7. * 处理菜单项获取、路由匹配、翻译等业务逻辑
  8. */
  9. export function useService() {
  10. const { t } = useTranslation();
  11. const location = useLocation();
  12. const menuItems = useMemo(() => getNavMenuItems(), []);
  13. const isActive = useCallback(
  14. (path: string): boolean => {
  15. return matchPath({ path, end: false }, location.pathname) !== null;
  16. },
  17. [location.pathname]
  18. );
  19. const getMenuItemLabel = useCallback(
  20. (item: NavMenuItem): string => {
  21. // getNavMenuItems 中已经设置了 locale,item.locale 总是存在
  22. return t(item.locale!, { defaultValue: item.name });
  23. },
  24. [t]
  25. );
  26. return {
  27. menuItems,
  28. isActive,
  29. getMenuItemLabel,
  30. };
  31. }