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';
3
import pathToRegexp from 'path-to-regexp';
jiang's avatar
jiang committed
4 5 6 7 8 9
import { Link } from 'dva/router';
import styles from './index.less';

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

10 11 12 13 14 15 16 17 18 19 20 21 22 23
// 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;
};

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