SiderMenu.js 6.46 KB
Newer Older
jiang's avatar
jiang committed
1 2
import React, { PureComponent } from 'react';
import { Layout, Menu, Icon } from 'antd';
陈帅's avatar
陈帅 committed
3
import pathToRegexp from 'path-to-regexp';
jiang's avatar
jiang committed
4 5
import { Link } from 'dva/router';
import styles from './index.less';
jim's avatar
jim committed
6
import { urlToList } from '../_utils/pathTools';
jiang's avatar
jiang committed
7 8 9 10

const { Sider } = Layout;
const { SubMenu } = Menu;

11 12 13 14
// 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
15
const getIcon = icon => {
16
  if (typeof icon === 'string' && icon.indexOf('http') === 0) {
17
    return <img src={icon} alt="icon" className={`${styles.icon} sider-menu-item-img`} />;
18 19 20 21 22 23 24
  }
  if (typeof icon === 'string') {
    return <Icon type={icon} />;
  }
  return icon;
};

25 26 27 28 29 30
/**
 * Recursively flatten the data
 * [{path:string},{path:string}] => {path,path2}
 * @param  menu
 */
export const getFlatMenuKeys = menu =>
陈帅's avatar
陈帅 committed
31 32 33 34 35 36 37
  menu.reduce((keys, item) => {
    keys.push(item.path);
    if (item.children) {
      return keys.concat(getFlatMenuKeys(item.children));
    }
    return keys;
  }, []);
38 39 40 41 42 43

/**
 * Find all matched menu keys based on paths
 * @param  flatMenuKeys: [/abc, /abc/:id, /abc/:id/info]
 * @param  paths: [/abc, /abc/11, /abc/11/info]
 */
此去's avatar
此去 committed
44
export const getMenuMatchKeys = (flatMenuKeys, paths) =>
陈帅's avatar
陈帅 committed
45 46 47 48 49
  paths.reduce(
    (matchKeys, path) =>
      matchKeys.concat(flatMenuKeys.filter(item => pathToRegexp(item).test(path))),
    []
  );
50

