BasicLayout.js 10.6 KB
Newer Older
1 2
import React from 'react';
import PropTypes from 'prop-types';
afc163's avatar
afc163 committed
3
import { Layout, Menu, Icon, Avatar, Dropdown, Tag, message, Spin } from 'antd';
4 5
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
ddcat1115's avatar
ddcat1115 committed
6
import { Link, routerRedux, Route, Redirect, Switch } from 'dva/router';
7 8 9 10 11 12
import moment from 'moment';
import groupBy from 'lodash/groupBy';
import styles from './BasicLayout.less';
import HeaderSearch from '../components/HeaderSearch';
import NoticeIcon from '../components/NoticeIcon';
import GlobalFooter from '../components/GlobalFooter';
afc163's avatar
afc163 committed
13
import { getNavData } from '../common/nav';
ddcat1115's avatar
ddcat1115 committed
14
import { getRouteData } from '../utils/utils';
15 16 17 18 19 20

const { Header, Sider, Content } = Layout;
const { SubMenu } = Menu;

class BasicLayout extends React.PureComponent {
  static childContextTypes = {
ddcat1115's avatar
ddcat1115 committed
21 22
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
23
  }
afc163's avatar
afc163 committed
24 25 26 27
  constructor(props) {
    super(props);
    // 把一级 Layout 的 children 作为菜单项
    this.menus = getNavData().reduce((arr, current) => arr.concat(current.children), []);
afc163's avatar
afc163 committed
28 29 30
    this.state = {
      openKeys: this.getDefaultCollapsedSubMenus(props),
    };
afc163's avatar
afc163 committed
31
  }
32
  getChildContext() {
ddcat1115's avatar
ddcat1115 committed
33 34 35 36 37 38 39 40
    const { location } = this.props;
    const routeData = getRouteData('BasicLayout');
    const menuData = getNavData().reduce((arr, current) => arr.concat(current.children), []);
    const breadcrumbNameMap = {};
    routeData.concat(menuData).forEach((item) => {
      breadcrumbNameMap[item.path] = item.name;
    });
    return { location, breadcrumbNameMap };
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'user/fetchCurrent',
    });
  }
  onCollapse = (collapsed) => {
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  }
  onMenuClick = ({ key }) => {
    if (key === 'logout') {
      this.props.dispatch(routerRedux.push('/user/login'));
    }
  }
afc163's avatar
afc163 committed
58 59
  getDefaultCollapsedSubMenus(props) {
    const currentMenuSelectedKeys = [...this.getCurrentMenuSelectedKeys(props)];
60 61 62
    currentMenuSelectedKeys.splice(-1, 1);
    return currentMenuSelectedKeys;
  }
