getPageTitle.ts 1.1 KB
Newer Older
Yu's avatar
Yu committed
1 2
import isEqual from 'lodash/isEqual';
import memoizeOne from 'memoize-one';
3 4 5
import pathToRegexp from 'path-to-regexp';
import { formatMessage } from 'umi-plugin-locale';
import defaultSettings from '../../config/defaultSettings';
何乐's avatar
何乐 committed
6
import { MenuDataItem } from '@/components/SiderMenu/BaseMenu';
7 8 9

const { menu, title } = defaultSettings;

何乐's avatar
何乐 committed
10 11 12 13
export const matchParamsPath = (
  pathname: string,
  breadcrumbNameMap: { [path: string]: MenuDataItem },
): MenuDataItem => {
Yu's avatar
Yu committed
14
  const pathKey = Object.keys(breadcrumbNameMap).find(key => pathToRegexp(key).test(pathname));
何乐's avatar
何乐 committed
15
  return breadcrumbNameMap[pathKey!];
Yu's avatar
Yu committed
16 17
};

何乐's avatar
何乐 committed
18 19 20 21
const getPageTitle = (
  pathname: string,
  breadcrumbNameMap: { [path: string]: MenuDataItem },
): string => {
Yu's avatar
Yu committed
22 23 24 25 26 27 28
  const currRouterData = matchParamsPath(pathname, breadcrumbNameMap);
  if (!currRouterData) {
    return title;
  }
  const pageName = menu.disableLocal
    ? currRouterData.name
    : formatMessage({
何乐's avatar
何乐 committed
29
        id: currRouterData.locale || currRouterData.name!,
Yu's avatar
Yu committed
30 31 32 33 34 35 36
        defaultMessage: currRouterData.name,
      });

  return `${pageName} - ${title}`;
};

export default memoizeOne(getPageTitle, isEqual);