SiderMenu.js 6.41 KB
Newer Older
jiang's avatar
jiang committed
1 2
import React, { PureComponent } from 'react';
import { Layout, Menu, Icon } from 'antd';
jim's avatar
jim 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';
Erwin Zhang's avatar
Erwin Zhang committed
6
import BaseMenu, { getMenuMatches } from './BaseMenu';
jim's avatar
jim committed
7
import { urlToList } from '../_utils/pathTools';
jiang's avatar
jiang committed
8

jim's avatar
jim committed
9
const { Sider } = Layout;
jiang's avatar
jiang committed
10 11
const { SubMenu } = Menu;

jim's avatar
jim committed
12 13 14 15 16
/**
 * θŽ·εΎ—θœε•ε­θŠ‚η‚Ή
 * @memberof SiderMenu
 */
const getDefaultCollapsedSubMenus = props => {
jim's avatar
jim committed
17 18 19
  const {
    location: { pathname },
  } = props;
jim's avatar
jim committed
20 21 22 23 24 25 26
  return urlToList(pathname)
    .map(item => {
      return getMenuMatches(props.flatMenuKeys, item)[0];
    })
    .filter(item => item);
};

27 28 29 30
// 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
31
const getIcon = icon => {
32
  if (typeof icon === 'string' && icon.indexOf('http') === 0) {
33
    return <img src={icon} alt="icon" className={`${styles.icon} sider-menu-item-img`} />;
34 35 36 37 38 39 40
  }
  if (typeof icon === 'string') {
    return <Icon type={icon} />;
  }
  return icon;
};

jim's avatar
jim committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
/**
 * Recursively flatten the data
 * [{path:string},{path:string}] => {path,path2}
 * @param  menu
 */
export const getFlatMenuKeys = menu =>
  menu.reduce((keys, item) => {
    keys.push(item.path);
    if (item.children) {
      return keys.concat(getFlatMenuKeys(item.children));
    }
    return keys;
  }, []);

/**
 * Find all matched menu keys based on paths
 * @param  flatMenuKeys: [/abc, /abc/:id, /abc/:id/info]
 * @param  paths: [/abc, /abc/11, /abc/11/info]
 */
export const getMenuMatchKeys = (flatMenuKeys, paths) =>
  paths.reduce(
    (matchKeys, path) =>
      matchKeys.concat(flatMenuKeys.filter(item => pathToRegexp(item).test(path))),
    []
  );

jiang's avatar
jiang committed
67
export default class SiderMenu extends PureComponent {
jim's avatar
jim committed
68 69 70 71 72
  static getDerivedStateFromProps(nextProps) {
    return {
      openKeys: getDefaultCollapsedSubMenus(nextProps),
    };
  }
jiang's avatar
jiang committed
73 74
  constructor(props) {
    super(props);
jim's avatar
jim committed
75 76
    this.menus = props.menuData;
    this.flatMenuKeys = getFlatMenuKeys(props.menuData);
jiang's avatar
jiang committed
77
    this.state = {
jim's avatar
jim committed
78
      openKeys: getDefaultCollapsedSubMenus(props),
jiang's avatar
jiang committed
79 80
    };
  }
jim's avatar
jim committed
81

82
  /**
jim's avatar
jim committed
83 84 85
   * Convert pathname to openKeys
   * /list/search/articles = > ['list','/list/search']
   * @param  props
jim's avatar
jim committed
86 87 88 89 90 91 92 93 94
   */
  getDefaultCollapsedSubMenus(props) {
    const {
      location: { pathname },
    } =
      props || this.props;
    return getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
  }
  /**
95 96 97
   * εˆ€ζ–­ζ˜―ε¦ζ˜―httpι“ΎζŽ₯.θΏ”ε›ž Link ζˆ– a
   * Judge whether it is http link.return a or Link
   * @memberof SiderMenu
98
   */
jim's avatar
jim committed
99
  getMenuItemPath = item => {
ddcat1115's avatar
ddcat1115 committed
100 101 102 103 104 105 106
    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}>
107 108
          {icon}
          <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
109 110 111 112 113 114 115 116
        </a>
      );
    }
    return (
      <Link
        to={itemPath}
        target={target}
        replace={itemPath === this.props.location.pathname}
117 118 119 120 121 122 123
        onClick={
          this.props.isMobile
            ? () => {
                this.props.onCollapse(true);
              }
            : undefined
        }
ddcat1115's avatar
ddcat1115 committed
124
      >
125 126
        {icon}
        <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
127 128
      </Link>
    );
