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

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

/**
 * 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
44
export const getMenuMatchKeys = (flatMenuKeys, paths) =>
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
45 46 47 48 49
  paths.reduce(
    (matchKeys, path) =>
      matchKeys.concat(flatMenuKeys.filter(item => pathToRegexp(item).test(path))),
    []
  );
50

jiang's avatar
jiang committed
51 52 53
export default class SiderMenu extends PureComponent {
  constructor(props) {
    super(props);
ddcat1115's avatar
ddcat1115 committed
54
    this.menus = props.menuData;
55
    this.flatMenuKeys = getFlatMenuKeys(props.menuData);
jiang's avatar
jiang committed
56 57 58 59
    this.state = {
      openKeys: this.getDefaultCollapsedSubMenus(props),
    };
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
60

61 62 63 64 65 66 67
  componentWillReceiveProps(nextProps) {
    if (nextProps.location.pathname !== this.props.location.pathname) {
      this.setState({
        openKeys: this.getDefaultCollapsedSubMenus(nextProps),
      });
    }
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
68

69 70 71 72 73
  /**
   * Convert pathname to openKeys
   * /list/search/articles = > ['list','/list/search']
   * @param  props
   */
jiang's avatar
jiang committed
74
  getDefaultCollapsedSubMenus(props) {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
75 76 77 78
    const {
      location: { pathname },
    } =
      props || this.props;
歀去's avatar
歀去 committed
79
    return getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
jiang's avatar
jiang committed
80
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
81

82
  /**
83 84 85
   * εˆ€ζ–­ζ˜―ε¦ζ˜―httpι“ΎζŽ₯.θΏ”ε›ž Link ζˆ– a
   * Judge whether it is http link.return a or Link
   * @memberof SiderMenu
86
   */
jim's avatar
jim committed
87
  getMenuItemPath = item => {
ddcat1115's avatar
ddcat1115 committed
88 89 90 91 92 93 94
    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}>
95 96
          {icon}
          <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
97 98 99 100 101 102 103 104
        </a>
      );
    }
    return (
      <Link
        to={itemPath}
        target={target}
        replace={itemPath === this.props.location.pathname}
105 106 107 108 109 110 111
        onClick={
          this.props.isMobile
            ? () => {
                this.props.onCollapse(true);
              }
            : undefined
        }
ddcat1115's avatar
ddcat1115 committed
112
      >
113 114
        {icon}
        <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
115 116
      </Link>
    );
117
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
118

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

ddcat1115's avatar
ddcat1115 committed
151
  /**
152 153 154
   * θŽ·εΎ—θœε•ε­θŠ‚η‚Ή
   * @memberof SiderMenu
   */
jim's avatar
jim committed
155
  getNavMenuItems = menusData => {
jiang's avatar
jiang committed
156 157 158
    if (!menusData) {
      return [];
    }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
159 160
    return menusData
      .filter(item => item.name && !item.hideInMenu)
jim's avatar
jim committed
161
      .map(item => {
162
        // make dom
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
163 164 165
        const ItemDom = this.getSubMenuOrItem(item);
        return this.checkPermissionItem(item.authority, ItemDom);
      })
166 167
      .filter(item => item);
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
168

169 170
  // Get the currently selected menu
  getSelectedMenuKeys = () => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
171 172 173
    const {
      location: { pathname },
    } = this.props;
歀去's avatar
歀去 committed
174
    return getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
175
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
176

ddcat1115's avatar
ddcat1115 committed
177 178
  // conversion Path
  // θ½¬εŒ–θ·―εΎ„
jim's avatar
jim committed
179
  conversionPath = path => {
ddcat1115's avatar
ddcat1115 committed
180 181 182 183 184
    if (path && path.indexOf('http') === 0) {
      return path;
    } else {
      return `/${path || ''}`.replace(/\/+/g, '/');
    }
185
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
186

ddcat1115's avatar
ddcat1115 committed
187 188 189 190
  // permission to check
  checkPermissionItem = (authority, ItemDom) => {
    if (this.props.Authorized && this.props.Authorized.check) {
      const { check } = this.props.Authorized;
191
      return check(authority, ItemDom);
ddcat1115's avatar
ddcat1115 committed
192 193
    }
    return ItemDom;
194
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
195

jim's avatar
jim committed
196 197 198
  isMainMenu = key => {
    return this.menus.some(item => key && (item.key === key || item.path === key));
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
199

jim's avatar
jim committed
200
  handleOpenChange = openKeys => {
ddcat1115's avatar
ddcat1115 committed
201 202
    const lastOpenKey = openKeys[openKeys.length - 1];
    const moreThanOne = openKeys.filter(openKey => this.isMainMenu(openKey)).length > 1;
jiang's avatar
jiang committed
203
    this.setState({
ddcat1115's avatar
ddcat1115 committed
204
      openKeys: moreThanOne ? [lastOpenKey] : [...openKeys],
jiang's avatar
jiang committed
205
    });
206
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
207

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