afc163's avatar
afc163 committed
63 64
  getCurrentMenuSelectedKeys(props) {
    const { location: { pathname } } = props || this.props;
65 66
    const keys = pathname.split('/').slice(1);
    if (keys.length === 1 && keys[0] === '') {
afc163's avatar
afc163 committed
67
      return [this.menus[0].key];
68 69 70 71
    }
    return keys;
  }
  getNavMenuItems(menusData, parentPath = '') {
afc163's avatar
afc163 committed
72 73 74
    if (!menusData) {
      return [];
    }
75 76 77 78 79 80 81 82 83
    return menusData.map((item) => {
      if (!item.name) {
        return null;
      }
      const itemPath = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
      if (item.children && item.children.some(child => child.name)) {
        return (
          <SubMenu
            title={
afc163's avatar
afc163 committed
84 85 86 87 88 89
              item.icon ? (
                <span>
                  <Icon type={item.icon} />
                  <span>{item.name}</span>
                </span>
              ) : item.name
90 91 92 93 94 95 96 97 98
            }
            key={item.key || item.path}
          >
            {this.getNavMenuItems(item.children, itemPath)}
          </SubMenu>
        );
      }
      return (
        <Menu.Item key={item.key || item.path}>
ddcat1115's avatar
ddcat1115 committed
99
          <Link to={itemPath}>
afc163's avatar
afc163 committed
100
            {item.icon && <Icon type={item.icon} />}
101 102 103 104 105 106 107
            <span>{item.name}</span>
          </Link>
        </Menu.Item>
      );
    });
  }
  getPageTitle() {
ddcat1115's avatar
ddcat1115 committed
108 109 110 111 112 113
    const { location } = this.props;
    const { pathname } = location;
    let title = 'Ant Design Pro';
    getRouteData('UserLayout').forEach((item) => {
      if (item.path === pathname) {
        title = `${item.name} - Ant Design Pro`;
114
      }
ddcat1115's avatar
ddcat1115 committed
115 116
    });
    return title;
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
  }
  getNoticeData() {
    const { notices = [] } = this.props;
    if (notices.length === 0) {
      return {};
    }
    const newNotices = notices.map((notice) => {
      const newNotice = { ...notice };
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      // transform id to item key
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = ({
afc163's avatar
afc163 committed
134
          todo: '',
135 136
          processing: 'blue',
          urgent: 'red',
afc163's avatar
afc163 committed
137
          doing: 'gold',
138
        })[newNotice.status];
afc163's avatar
afc163 committed
139
        newNotice.extra = <Tag color={color}>{newNotice.extra}</Tag>;
140 141 142 143 144
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  }
afc163's avatar
afc163 committed
145
  handleOpenChange = (openKeys) => {
afc163's avatar
afc163 committed
146
    const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
afc163's avatar
afc163 committed
147 148 149 150
    this.setState({
      openKeys: latestOpenKey ? [latestOpenKey] : [],
    });
  }
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
  toggle = () => {
    const { collapsed } = this.props;
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: !collapsed,
    });
  }
  handleNoticeClear = (type) => {
    message.success(`清空了${type}`);
    this.props.dispatch({
      type: 'global/clearNotices',
      payload: type,
    });
  }
  handleNoticeVisibleChange = (visible) => {
    if (visible) {
      this.props.dispatch({
        type: 'global/fetchNotices',
      });
    }
  }
  render() {
ddcat1115's avatar
ddcat1115 committed
173
    const { currentUser, collapsed, fetchingNotices } = this.props;
174 175 176

    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
afc163's avatar
afc163 committed
177 178
        <Menu.Item disabled><Icon type="user" />个人中心</Menu.Item>
        <Menu.Item disabled><Icon type="setting" />设置</Menu.Item>
179 180 181 182 183 184
        <Menu.Divider />
        <Menu.Item key="logout"><Icon type="logout" />退出登录</Menu.Item>
      </Menu>
    );
    const noticeData = this.getNoticeData();

afc163's avatar
afc163 committed
185 186 187 188 189
    // Don't show popup menu when it is been collapsed
    const menuProps = collapsed ? {} : {
      openKeys: this.state.openKeys,
    };

