BaseMenu.js 4.99 KB
Newer Older
jim's avatar
jim committed
1 2
import React, { PureComponent } from 'react';
import { Menu, Icon } from 'antd';
zinkey's avatar
zinkey committed
3
import Link from 'umi/link';
陈帅's avatar
陈帅 committed
4 5
import isEqual from 'lodash/isEqual';
import memoizeOne from 'memoize-one';
陈帅's avatar
陈帅 committed
6
import { formatMessage } from 'umi/locale';
jim's avatar
jim committed
7
import pathToRegexp from 'path-to-regexp';
jim's avatar
jim committed
8
import { urlToList } from '../_utils/pathTools';
jim's avatar
jim committed
9 10 11 12 13 14 15 16
import styles from './index.less';

const { SubMenu } = Menu;

// Allow menu.js config icon as string or ReactNode
//   icon: 'setting',
//   icon: 'http://demo.com/icon.png',
//   icon: <Icon type="setting" />,
jim's avatar
jim committed
17
const getIcon = icon => {
jim's avatar
jim committed
18 19 20 21 22 23 24 25 26
  if (typeof icon === 'string' && icon.indexOf('http') === 0) {
    return <img src={icon} alt="icon" className={styles.icon} />;
  }
  if (typeof icon === 'string') {
    return <Icon type={icon} />;
  }
  return icon;
};

27 28 29 30 31 32 33
export const getMenuMatches = (flatMenuKeys, path) =>
  flatMenuKeys.filter(item => {
    if (item) {
      return pathToRegexp(item).test(path);
    }
    return false;
  });
jim's avatar
jim committed
34

