BasicLayout.js 12.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';
6
import { Link, Route, Redirect, Switch } from 'dva/router';
7 8
import moment from 'moment';
import groupBy from 'lodash/groupBy';
afc163's avatar
afc163 committed
9 10
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
afc163's avatar
afc163 committed
11
import Debounce from 'lodash-decorators/debounce';
12 13 14
import HeaderSearch from '../components/HeaderSearch';
import NoticeIcon from '../components/NoticeIcon';
import GlobalFooter from '../components/GlobalFooter';
afc163's avatar
afc163 committed
15 16
import NotFound from '../routes/Exception/404';
import styles from './BasicLayout.less';
17
import logo from '../assets/logo.svg';
18 19 20 21

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

afc163's avatar
afc163 committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
  },
};

43 44
class BasicLayout extends React.PureComponent {
  static childContextTypes = {
ddcat1115's avatar
ddcat1115 committed
45 46
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
47
  }
afc163's avatar
afc163 committed
48 49 50
  constructor(props) {
    super(props);
    // 把一级 Layout 的 children 作为菜单项
51
    this.menus = props.navData.reduce((arr, current) => arr.concat(current.children), []);
afc163's avatar
afc163 committed
52 53 54
    this.state = {
      openKeys: this.getDefaultCollapsedSubMenus(props),
    };
afc163's avatar
afc163 committed
55
  }
56
  getChildContext() {
57
    const { location, navData, getRouteData } = this.props;
ddcat1115's avatar
ddcat1115 committed
58
    const routeData = getRouteData('BasicLayout');
59
    const firstMenuData = navData.reduce((arr, current) => arr.concat(current.children), []);
ddcat1115's avatar
ddcat1115 committed
60
    const menuData = this.getMenuData(firstMenuData, '');
ddcat1115's avatar
ddcat1115 committed
61
    const breadcrumbNameMap = {};
ddcat1115's avatar
ddcat1115 committed
62

ddcat1115's avatar
ddcat1115 committed
63
    routeData.concat(menuData).forEach((item) => {
afc163's avatar
afc163 committed
64 65 66 67
      breadcrumbNameMap[item.path] = {
        name: item.name,
        component: item.component,
      };
ddcat1115's avatar
ddcat1115 committed
68 69
    });
    return { location, breadcrumbNameMap };
70 71 72 73 74 75
  }
  componentDidMount() {
    this.props.dispatch({
      type: 'user/fetchCurrent',
    });
  }
afc163's avatar
afc163 committed
76
  componentWillUnmount() {
afc163's avatar
afc163 committed
77
    this.triggerResizeEvent.cancel();
afc163's avatar
afc163 committed
78
  }
79 80 81 82 83 84 85 86
  onCollapse = (collapsed) => {
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  }
  onMenuClick = ({ key }) => {
    if (key === 'logout') {
ddcat1115's avatar
fix #52  
ddcat1115 committed
87 88 89
      this.props.dispatch({
        type: 'login/logout',
      });
90 91
    }
  }
ddcat1115's avatar
ddcat1115 committed
92 93 94 95 96 97 98 99 100 101
  getMenuData = (data, parentPath) => {
    let arr = [];
    data.forEach((item) => {
      if (item.children) {
        arr.push({ path: `${parentPath}/${item.path}`, name: item.name });
        arr = arr.concat(this.getMenuData(item.children, `${parentPath}/${item.path}`));
      }
    });
    return arr;
  }
afc163's avatar
afc163 committed
102 103
  getDefaultCollapsedSubMenus(props) {
    const currentMenuSelectedKeys = [...this.getCurrentMenuSelectedKeys(props)];
104
    currentMenuSelectedKeys.splice(-1, 1);
afc163's avatar
afc163 committed
105 106 107
    if (currentMenuSelectedKeys.length === 0) {
      return ['dashboard'];
    }
108 109
    return currentMenuSelectedKeys;
  }
afc163's avatar
afc163 committed
110 111
  getCurrentMenuSelectedKeys(props) {
    const { location: { pathname } } = props || this.props;
112 113
    const keys = pathname.split('/').slice(1);
    if (keys.length === 1 && keys[0] === '') {
afc163's avatar
afc163 committed
114
      return [this.menus[0].key];
115 116 117 118
    }
    return keys;
  }
  getNavMenuItems(menusData, parentPath = '') {
afc163's avatar
afc163 committed
119 120 121
    if (!menusData) {
      return [];
    }
122 123 124 125
    return menusData.map((item) => {
      if (!item.name) {
        return null;
      }
afc163's avatar
afc163 committed
126 127 128 129 130 131
      let itemPath;
      if (item.path.indexOf('http') === 0) {
        itemPath = item.path;
      } else {
        itemPath = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
      }
132 133 134 135
      if (item.children && item.children.some(child => child.name)) {
        return (
          <SubMenu
            title={
afc163's avatar
afc163 committed
136 137 138 139 140 141
              item.icon ? (
                <span>
                  <Icon type={item.icon} />
                  <span>{item.name}</span>
                </span>
              ) : item.name
142 143 144 145 146 147 148
            }
            key={item.key || item.path}
          >
            {this.getNavMenuItems(item.children, itemPath)}
          </SubMenu>
        );
      }
afc163's avatar
afc163 committed
149
      const icon = item.icon && <Icon type={item.icon} />;
150 151
      return (
        <Menu.Item key={item.key || item.path}>
afc163's avatar
afc163 committed
152 153 154 155 156 157
          {
            /^https?:\/\//.test(itemPath) ? (
              <a href={itemPath} target={item.target}>
                {icon}<span>{item.name}</span>
              </a>
            ) : (
afc163's avatar
afc163 committed
158 159 160 161 162
              <Link
                to={itemPath}
                target={item.target}
                replace={itemPath === this.props.location.pathname}
              >
afc163's avatar
afc163 committed
163 164
                {icon}<span>{item.name}</span>
              </Link>
WhatAKitty's avatar
WhatAKitty committed
165
            )
afc163's avatar
afc163 committed
166
          }
167 168 169 170 171
        </Menu.Item>
      );
    });
  }
  getPageTitle() {
172
    const { location, getRouteData } = this.props;
ddcat1115's avatar
ddcat1115 committed
173 174
    const { pathname } = location;
    let title = 'Ant Design Pro';
ddcat1115's avatar
ddcat1115 committed
175
    getRouteData('BasicLayout').forEach((item) => {
ddcat1115's avatar
ddcat1115 committed
176 177
      if (item.path === pathname) {
        title = `${item.name} - Ant Design Pro`;
178
      }
ddcat1115's avatar
ddcat1115 committed
179 180
    });
    return title;
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
  }
  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
