SliderMenu.js 6.68 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
  const {
    location: { pathname },
陈帅's avatar
陈帅 committed
19
    flatMenuKeys,
jim's avatar
jim committed
20
  } = props;
jim's avatar
jim committed
21 22
  return urlToList(pathname)
    .map(item => {
陈帅's avatar
陈帅 committed
23
      return getMenuMatches(flatMenuKeys, item)[0];
jim's avatar
jim committed
24 25 26 27
    })
    .filter(item => item);
};

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

jim's avatar
jim committed
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 67
/**
 * 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
68 69 70
export default class SiderMenu extends PureComponent {
  constructor(props) {
    super(props);
jim's avatar
jim committed
71
    this.flatMenuKeys = getFlatMenuKeys(props.menuData);
jiang's avatar
jiang committed
72
    this.state = {
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;
  }
陈帅's avatar
陈帅 committed
87

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

jim's avatar
jim committed
101
  /**
102 103 104
   * 判断是否是http链接.返回 Link 或 a
   * Judge whether it is http link.return a or Link
   * @memberof SiderMenu
陈帅's avatar
陈帅 committed
105
   */
jim's avatar
jim committed
106
  getMenuItemPath = item => {
ddcat1115's avatar
ddcat1115 committed
107 108 109 110 111 112 113
    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}>
114 115
          {icon}
          <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
116 117 118
        </a>
      );
    }
陈帅's avatar
陈帅 committed
119
    const { pathname, isMobile, onCollapse } = this.props;
ddcat1115's avatar
ddcat1115 committed
120 121 122 123
    return (
      <Link
        to={itemPath}
        target={target}
陈帅's avatar
陈帅 committed
124
        replace={itemPath === pathname}
125
        onClick={
陈帅's avatar
陈帅 committed
126
          isMobile
127
            ? () => {
陈帅's avatar
陈帅 committed
128
                onCollapse(true);
129 130 131
              }
            : undefined
        }
ddcat1115's avatar
ddcat1115 committed
132
      >
133 134
        {icon}
        <span>{name}</span>
ddcat1115's avatar
ddcat1115 committed
135 136
      </Link>
    );
137
  };
陈帅's avatar
陈帅 committed
138

ddcat1115's avatar
ddcat1115 committed
139 140 141
  /**
   * get SubMenu or Item
   */
jim's avatar
jim committed
142
  getSubMenuOrItem = item => {
ddcat1115's avatar
ddcat1115 committed
143
    if (item.children && item.children.some(child => child.name)) {
hzq's avatar
hzq committed
144 145 146 147 148 149 150 151 152 153 154 155
      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
156 157
                item.name
              )
hzq's avatar
hzq committed
158 159 160 161 162
            }
            key={item.path}
          >
            {childrenItems}
          </SubMenu>
hzq's avatar
hzq committed
163
        );
hzq's avatar
hzq committed
164
      }
hzq's avatar
hzq committed
165
      return null;
ddcat1115's avatar
ddcat1115 committed
166
    } else {
jim's avatar
jim committed
167
      return <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>;
ddcat1115's avatar
ddcat1115 committed
168
    }
169
  };
陈帅's avatar
陈帅 committed
170

jim's avatar
jim committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  /**
   * 获得菜单子节点
   * @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
188

jim's avatar
jim committed
189 190 191 192 193 194 195
  // Get the currently selected menu
  getSelectedMenuKeys = () => {
    const {
      location: { pathname },
    } = this.props;
    return getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
  };
陈帅's avatar
陈帅 committed
196

jim's avatar
jim committed
197 198 199 200 201 202 203 204 205
  // conversion Path
  // 转化路径
  conversionPath = path => {
    if (path && path.indexOf('http') === 0) {
      return path;
    } else {
      return `/${path || ''}`.replace(/\/+/g, '/');
    }
  };
陈帅's avatar
陈帅 committed
206

jim's avatar
jim committed
207 208
  // permission to check
  checkPermissionItem = (authority, ItemDom) => {
陈帅's avatar
陈帅 committed
209 210 211
    const { Authorized } = this.props;
    if (Authorized && Authorized.check) {
      const { check } = Authorized;
jim's avatar
jim committed
212 213 214 215
      return check(authority, ItemDom);
    }
    return ItemDom;
  };
陈帅's avatar
陈帅 committed
216

jim's avatar
jim committed
217
  isMainMenu = key => {
陈帅's avatar
陈帅 committed
218 219
    const { menuData } = this.props;
    return menuData.some(item => {
jim's avatar
jim committed
220 221 222 223 224
      if (key) {
        return item.key === key || item.path === key;
      }
      return false;
    });
jim's avatar
jim committed
225
  };
陈帅's avatar
陈帅 committed
226

jim's avatar
jim committed
227
  handleOpenChange = openKeys => {
ddcat1115's avatar
ddcat1115 committed
228
    const moreThanOne = openKeys.filter(openKey => this.isMainMenu(openKey)).length > 1;
jiang's avatar
jiang committed
229
    this.setState({
jim's avatar
jim committed
230
      openKeys: moreThanOne ? [openKeys.pop()] : [...openKeys],
jiang's avatar
jiang committed
231
    });
232
  };
陈帅's avatar
陈帅 committed
233

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