SiderMenu.js 6.48 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
  componentWillReceiveProps(nextProps) {
62 63
    const { location } = this.props;
    if (nextProps.location.pathname !== location.pathname) {
64 65 66 67 68
      this.setState({
        openKeys: this.getDefaultCollapsedSubMenus(nextProps),
      });
    }
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
69

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

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

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

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

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

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

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

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

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

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