SliderMenu.js 6.84 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
import { Link } from 'dva/router';
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
5
import { FormattedMessage } from 'react-intl';
jiang's avatar
jiang committed
6
import styles from './index.less';
Erwin Zhang's avatar
Erwin Zhang committed
7
import BaseMenu, { getMenuMatches } from './BaseMenu';
jim's avatar
jim committed
8
import { urlToList } from '../_utils/pathTools';
jiang's avatar
jiang committed
9

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

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

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

jim's avatar
jim committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
/**
 * 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
69 70 71
export default class SiderMenu extends PureComponent {
  constructor(props) {
    super(props);
jim's avatar
jim committed
72
    this.flatMenuKeys = getFlatMenuKeys(props.menuData);
jiang's avatar
jiang committed
73
    this.state = {
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;
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
88

89
  /**
jim's avatar
jim committed
90 91 92
   * Convert pathname to openKeys
   * /list/search/articles = > ['list','/list/search']
   * @param  props
jim's avatar
jim committed
93 94 95 96 97 98 99 100
   */
  getDefaultCollapsedSubMenus(props) {
    const {
      location: { pathname },
    } =
      props || this.props;
    return getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
101

jim's avatar
jim committed
102
  /**
103 104 105
   * εˆ€ζ–­ζ˜―ε¦ζ˜―httpι“ΎζŽ₯.θΏ”ε›ž Link ζˆ– a
   * Judge whether it is http link.return a or Link
   * @memberof SiderMenu
106
   */
jim's avatar
jim committed
107
  getMenuItemPath = item => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
108
    console.log(item);
ddcat1115's avatar
ddcat1115 committed
109 110 111 112 113 114 115
    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}>
116
          {icon}
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
117 118 119
          <span>
            <FormattedMessage id={name} />
          </span>
ddcat1115's avatar
ddcat1115 committed
120 121 122
        </a>
      );
    }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
123
    const { pathname, isMobile, onCollapse } = this.props;
ddcat1115's avatar
ddcat1115 committed
124 125 126 127
    return (
      <Link
        to={itemPath}
        target={target}
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
128
        replace={itemPath === pathname}
129
        onClick={
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
130
          isMobile
131
            ? () => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
132
                onCollapse(true);
133 134 135
              }
            : undefined
        }
ddcat1115's avatar
ddcat1115 committed
136
      >
137
        {icon}
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
138 139 140
        <span>
          <FormattedMessage id={name} />
        </span>
ddcat1115's avatar
ddcat1115 committed
141 142
      </Link>
    );
143
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
144

ddcat1115's avatar
ddcat1115 committed
145 146 147
  /**
   * get SubMenu or Item
   */
jim's avatar
jim committed
148
  getSubMenuOrItem = item => {
ddcat1115's avatar
ddcat1115 committed
149
    if (item.children && item.children.some(child => child.name)) {
hzq's avatar
hzq committed
150 151 152 153 154 155 156 157 158 159 160 161
      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
162 163
                item.name
              )
hzq's avatar
hzq committed
164 165 166 167 168
            }
            key={item.path}
          >
            {childrenItems}
          </SubMenu>
hzq's avatar
hzq committed
169
        );
hzq's avatar
hzq committed
170
      }
hzq's avatar
hzq committed
171
      return null;
ddcat1115's avatar
ddcat1115 committed
172
    } else {
jim's avatar
jim committed
173
      return <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>;
ddcat1115's avatar
ddcat1115 committed
174
    }
175
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
176

jim's avatar
jim committed
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
  /**
   * θŽ·εΎ—θœε•ε­θŠ‚η‚Ή
   * @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);
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
194

jim's avatar
jim committed
195 196 197 198 199 200 201
  // Get the currently selected menu
  getSelectedMenuKeys = () => {
    const {
      location: { pathname },
    } = this.props;
    return getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
202

jim's avatar
jim committed
203 204 205 206 207 208 209 210 211
  // conversion Path
  // θ½¬εŒ–θ·―εΎ„
  conversionPath = path => {
    if (path && path.indexOf('http') === 0) {
      return path;
    } else {
      return `/${path || ''}`.replace(/\/+/g, '/');
    }
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
212

jim's avatar
jim committed
213 214
  // permission to check
  checkPermissionItem = (authority, ItemDom) => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
215 216 217
    const { Authorized } = this.props;
    if (Authorized && Authorized.check) {
      const { check } = Authorized;
jim's avatar
jim committed
218 219 220 221
      return check(authority, ItemDom);
    }
    return ItemDom;
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
222

jim's avatar
jim committed
223
  isMainMenu = key => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
224 225
    const { menuData } = this.props;
    return menuData.some(item => {
jim's avatar
jim committed
226 227 228 229 230
      if (key) {
        return item.key === key || item.path === key;
      }
      return false;
    });
jim's avatar
jim committed
231
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
232

jim's avatar
jim committed
233
  handleOpenChange = openKeys => {
ddcat1115's avatar
ddcat1115 committed
234
    const moreThanOne = openKeys.filter(openKey => this.isMainMenu(openKey)).length > 1;
jiang's avatar
jiang committed
235
    this.setState({
jim's avatar
jim committed
236
      openKeys: moreThanOne ? [openKeys.pop()] : [...openKeys],
jiang's avatar
jiang committed
237
    });
238
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
239

jiang's avatar
jiang committed
240
  render() {
241
    const { logo, collapsed, onCollapse, fixSiderbar, theme } = this.props;
242
    const { openKeys } = this.state;
jim's avatar
jim committed
243
    const defaultProps = collapsed ? {} : { openKeys };
jiang's avatar
jiang committed
244 245 246 247 248
    return (
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
249
        breakpoint="lg"
jiang's avatar
jiang committed
250 251
        onCollapse={onCollapse}
        width={256}
252 253 254
        className={`${styles.sider} ${fixSiderbar ? styles.fixSiderbar : ''} ${
          theme === 'light' ? styles.light : ''
        }`}
jiang's avatar
jiang committed
255
      >
256
        <div className={styles.logo} key="logo" id="logo">
jiang's avatar
jiang committed
257 258 259 260 261
          <Link to="/">
            <img src={logo} alt="logo" />
            <h1>Ant Design Pro</h1>
          </Link>
        </div>
Erwin Zhang's avatar
Erwin Zhang committed
262
        <BaseMenu
jim's avatar
jim committed
263
          {...this.props}
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
264
          key="Menu"
jiang's avatar
jiang committed
265
          mode="inline"
jim's avatar
jim committed
266
          handleOpenChange={this.handleOpenChange}
jiang's avatar
jiang committed
267 268
          onOpenChange={this.handleOpenChange}
          style={{ padding: '16px 0', width: '100%' }}
jim's avatar
jim committed
269
          {...defaultProps}
jim's avatar
jim committed
270
        />
jiang's avatar
jiang committed
271 272 273 274
      </Sider>
    );
  }
}