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 6 7 8 9 10 11 12 13 14 15 16
import pathToRegexp from 'path-to-regexp';
import { formatMessage } from 'umi-plugin-locale';
import defaultSettings from '../../config/defaultSettings';

const { menu, title } = defaultSettings;

interface RouterData {
  name: string;
  locale: string;
  authority?: string[];
  children?: any[];
  icon?: string;
  path: string;
}
Yu's avatar
Yu committed
17

18
export const matchParamsPath = (pathname: string, breadcrumbNameMap: object): RouterData => {
Yu's avatar
Yu committed
19 20 21 22
  const pathKey = Object.keys(breadcrumbNameMap).find(key => pathToRegexp(key).test(pathname));
  return breadcrumbNameMap[pathKey];
};

23
const getPageTitle = (pathname: string, breadcrumbNameMap: object): string => {
Yu's avatar
Yu committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
  const currRouterData = matchParamsPath(pathname, breadcrumbNameMap);
  if (!currRouterData) {
    return title;
  }
  const pageName = menu.disableLocal
    ? currRouterData.name
    : formatMessage({
        id: currRouterData.locale || currRouterData.name,
        defaultMessage: currRouterData.name,
      });

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

export default memoizeOne(getPageTitle, isEqual);