SiderMenu.js 6.08 KB
Newer Older
jiang's avatar
jiang committed
1 2
import React, { PureComponent } from 'react';
import { Layout, Menu, Icon } from 'antd';
3
import pathToRegexp from 'path-to-regexp';
jiang's avatar
jiang committed
4 5
import { Link } from 'dva/router';
import styles from './index.less';
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 15 16 17 18 19 20 21 22 23 24
// Allow menu.js config icon as string or ReactNode
//   icon: 'setting',
//   icon: 'http://demo.com/icon.png',
//   icon: <Icon type="setting" />,
const getIcon = (icon) => {
  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;
};

25 26 27 28 29 30
export const getMeunMatcheys = (flatMenuKeys, path) => {
  return flatMenuKeys.filter((item) => {
    return pathToRegexp(item).test(path);
  });
};

jiang's avatar
jiang committed
31 32 33
export default class SiderMenu extends PureComponent {
  constructor(props) {
    super(props);
ddcat1115's avatar
ddcat1115 committed
34
    this.menus = props.menuData;
35
    this.flatMenuKeys = this.getFlatMenuKeys(props.menuData);
jiang's avatar
jiang committed
36 37 38 39
    this.state = {
      openKeys: this.getDefaultCollapsedSubMenus(props),
    };
  }
40 41 42 43 44 45 46
  componentWillReceiveProps(nextProps) {
    if (nextProps.location.pathname !== this.props.location.pathname) {
      this.setState({
        openKeys: this.getDefaultCollapsedSubMenus(nextProps),
      });
    }
  }
47 48 49 50 51
  /**
   * Convert pathname to openKeys
   * /list/search/articles = > ['list','/list/search']
   * @param  props
   */
jiang's avatar
jiang committed
52 53
  getDefaultCollapsedSubMenus(props) {
    const { location: { pathname } } = props || this.props;
54 55 56 57 58
    return urlToList(pathname)
      .map((item) => {
        return getMeunMatcheys(this.flatMenuKeys, item)[0];
      })
      .filter(item => item);
jiang's avatar
jiang committed
59
  }
60 61 62 63 64
  /**
   * Recursively flatten the data
   * [{path:string},{path:string}] => {path,path2}
   * @param  menus
   */
jiang's avatar
jiang committed
65 66 67 68 69 70
  getFlatMenuKeys(menus) {
    let keys = [];
    menus.forEach((item) => {
      if (item.children) {
        keys = keys.concat(this.getFlatMenuKeys(item.children));
      }
71
      keys.push(item.path);
jiang's avatar
jiang committed
72 73 74
    });
    return keys;
  }
75
  /**
76 77 78
   * εˆ€ζ–­ζ˜―ε¦ζ˜―httpι“ΎζŽ₯.θΏ”ε›ž Link ζˆ– a
   * Judge whether it is http link.return a or Link
   * @memberof SiderMenu
79
   */
ddcat1115's avatar
ddcat1115 committed
80 81 82 83 84 85 86 87
  getMenuItemPath = (item) => {
    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}>
88 89
          {icon}
          <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
90 91 92 93 94 95 96 97
        </a>
      );
    }
    return (
      <Link
        to={itemPath}
        target={target}
        replace={itemPath === this.props.location.pathname}
98 99 100 101 102 103 104
        onClick={
          this.props.isMobile
            ? () => {
                this.props.onCollapse(true);
              }
            : undefined
        }
ddcat1115's avatar
ddcat1115 committed
105
      >
106 107
        {icon}
        <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
108 109
      </Link>
    );
110
  };
ddcat1115's avatar
ddcat1115 committed
111 112 113
  /**
   * get SubMenu or Item
   */
114
  getSubMenuOrItem = (item) => {
ddcat1115's avatar
ddcat1115 committed
115 116 117 118 119 120 121 122 123
    if (item.children && item.children.some(child => child.name)) {
      return (
        <SubMenu
          title={
            item.icon ? (
              <span>
                {getIcon(item.icon)}
                <span>{item.name}</span>
              </span>
124 125 126 127
            ) : (
              item.name
            )
          }
128
          key={item.path}
ddcat1115's avatar
ddcat1115 committed
129 130 131 132 133 134
        >
          {this.getNavMenuItems(item.children)}
        </SubMenu>
      );
    } else {
      return (
135
        <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>
ddcat1115's avatar
ddcat1115 committed
136 137
      );
    }
138
  };