198
          todo: '',
199 200
          processing: 'blue',
          urgent: 'red',
afc163's avatar
afc163 committed
201
          doing: 'gold',
202
        })[newNotice.status];
afc163's avatar
afc163 committed
203
        newNotice.extra = <Tag color={color} style={{ marginRight: 0 }}>{newNotice.extra}</Tag>;
204 205 206 207 208
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  }
afc163's avatar
afc163 committed
209
  handleOpenChange = (openKeys) => {
valleykid's avatar
valleykid committed
210 211
    const lastOpenKey = openKeys[openKeys.length - 1];
    const isMainMenu = this.menus.some(
valleykid's avatar
valleykid committed
212
      item => lastOpenKey && (item.key === lastOpenKey || item.path === lastOpenKey)
valleykid's avatar
valleykid committed
213
    );
afc163's avatar
afc163 committed
214
    this.setState({
valleykid's avatar
valleykid committed
215
      openKeys: isMainMenu ? [lastOpenKey] : [...openKeys],
afc163's avatar
afc163 committed
216 217
    });
  }
218 219 220 221 222 223
  toggle = () => {
    const { collapsed } = this.props;
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: !collapsed,
    });
afc163's avatar
afc163 committed
224 225 226 227 228 229 230
    this.triggerResizeEvent();
  }
  @Debounce(600)
  triggerResizeEvent() { // eslint-disable-line
    const event = document.createEvent('HTMLEvents');
    event.initEvent('resize', true, false);
    window.dispatchEvent(event);
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
  }
  handleNoticeClear = (type) => {
    message.success(`清空了${type}`);
    this.props.dispatch({
      type: 'global/clearNotices',
      payload: type,
    });
  }
  handleNoticeVisibleChange = (visible) => {
    if (visible) {
      this.props.dispatch({
        type: 'global/fetchNotices',
      });
    }
  }
  render() {
247
    const { currentUser, collapsed, fetchingNotices, getRouteData } = this.props;
248 249 250

    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
afc163's avatar
afc163 committed
251 252
        <Menu.Item disabled><Icon type="user" />个人中心</Menu.Item>
        <Menu.Item disabled><Icon type="setting" />设置</Menu.Item>
253 254 255 256 257 258
        <Menu.Divider />
        <Menu.Item key="logout"><Icon type="logout" />退出登录</Menu.Item>
      </Menu>
    );
    const noticeData = this.getNoticeData();