jiang's avatar
jiang committed
51 52 53
export default class SiderMenu extends PureComponent {
  constructor(props) {
    super(props);
54
    this.flatMenuKeys = getFlatMenuKeys(props.menuData);
jiang's avatar
jiang committed
55 56 57 58
    this.state = {
      openKeys: this.getDefaultCollapsedSubMenus(props),
    };
  }
陈帅's avatar
陈帅 committed
59

60
  componentWillReceiveProps(nextProps) {
61 62
    const { location } = this.props;
    if (nextProps.location.pathname !== location.pathname) {
63 64 65 66 67
      this.setState({
        openKeys: this.getDefaultCollapsedSubMenus(nextProps),
      });
    }
  }
陈帅's avatar
陈帅 committed
68

陈帅's avatar
陈帅 committed
69 70 71 72 73
  /**
   * Convert pathname to openKeys
   * /list/search/articles = > ['list','/list/search']
   * @param  props
   */
jiang's avatar
jiang committed
74
  getDefaultCollapsedSubMenus(props) {
陈帅's avatar
陈帅 committed
75 76 77 78
    const {
      location: { pathname },
    } =
      props || this.props;
此去's avatar
此去 committed
79
    return getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
jiang's avatar
jiang committed
80
  }
陈帅's avatar
陈帅 committed
81

陈帅's avatar
陈帅 committed
82
  /**
83 84 85
   * 判断是否是http链接.返回 Link 或 a
   * Judge whether it is http link.return a or Link
   * @memberof SiderMenu
陈帅's avatar
陈帅 committed
86
   */
jim's avatar
jim committed
87
  getMenuItemPath = item => {
ddcat1115's avatar
ddcat1115 committed
88 89 90 91 92 93 94
    const itemPath = this.conversionPath(item.path);
    const icon = getIcon(item.icon);
    const { target, name } = item;
    // Is it a http link
    if (/^https?:\/\//.test(itemPath)) {
      return (
        <a href={itemPath} target={target}>
95 96
          {icon}
          <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
97 98 99
        </a>
      );
    }
100
    const { location, isMobile, onCollapse } = this.props;
ddcat1115's avatar
ddcat1115 committed
101 102 103 104
    return (
      <Link
        to={itemPath}
        target={target}
105
        replace={itemPath === location.pathname}
106
        onClick={
107
          isMobile
108
            ? () => {
109
                onCollapse(true);
110 111 112
              }
            : undefined
        }
ddcat1115's avatar
ddcat1115 committed
113
      >
114 115
        {icon}
        <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
116 117
      </Link>
    );
118
  };
陈帅's avatar
陈帅 committed
119

ddcat1115's avatar
ddcat1115 committed
120 121 122
  /**
   * get SubMenu or Item
   */
jim's avatar
jim committed
123
  getSubMenuOrItem = item => {
ddcat1115's avatar
ddcat1115 committed
124
    if (item.children && item.children.some(child => child.name)) {
hzq's avatar
hzq committed
125 126 127 128 129 130 131 132 133 134 135 136
      const childrenItems = this.getNavMenuItems(item.children);
      // 当无子菜单时就不展示菜单
      if (childrenItems && childrenItems.length > 0) {
        return (
          <SubMenu
            title={
              item.icon ? (
                <span>
                  {getIcon(item.icon)}
                  <span>{item.name}</span>
                </span>
              ) : (
jim's avatar
jim committed
137 138
                item.name
              )
hzq's avatar
hzq committed
139 140 141 142 143
            }
            key={item.path}
          >
            {childrenItems}
          </SubMenu>
hzq's avatar
hzq committed
144
        );
hzq's avatar
hzq committed
145
      }
hzq's avatar
hzq committed
146
      return null;
ddcat1115's avatar
ddcat1115 committed
147
    } else {
jim's avatar
jim committed
148
      return <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>;
ddcat1115's avatar
ddcat1115 committed
149
    }
150
  };
陈帅's avatar
陈帅 committed
151

ddcat1115's avatar
ddcat1115 committed
152
  /**
153 154 155
   * 获得菜单子节点
   * @memberof SiderMenu
   */
jim's avatar
jim committed
156
  getNavMenuItems = menusData => {
jiang's avatar
jiang committed
157 158 159
    if (!menusData) {
      return [];
    }
陈帅's avatar
陈帅 committed
160 161
    return menusData
      .filter(item => item.name && !item.hideInMenu)
jim's avatar
jim committed
162
      .map(item => {
163
        // make dom
陈帅's avatar
陈帅 committed
164 165 166
        const ItemDom = this.getSubMenuOrItem(item);
        return this.checkPermissionItem(item.authority, ItemDom);
      })
167 168
      .filter(item => item);
  };
陈帅's avatar
陈帅 committed
169

170 171
  // Get the currently selected menu
  getSelectedMenuKeys = () => {
陈帅's avatar
陈帅 committed
172 173 174
    const {
      location: { pathname },
    } = this.props;
此去's avatar
此去 committed
175
    return getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
176
  };
陈帅's avatar
陈帅 committed
177

ddcat1115's avatar
ddcat1115 committed
178 179
  // conversion Path
  // 转化路径
jim's avatar
jim committed
180
  conversionPath = path => {
ddcat1115's avatar
ddcat1115 committed
181 182 183 184 185
    if (path && path.indexOf('http') === 0) {
      return path;
    } else {
      return `/${path || ''}`.replace(/\/+/g, '/');
    }
186
  };
陈帅's avatar
陈帅 committed
187

ddcat1115's avatar
ddcat1115 committed
188 189
  // permission to check
  checkPermissionItem = (authority, ItemDom) => {
190 191 192
    const { Authorized } = this.props;
    if (Authorized && Authorized.check) {
      const { check } = Authorized;
193
      return check(authority, ItemDom);
ddcat1115's avatar
ddcat1115 committed
194 195
    }
    return ItemDom;
196
  };
陈帅's avatar
陈帅 committed
197

jim's avatar
jim committed
198
  isMainMenu = key => {
199
    return this.props.menuData.some(item => key && (item.key === key || item.path === key));
jim's avatar
jim committed
200
  };
陈帅's avatar
陈帅 committed
201

jim's avatar
jim committed
202
  handleOpenChange = openKeys => {
ddcat1115's avatar
ddcat1115 committed
203 204
    const lastOpenKey = openKeys[openKeys.length - 1];
    const moreThanOne = openKeys.filter(openKey => this.isMainMenu(openKey)).length > 1;
jiang's avatar
jiang committed
205
    this.setState({
ddcat1115's avatar
ddcat1115 committed
206
      openKeys: moreThanOne ? [lastOpenKey] : [...openKeys],
jiang's avatar
jiang committed
207
    });
208
  };
陈帅's avatar
陈帅 committed
209

jiang's avatar
jiang committed
210
  render() {
211
    const { logo, collapsed, onCollapse } = this.props;
212
    const { openKeys } = this.state;
jiang's avatar
jiang committed
213
    // Don't show popup menu when it is been collapsed
214 215 216
    const menuProps = collapsed
      ? {}
      : {
jim's avatar
jim committed
217 218
          openKeys,
        };
219
    // if pathname can't match, use the nearest parent's key
220
    let selectedKeys = this.getSelectedMenuKeys();
221 222 223
    if (!selectedKeys.length) {
      selectedKeys = [openKeys[openKeys.length - 1]];
    }
jiang's avatar
jiang committed
224 225 226 227 228
    return (
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
229
        breakpoint="lg"
jiang's avatar
jiang committed
230 231 232 233
        onCollapse={onCollapse}
        width={256}
        className={styles.sider}
      >
陈帅's avatar
陈帅 committed
234
        <div className={styles.logo} key="logo">
jiang's avatar
jiang committed
235 236 237 238 239 240
          <Link to="/">
            <img src={logo} alt="logo" />
            <h1>Ant Design Pro</h1>
          </Link>
        </div>
        <Menu
陈帅's avatar
陈帅 committed
241
          key="Menu"
jiang's avatar
jiang committed
242 243 244 245
          theme="dark"
          mode="inline"
          {...menuProps}
          onOpenChange={this.handleOpenChange}
246
          selectedKeys={selectedKeys}
jiang's avatar
jiang committed
247 248
          style={{ padding: '16px 0', width: '100%' }}
        >
249
          {this.getNavMenuItems(this.props.menuData)}
jiang's avatar
jiang committed
250 251 252 253 254
        </Menu>
      </Sider>
    );
  }
}