SiderMenu.js 6.62 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
import { Link } from 'dva/router';
5
import classNames from 'classnames';
jiang's avatar
jiang committed
6
import styles from './index.less';
jim's avatar
jim committed
7
import { urlToList } from '../_utils/pathTools';
jiang's avatar
jiang committed
8 9 10 11

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

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

24 25 26
  return icon;
};

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

/**
 * 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
46
export const getMenuMatchKeys = (flatMenuKeys, paths) =>
陈帅's avatar
陈帅 committed
47 48 49 50 51
  paths.reduce(
    (matchKeys, path) =>
      matchKeys.concat(flatMenuKeys.filter(item => pathToRegexp(item).test(path))),
    []
  );
52

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

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

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

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

ddcat1115's avatar
ddcat1115 committed
121 122 123
  /**
   * get SubMenu or Item
   */
jim's avatar
jim committed
124
  getSubMenuOrItem = item => {
ddcat1115's avatar
ddcat1115 committed
125
    if (item.children && item.children.some(child => child.name)) {
hzq's avatar
hzq committed
126 127 128 129 130 131 132 133 134 135 136 137
      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
138 139
                item.name
              )
hzq's avatar
hzq committed
140 141 142 143 144
            }
            key={item.path}
          >
            {childrenItems}
          </SubMenu>
hzq's avatar
hzq committed
145
        );
hzq's avatar
hzq committed
146
      }
hzq's avatar
hzq committed
147
      return null;
ddcat1115's avatar
ddcat1115 committed
148
    } else {
jim's avatar
jim committed
149
      return <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>;
ddcat1115's avatar
ddcat1115 committed
150
    }
151
  };
陈帅's avatar
陈帅 committed
152

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

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

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

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

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

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

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