190 191 192 193 194 195 196 197 198 199
    return (
      <DocumentTitle title={this.getPageTitle()}>
        <Layout>
          <Sider
            trigger={null}
            collapsible
            collapsed={collapsed}
            collapsedWidth={80}
            breakpoint="md"
            onCollapse={this.onCollapse}
afc163's avatar
afc163 committed
200
            width={256}
afc163's avatar
afc163 committed
201
            className={styles.sider}
202 203 204
          >
            <div className={styles.logo}>
              <Link to="/">
niko's avatar
niko committed
205
                <img src="https://gw.alipayobjects.com/zos/rmsportal/iwWyPinUoseUxIAeElSx.svg" alt="logo" />
206 207 208 209 210 211
                <h1>Ant Design Pro</h1>
              </Link>
            </div>
            <Menu
              theme="dark"
              mode="inline"
afc163's avatar
afc163 committed
212
              {...menuProps}
afc163's avatar
afc163 committed
213
              onOpenChange={this.handleOpenChange}
214 215
              selectedKeys={this.getCurrentMenuSelectedKeys()}
              style={{ margin: '24px 0', width: '100%' }}
niko's avatar
niko committed
216
              inlineIndent={24}
217
            >
afc163's avatar
afc163 committed
218
              {this.getNavMenuItems(this.menus)}
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
            </Menu>
          </Sider>
          <Layout>
            <Header className={styles.header}>
              <Icon
                className={styles.trigger}
                type={collapsed ? 'menu-unfold' : 'menu-fold'}
                onClick={this.toggle}
              />
              <div className={styles.right}>
                <HeaderSearch
                  className={`${styles.action} ${styles.search}`}
                  placeholder="站内搜索"
                  dataSource={['搜索提示一', '搜索提示二', '搜索提示三']}
                  onSearch={(value) => {
afc163's avatar
afc163 committed
234
                    console.log('input', value); // eslint-disable-line
235 236
                  }}
                  onPressEnter={(value) => {
afc163's avatar
afc163 committed
237
                    console.log('enter', value); // eslint-disable-line
238 239 240 241 242 243 244 245 246 247 248 249 250
                  }}
                />
                <NoticeIcon
                  className={styles.action}
                  count={currentUser.notifyCount}
                  onItemClick={(item, tabProps) => {
                    console.log(item, tabProps); // eslint-disable-line
                  }}
                  onClear={this.handleNoticeClear}
                  onPopupVisibleChange={this.handleNoticeVisibleChange}
                  loading={fetchingNotices}
                  popupAlign={{ offset: [20, -16] }}
                >
afc163's avatar
afc163 committed
251 252 253 254
                  <NoticeIcon.Tab
                    list={noticeData['通知']}
                    title="通知"
                    emptyText="你已查看所有通知"
afc163's avatar
afc163 committed
255
                    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
afc163's avatar
afc163 committed
256 257 258 259 260
                  />
                  <NoticeIcon.Tab
                    list={noticeData['消息']}
                    title="消息"
                    emptyText="您已读完所有消息"
afc163's avatar
afc163 committed
261
                    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
afc163's avatar
afc163 committed
262 263 264 265 266 267 268
                  />
                  <NoticeIcon.Tab
                    list={noticeData['待办']}
                    title="待办"
                    emptyText="你已完成所有待办"
                    emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
                  />
269
                </NoticeIcon>
afc163's avatar
afc163 committed
270 271 272 273 274 275 276 277
                {currentUser.name ? (
                  <Dropdown overlay={menu}>
                    <span className={`${styles.action} ${styles.account}`}>
                      <Avatar size="small" className={styles.avatar} src={currentUser.avatar} />
                      {currentUser.name}
                    </span>
                  </Dropdown>
                ) : <Spin size="small" style={{ marginLeft: 8 }} />}
278 279
              </div>
            </Header>
afc163's avatar
afc163 committed
280
            <Content style={{ margin: '24px 24px 0', height: '100%' }}>
ddcat1115's avatar
ddcat1115 committed
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
              <Switch>
                {
                  getRouteData('BasicLayout').map(item =>
                    (
                      <Route
                        exact={item.exact}
                        key={item.path}
                        path={item.path}
                        component={item.component}
                      />
                    )
                  )
                }
                <Redirect to="/dashboard/analysis" />
              </Switch>
afc163's avatar
afc163 committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309
              <GlobalFooter
                links={[{
                  title: '帮助',
                  href: '',
                }, {
                  title: '隐私',
                  href: '',
                }, {
                  title: '条款',
                  href: '',
                  blankTarget: true,
                }]}
                copyright={<div>Copyright <Icon type="copyright" /> 2017 蚂蚁金服体验技术部出品</div>}
              />
310 311 312 313 314 315 316 317 318 319 320 321 322 323
            </Content>
          </Layout>
        </Layout>
      </DocumentTitle>
    );
  }
}

export default connect(state => ({
  currentUser: state.user.currentUser,
  collapsed: state.global.collapsed,
  fetchingNotices: state.global.fetchingNotices,
  notices: state.global.notices,
}))(BasicLayout);