Erwin Zhang's avatar
Erwin Zhang committed
35
export default class BaseMenu extends PureComponent {
jim's avatar
jim committed
36 37
  constructor(props) {
    super(props);
陈帅's avatar
陈帅 committed
38
    this.getSelectedMenuKeys = memoizeOne(this.getSelectedMenuKeys, isEqual);
jim's avatar
jim committed
39 40
    this.flatMenuKeys = this.getFlatMenuKeys(props.menuData);
  }
陈帅's avatar
陈帅 committed
41

jim's avatar
jim committed
42 43 44 45 46 47 48
  /**
   * Recursively flatten the data
   * [{path:string},{path:string}] => {path,path2}
   * @param  menus
   */
  getFlatMenuKeys(menus) {
    let keys = [];
jim's avatar
jim committed
49
    menus.forEach(item => {
jim's avatar
jim committed
50 51 52 53 54 55 56
      if (item.children) {
        keys = keys.concat(this.getFlatMenuKeys(item.children));
      }
      keys.push(item.path);
    });
    return keys;
  }
陈帅's avatar
陈帅 committed
57

jim's avatar
jim committed
58 59 60 61
  /**
   * 获得菜单子节点
   * @memberof SiderMenu
   */
陈帅's avatar
陈帅 committed
62
  getNavMenuItems = (menusData, parent) => {
jim's avatar
jim committed
63 64 65 66 67
    if (!menusData) {
      return [];
    }
    return menusData
      .filter(item => item.name && !item.hideInMenu)
jim's avatar
jim committed
68
      .map(item => {
jim's avatar
jim committed
69
        // make dom
陈帅's avatar
陈帅 committed
70
        const ItemDom = this.getSubMenuOrItem(item, parent);
jim's avatar
jim committed
71 72 73 74
        return this.checkPermissionItem(item.authority, ItemDom);
      })
      .filter(item => item);
  };
陈帅's avatar
陈帅 committed
75

jim's avatar
jim committed
76
  // Get the currently selected menu
陈帅's avatar
陈帅 committed
77
  getSelectedMenuKeys = pathname =>
陈帅's avatar
陈帅 committed
78
    urlToList(pathname).map(itemPath => getMenuMatches(this.flatMenuKeys, itemPath).pop());
陈帅's avatar
陈帅 committed
79

jim's avatar
jim committed
80 81 82
  /**
   * get SubMenu or Item
   */
陈帅's avatar
陈帅 committed
83
  getSubMenuOrItem = item => {
afc163's avatar
afc163 committed
84 85
    // doc: add hideChildrenInMenu
    if (item.children && !item.hideChildrenInMenu && item.children.some(child => child.name)) {
陈帅's avatar
陈帅 committed
86
      const name = item.locale ? formatMessage({ id: item.locale }) : item.name;
jim's avatar
jim committed
87 88 89 90 91 92
      return (
        <SubMenu
          title={
            item.icon ? (
              <span>
                {getIcon(item.icon)}
陈帅's avatar
陈帅 committed
93
                <span>{name}</span>
jim's avatar
jim committed
94 95
              </span>
            ) : (
陈帅's avatar
陈帅 committed
96
              name
jim's avatar
jim committed
97 98 99 100
            )
          }
          key={item.path}
        >
陈帅's avatar
陈帅 committed
101
          {this.getNavMenuItems(item.children)}
jim's avatar
jim committed
102 103 104
        </SubMenu>
      );
    }
105
    return <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>;
jim's avatar
jim committed
106
  };
陈帅's avatar
陈帅 committed
107

jim's avatar
jim committed
108 109 110 111 112
  /**
   * 判断是否是http链接.返回 Link 或 a
   * Judge whether it is http link.return a or Link
   * @memberof SiderMenu
   */
陈帅's avatar
陈帅 committed
113
  getMenuItemPath = item => {
陈帅's avatar
陈帅 committed
114
    const name = item.locale ? formatMessage({ id: item.locale }) : item.name;
jim's avatar
jim committed
115 116
    const itemPath = this.conversionPath(item.path);
    const icon = getIcon(item.icon);
陈帅's avatar
陈帅 committed
117
    const { target } = item;
jim's avatar
jim committed
118 119 120 121 122 123 124 125 126
    // Is it a http link
    if (/^https?:\/\//.test(itemPath)) {
      return (
        <a href={itemPath} target={target}>
          {icon}
          <span>{name}</span>
        </a>
      );
    }
陈帅's avatar
陈帅 committed
127
    const { location, isMobile, onCollapse } = this.props;
jim's avatar
jim committed
128 129 130 131
    return (
      <Link
        to={itemPath}
        target={target}
陈帅's avatar
陈帅 committed
132
        replace={itemPath === location.pathname}
jim's avatar
jim committed
133
        onClick={
陈帅's avatar
陈帅 committed
134
          isMobile
jim's avatar
jim committed
135
            ? () => {
陈帅's avatar
陈帅 committed
136
                onCollapse(true);
jim's avatar
jim committed
137 138 139 140 141 142 143 144 145
              }
            : undefined
        }
      >
        {icon}
        <span>{name}</span>
      </Link>
    );
  };
146

jim's avatar
jim committed
147 148
  // permission to check
  checkPermissionItem = (authority, ItemDom) => {
陈帅's avatar
陈帅 committed
149 150 151
    const { Authorized } = this.props;
    if (Authorized && Authorized.check) {
      const { check } = Authorized;
jim's avatar
jim committed
152 153 154 155
      return check(authority, ItemDom);
    }
    return ItemDom;
  };
陈帅's avatar
陈帅 committed
156

jim's avatar
jim committed
157
  conversionPath = path => {
jim's avatar
jim committed
158 159 160
    if (path && path.indexOf('http') === 0) {
      return path;
    }
161
    return `/${path || ''}`.replace(/\/+/g, '/');
jim's avatar
jim committed
162
  };
陈帅's avatar
陈帅 committed
163

jim's avatar
jim committed
164
  render() {
陈帅's avatar
陈帅 committed
165 166 167 168 169 170
    const {
      openKeys,
      theme,
      mode,
      location: { pathname },
    } = this.props;
jim's avatar
jim committed
171
    // if pathname can't match, use the nearest parent's key
陈帅's avatar
陈帅 committed
172
    let selectedKeys = this.getSelectedMenuKeys(pathname);
jim's avatar
jim committed
173 174 175
    if (!selectedKeys.length && openKeys) {
      selectedKeys = [openKeys[openKeys.length - 1]];
    }
jim's avatar
jim committed
176 177 178 179 180 181
    let props = {};
    if (openKeys) {
      props = {
        openKeys,
      };
    }
陈帅's avatar
陈帅 committed
182
    const { handleOpenChange, style, menuData } = this.props;
jim's avatar
jim committed
183 184 185
    return (
      <Menu
        key="Menu"
jim's avatar
jim committed
186 187
        mode={mode}
        theme={theme}
陈帅's avatar
陈帅 committed
188
        onOpenChange={handleOpenChange}
jim's avatar
jim committed
189
        selectedKeys={selectedKeys}
陈帅's avatar
陈帅 committed
190
        style={style}
191
        className={mode === 'horizontal' ? 'top-nav-menu' : ''}
jim's avatar
jim committed
192
        {...props}
jim's avatar
jim committed
193
      >
陈帅's avatar
陈帅 committed
194
        {this.getNavMenuItems(menuData)}
jim's avatar
jim committed
195 196 197 198
      </Menu>
    );
  }
}