SliderMenu.js 6.64 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
    this.flatMenuKeys = getFlatMenuKeys(props.menuData);
jiang's avatar
jiang committed
71
    this.state = {
jim's avatar
jim committed
72
      pathname: props.location.pathname,
jim's avatar
jim committed
73
      openKeys: getDefaultCollapsedSubMenus(props),
jiang's avatar
jiang committed
74 75
    };
  }
jim's avatar
jim committed
76

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