SiderMenu.js 6.6 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 68 69
export default class SiderMenu extends PureComponent {
  constructor(props) {
    super(props);
jim's avatar
jim committed
70 71
    this.menus = props.menuData;
    this.flatMenuKeys = getFlatMenuKeys(props.menuData);
jiang's avatar
jiang committed
72
    this.state = {
jim's avatar
jim committed
73
      pathname: props.location.pathname,
jim's avatar
jim committed
74
      openKeys: getDefaultCollapsedSubMenus(props),
jiang's avatar
jiang committed
75 76
    };
  }
jim's avatar
jim committed
77

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