BasicLayout.js 8.94 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
import React from 'react';
import PropTypes from 'prop-types';
import { Layout, Menu, Icon, Avatar, Dropdown, Tag, message } from 'antd';
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
import { Link, routerRedux } from 'dva/router';
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';
14 15 16 17 18 19 20 21 22

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

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

    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        <Menu.Item><Icon type="user" />个人中心</Menu.Item>
        <Menu.Item><Icon type="setting" />设置</Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout"><Icon type="logout" />退出登录</Menu.Item>
      </Menu>
    );

    const noticeData = this.getNoticeData();

afc163's avatar
afc163 committed
176 177 178 179 180
    // Don't show popup menu when it is been collapsed
    const menuProps = collapsed ? {} : {
      openKeys: this.state.openKeys,
    };

181 182 183 184 185 186 187 188 189 190 191
    return (
      <DocumentTitle title={this.getPageTitle()}>
        <Layout>
          <Sider
            trigger={null}
            collapsible
            collapsed={collapsed}
            collapsedWidth={80}
            breakpoint="md"
            onCollapse={this.onCollapse}
            style={{ minHeight: '100vh' }}
afc163's avatar
afc163 committed
192
            width={256}
193 194 195 196 197 198 199 200 201 202
          >
            <div className={styles.logo}>
              <Link to="/">
                <img src="https://gw.alipayobjects.com/zos/rmsportal/osjtaBtmmQzWRvMbcKeb.svg" alt="logo" />
                <h1>Ant Design Pro</h1>
              </Link>
            </div>
            <Menu
              theme="dark"
              mode="inline"
afc163's avatar
afc163 committed
203
              {...menuProps}
afc163's avatar
afc163 committed
204
              onOpenChange={this.handleOpenChange}
205 206
              selectedKeys={this.getCurrentMenuSelectedKeys()}
              style={{ margin: '24px 0', width: '100%' }}
afc163's avatar
afc163 committed
207
              inlineIndent={32}
208
            >
afc163's avatar
afc163 committed
209
              {this.getNavMenuItems(this.menus)}
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
            </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
225
                    console.log('input', value); // eslint-disable-line
226 227
                  }}
                  onPressEnter={(value) => {
afc163's avatar
afc163 committed
228
                    console.log('enter', value); // eslint-disable-line
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
                  }}
                />
                <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] }}
                >
                  <NoticeIcon.Tab list={noticeData['通知']} title="通知" />
                  <NoticeIcon.Tab list={noticeData['消息']} title="消息" />
                  <NoticeIcon.Tab list={noticeData['待办']} title="待办" />
                </NoticeIcon>
                <Dropdown overlay={menu}>
                  <span className={`${styles.action} ${styles.account}`}>
                    <Avatar size="small" className={styles.avatar} src={currentUser.avatar} />
                    {currentUser.name}
                  </span>
                </Dropdown>
              </div>
            </Header>
afc163's avatar
afc163 committed
254
            <Content style={{ margin: '24px 24px 0', height: '100%' }}>
255
              {children}
afc163's avatar
afc163 committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269
              <GlobalFooter
                links={[{
                  title: '帮助',
                  href: '',
                }, {
                  title: '隐私',
                  href: '',
                }, {
                  title: '条款',
                  href: '',
                  blankTarget: true,
                }]}
                copyright={<div>Copyright <Icon type="copyright" /> 2017 蚂蚁金服体验技术部出品</div>}
              />
270 271 272 273 274 275 276 277 278 279 280 281 282 283
            </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);