129
  };
ddcat1115's avatar
ddcat1115 committed
130 131 132
  /**
   * get SubMenu or Item
   */
jim's avatar
jim committed
133
  getSubMenuOrItem = item => {
ddcat1115's avatar
ddcat1115 committed
134
    if (item.children && item.children.some(child => child.name)) {
hzq's avatar
hzq committed
135 136 137 138 139 140 141 142 143 144 145 146
      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
147 148
                item.name
              )
hzq's avatar
hzq committed
149 150 151 152 153
            }
            key={item.path}
          >
            {childrenItems}
          </SubMenu>
hzq's avatar
hzq committed
154
        );
hzq's avatar
hzq committed
155
      }
hzq's avatar
hzq committed
156
      return null;
ddcat1115's avatar
ddcat1115 committed
157
    } else {
jim's avatar
jim committed
158
      return <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>;
ddcat1115's avatar
ddcat1115 committed
159
    }
160
  };
jim's avatar
jim committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
  /**
   * θŽ·εΎ—θœε•ε­θŠ‚η‚Ή
   * @memberof SiderMenu
   */
  getNavMenuItems = menusData => {
    if (!menusData) {
      return [];
    }
    return menusData
      .filter(item => item.name && !item.hideInMenu)
      .map(item => {
        // make dom
        const ItemDom = this.getSubMenuOrItem(item);
        return this.checkPermissionItem(item.authority, ItemDom);
      })
      .filter(item => item);
  };
  // Get the currently selected menu
  getSelectedMenuKeys = () => {
    const {
      location: { pathname },
    } = this.props;
    return getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
  };
  // 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;
  };
jim's avatar
jim committed
202
  isMainMenu = key => {
jim's avatar
jim committed
203
    return this.props.menuData.some(item => key && (item.key === key || item.path === key));
jim's avatar
jim committed
204 205
  };
  handleOpenChange = openKeys => {
ddcat1115's avatar
ddcat1115 committed
206 207
    const lastOpenKey = openKeys[openKeys.length - 1];
    const moreThanOne = openKeys.filter(openKey => this.isMainMenu(openKey)).length > 1;
jiang's avatar
jiang committed
208
    this.setState({
ddcat1115's avatar
ddcat1115 committed
209
      openKeys: moreThanOne ? [lastOpenKey] : [...openKeys],
jiang's avatar
jiang committed
210
    });
211
  };
jiang's avatar
jiang committed
212
  render() {
jim's avatar
jim committed
213
    const { logo, collapsed, onCollapse, theme } = this.props;
214
    const { openKeys } = this.state;
jim's avatar
jim committed
215
    const defaultProps = collapsed ? {} : { openKeys };
jiang's avatar
jiang committed
216 217 218 219 220
    return (
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
221
        breakpoint="lg"
jiang's avatar
jiang committed
222 223
        onCollapse={onCollapse}
        width={256}
jim's avatar
jim committed
224
        className={`${styles.sider} ${theme === 'light' ? styles.light : ''}`}
jiang's avatar
jiang committed
225
      >
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
226
        <div className={styles.logo} key="logo">
jiang's avatar
jiang committed
227 228 229 230 231
          <Link to="/">
            <img src={logo} alt="logo" />
            <h1>Ant Design Pro</h1>
          </Link>
        </div>
Erwin Zhang's avatar
Erwin Zhang committed
232
        <BaseMenu
jim's avatar
jim committed
233
          {...this.props}
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
234
          key="Menu"
jiang's avatar
jiang committed
235
          mode="inline"
jim's avatar
jim committed
236
          handleOpenChange={this.handleOpenChange}
jiang's avatar
jiang committed
237 238
          onOpenChange={this.handleOpenChange}
          style={{ padding: '16px 0', width: '100%' }}
jim's avatar
jim committed
239
          {...defaultProps}
jim's avatar
jim committed
240
        />
jiang's avatar
jiang committed
241 242 243 244
      </Sider>
    );
  }
}