ddcat1115's avatar
ddcat1115 committed
139
  /**
140 141 142
   * θŽ·εΎ—θœε•ε­θŠ‚η‚Ή
   * @memberof SiderMenu
   */
ddcat1115's avatar
ddcat1115 committed
143
  getNavMenuItems = (menusData) => {
jiang's avatar
jiang committed
144 145 146
    if (!menusData) {
      return [];
    }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
147 148 149
    return menusData
      .filter(item => item.name && !item.hideInMenu)
      .map((item) => {
150
        // make dom
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
151 152 153
        const ItemDom = this.getSubMenuOrItem(item);
        return this.checkPermissionItem(item.authority, ItemDom);
      })
154 155 156 157 158 159 160 161 162
      .filter(item => item);
  };
  // Get the currently selected menu
  getSelectedMenuKeys = () => {
    const { location: { pathname } } = this.props;
    return urlToList(pathname).map(itemPath =>
      getMeunMatcheys(this.flatMenuKeys, itemPath).pop(),
    );
  };
ddcat1115's avatar
ddcat1115 committed
163 164
  // conversion Path
  // θ½¬εŒ–θ·―εΎ„
165
  conversionPath = (path) => {
ddcat1115's avatar
ddcat1115 committed
166 167 168 169 170
    if (path && path.indexOf('http') === 0) {
      return path;
    } else {
      return `/${path || ''}`.replace(/\/+/g, '/');
    }
171
  };
ddcat1115's avatar
ddcat1115 committed
172 173 174 175
  // permission to check
  checkPermissionItem = (authority, ItemDom) => {
    if (this.props.Authorized && this.props.Authorized.check) {
      const { check } = this.props.Authorized;
176
      return check(authority, ItemDom);
ddcat1115's avatar
ddcat1115 committed
177 178
    }
    return ItemDom;
179
  };
jiang's avatar
jiang committed
180 181 182
  handleOpenChange = (openKeys) => {
    const lastOpenKey = openKeys[openKeys.length - 1];
    const isMainMenu = this.menus.some(
183 184
      item =>
        lastOpenKey && (item.key === lastOpenKey || item.path === lastOpenKey),
jiang's avatar
jiang committed
185 186 187 188
    );
    this.setState({
      openKeys: isMainMenu ? [lastOpenKey] : [...openKeys],
    });
189
  };
jiang's avatar
jiang committed
190
  render() {
191
    const { logo, collapsed, onCollapse } = this.props;
192
    const { openKeys } = this.state;
jiang's avatar
jiang committed
193
    // Don't show popup menu when it is been collapsed
194 195 196 197 198
    const menuProps = collapsed
      ? {}
      : {
        openKeys,
      };
199
    // if pathname can't match, use the nearest parent's key
200
    let selectedKeys = this.getSelectedMenuKeys();
201 202 203
    if (!selectedKeys.length) {
      selectedKeys = [openKeys[openKeys.length - 1]];
    }
jiang's avatar
jiang committed
204 205 206 207 208
    return (
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
209
        breakpoint="lg"
jiang's avatar
jiang committed
210 211 212 213
        onCollapse={onCollapse}
        width={256}
        className={styles.sider}
      >
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
214
        <div className={styles.logo} key="logo">
jiang's avatar
jiang committed
215 216 217 218 219 220
          <Link to="/">
            <img src={logo} alt="logo" />
            <h1>Ant Design Pro</h1>
          </Link>
        </div>
        <Menu
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
221
          key="Menu"
jiang's avatar
jiang committed
222 223 224 225
          theme="dark"
          mode="inline"
          {...menuProps}
          onOpenChange={this.handleOpenChange}
226
          selectedKeys={selectedKeys}
jiang's avatar
jiang committed
227 228 229 230 231 232 233 234
          style={{ padding: '16px 0', width: '100%' }}
        >
          {this.getNavMenuItems(this.menus)}
        </Menu>
      </Sider>
    );
  }
}