afc163's avatar
afc163 committed
259 260 261 262 263
    // Don't show popup menu when it is been collapsed
    const menuProps = collapsed ? {} : {
      openKeys: this.state.openKeys,
    };

afc163's avatar
afc163 committed
264 265 266 267 268 269 270 271 272 273 274 275 276
    const layout = (
      <Layout>
        <Sider
          trigger={null}
          collapsible
          collapsed={collapsed}
          breakpoint="md"
          onCollapse={this.onCollapse}
          width={256}
          className={styles.sider}
        >
          <div className={styles.logo}>
            <Link to="/">
277
              <img src={logo} alt="logo" />
afc163's avatar
afc163 committed
278 279 280 281 282 283 284 285 286 287
              <h1>Ant Design Pro</h1>
            </Link>
          </div>
          <Menu
            theme="dark"
            mode="inline"
            {...menuProps}
            onOpenChange={this.handleOpenChange}
            selectedKeys={this.getCurrentMenuSelectedKeys()}
            style={{ margin: '16px 0', width: '100%' }}
288
          >
afc163's avatar
afc163 committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
            {this.getNavMenuItems(this.menus)}
          </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) => {
                  console.log('input', value); // eslint-disable-line
                }}
                onPressEnter={(value) => {
                  console.log('enter', value); // eslint-disable-line
                }}
310
              />
afc163's avatar
afc163 committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
              <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="通知"
                  emptyText="你已查看所有通知"
                  emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
                />
                <NoticeIcon.Tab
                  list={noticeData['消息']}
                  title="消息"
                  emptyText="您已读完所有消息"
                  emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
333
                />
afc163's avatar
afc163 committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
                <NoticeIcon.Tab
                  list={noticeData['待办']}
                  title="待办"
                  emptyText="你已完成所有待办"
                  emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
                />
              </NoticeIcon>
              {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 }} />}
            </div>
          </Header>
          <Content style={{ margin: '24px 24px 0', height: '100%' }}>
afc163's avatar
afc163 committed
352 353 354 355 356 357 358 359 360 361 362 363
            <div style={{ minHeight: 'calc(100vh - 260px)' }}>
              <Switch>
                {
                  getRouteData('BasicLayout').map(item =>
                    (
                      <Route
                        exact={item.exact}
                        key={item.path}
                        path={item.path}
                        component={item.component}
                      />
                    )
ddcat1115's avatar
ddcat1115 committed
364
                  )
afc163's avatar
afc163 committed
365 366 367 368 369
                }
                <Redirect exact from="/" to="/dashboard/analysis" />
                <Route component={NotFound} />
              </Switch>
            </div>
afc163's avatar
afc163 committed
370 371
            <GlobalFooter
              links={[{
afc163's avatar
afc163 committed
372
                title: 'Pro 首页',
afc163's avatar
afc163 committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
                href: 'http://pro.ant.design',
                blankTarget: true,
              }, {
                title: 'GitHub',
                href: 'https://github.com/ant-design/ant-design-pro',
                blankTarget: true,
              }, {
                title: 'Ant Design',
                href: 'http://ant.design',
                blankTarget: true,
              }]}
              copyright={
                <div>
                  Copyright <Icon type="copyright" /> 2017 蚂蚁金服体验技术部出品
                </div>
              }
            />
          </Content>
391
        </Layout>
afc163's avatar
afc163 committed
392 393 394 395 396 397 398 399
      </Layout>
    );

    return (
      <DocumentTitle title={this.getPageTitle()}>
        <ContainerQuery query={query}>
          {params => <div className={classNames(params)}>{layout}</div>}
        </ContainerQuery>
400 401 402 403 404 405 406 407 408 409 410
      </DocumentTitle>
    );
  }
}

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