SliderMenu.js 6.92 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 'umi/locale';
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 => {
ddcat1115's avatar
ddcat1115 committed
108 109
    const itemPath = this.conversionPath(item.path);
    const icon = getIcon(item.icon);
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
110
    const { target, name, locale } = item;
ddcat1115's avatar
ddcat1115 committed
111 112 113 114
    // Is it a http link
    if (/^https?:\/\//.test(itemPath)) {
      return (
        <a href={itemPath} target={target}>
115
          {icon}
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
116
          <span>
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
117
            <FormattedMessage id={locale} defaultMessage={name} />
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
118
          </span>
ddcat1115's avatar
ddcat1115 committed
119 120 121
        </a>
      );
    }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
122
    const { pathname, isMobile, onCollapse } = this.props;
ddcat1115's avatar
ddcat1115 committed
123 124 125 126
    return (
      <Link
        to={itemPath}
        target={target}
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
127
        replace={itemPath === pathname}
128
        onClick={
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
129
          isMobile
130
            ? () => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
131
                onCollapse(true);
132 133 134
              }
            : undefined
        }
ddcat1115's avatar
ddcat1115 committed
135
      >
136
        {icon}
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
137
        <span>
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
138
          <FormattedMessage id={locale} defaultMessage={name} />
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
139
        </span>
ddcat1115's avatar
ddcat1115 committed
140 141
      </Link>
    );
142
  };
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
143

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

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

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

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

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

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

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

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