BasicLayout.js 7.82 KB
Newer Older
陈帅's avatar
陈帅 committed
1
import React, { Fragment } from 'react';
2
import PropTypes from 'prop-types';
3
import { Layout, Icon, message } from 'antd';
4 5
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';
6
import { Route, Redirect, Switch, routerRedux } from 'dva/router';
afc163's avatar
afc163 committed
7 8
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
jiang's avatar
jiang committed
9
import { enquireScreen } from 'enquire-js';
偏右's avatar
偏右 committed
10
import GlobalHeader from '../components/GlobalHeader';
11
import GlobalFooter from '../components/GlobalFooter';
偏右's avatar
偏右 committed
12
import SiderMenu from '../components/SiderMenu';
afc163's avatar
afc163 committed
13
import NotFound from '../routes/Exception/404';
ddcat1115's avatar
ddcat1115 committed
14
import { getRoutes } from '../utils/utils';
ddcat1115's avatar
ddcat1115 committed
15
import Authorized from '../utils/Authorized';
陈帅's avatar
陈帅 committed
16
import { getMenuData } from '../common/menu';
17
import logo from '../assets/logo.svg';
18

19
const { Content, Header, Footer } = Layout;
ddcat1115's avatar
ddcat1115 committed
20
const { AuthorizedRoute, check } = Authorized;
ddcat1115's avatar
ddcat1115 committed
21

陈帅's avatar
陈帅 committed
22 23 24 25
/**
 * 根据菜单取得重定向地址.
 */
const redirectData = [];
jim's avatar
jim committed
26
const getRedirect = item => {
陈帅's avatar
陈帅 committed
27 28 29
  if (item && item.children) {
    if (item.children[0] && item.children[0].path) {
      redirectData.push({
jim's avatar
jim committed
30 31
        from: `${item.path}`,
        to: `${item.children[0].path}`,
陈帅's avatar
陈帅 committed
32
      });
jim's avatar
jim committed
33
      item.children.forEach(children => {
陈帅's avatar
陈帅 committed
34 35 36 37 38 39 40
        getRedirect(children);
      });
    }
  }
};
getMenuData().forEach(getRedirect);

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
/**
 * 获取面包屑映射
 * @param {Object} menuData 菜单配置
 * @param {Object} routerData 路由配置
 */
const getBreadcrumbNameMap = (menuData, routerData) => {
  const result = {};
  const childResult = {};
  for (const i of menuData) {
    if (!routerData[i.path]) {
      result[i.path] = i;
    }
    if (i.children) {
      Object.assign(childResult, getBreadcrumbNameMap(i.children, routerData));
    }
  }
  return Object.assign({}, routerData, result, childResult);
};

afc163's avatar
afc163 committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
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,
  },
};

jiang's avatar
jiang committed
81
let isMobile;
jim's avatar
jim committed
82
enquireScreen(b => {
jiang's avatar
jiang committed
83 84 85
  isMobile = b;
});

86 87
class BasicLayout extends React.PureComponent {
  static childContextTypes = {
ddcat1115's avatar
ddcat1115 committed
88 89
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
jim's avatar
jim committed
90
  };
jiang's avatar
jiang committed
91 92 93
  state = {
    isMobile,
  };
94
  getChildContext() {
ddcat1115's avatar
ddcat1115 committed
95 96 97
    const { location, routerData } = this.props;
    return {
      location,
98
      breadcrumbNameMap: getBreadcrumbNameMap(getMenuData(), routerData),
ddcat1115's avatar
ddcat1115 committed
99
    };
100
  }
jiang's avatar
jiang committed
101
  componentDidMount() {
jim's avatar
jim committed
102
    enquireScreen(mobile => {
jiang's avatar
jiang committed
103
      this.setState({
afc163's avatar
afc163 committed
104
        isMobile: mobile,
jiang's avatar
jiang committed
105 106
      });
    });
107 108 109
    this.props.dispatch({
      type: 'user/fetchCurrent',
    });
jiang's avatar
jiang committed
110
  }
111
  getPageTitle() {
ddcat1115's avatar
ddcat1115 committed
112
    const { routerData, location } = this.props;
ddcat1115's avatar
ddcat1115 committed
113 114
    const { pathname } = location;
    let title = 'Ant Design Pro';
ddcat1115's avatar
ddcat1115 committed
115 116 117
    if (routerData[pathname] && routerData[pathname].name) {
      title = `${routerData[pathname].name} - Ant Design Pro`;
    }
ddcat1115's avatar
ddcat1115 committed
118
    return title;
119
  }
120 121 122 123
  getBashRedirect = () => {
    // According to the url parameter to redirect
    // 这里是重定向的,重定向到 url 的 redirect 参数所示地址
    const urlParams = new URL(window.location.href);
jim's avatar
jim committed
124 125

    const redirect = urlParams.searchParams.get('redirect');
126
    // Remove the parameters in the url
jim's avatar
jim committed
127 128 129 130
    if (redirect) {
      urlParams.searchParams.delete('redirect');
      window.history.replaceState(null, 'redirect', urlParams.href);
    } else {
ddcat1115's avatar
ddcat1115 committed
131 132
      const { routerData } = this.props;
      // get the first authorized route path in routerData
jim's avatar
jim committed
133 134 135
      const authorizedPath = Object.keys(routerData).find(
        item => check(routerData[item].authority, item) && item !== '/'
      );
ddcat1115's avatar
ddcat1115 committed
136
      return authorizedPath;
jim's avatar
jim committed
137
    }
138
    return redirect;
jim's avatar
jim committed
139 140
  };
  handleMenuCollapse = collapsed => {
141 142 143 144
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
jim's avatar
jim committed
145 146
  };
  handleNoticeClear = type => {
147 148 149 150 151
    message.success(`清空了${type}`);
    this.props.dispatch({
      type: 'global/clearNotices',
      payload: type,
    });
jim's avatar
jim committed
152
  };
153
  handleMenuClick = ({ key }) => {
154 155 156 157
    if (key === 'triggerError') {
      this.props.dispatch(routerRedux.push('/exception/trigger'));
      return;
    }
158 159 160 161 162
    if (key === 'logout') {
      this.props.dispatch({
        type: 'login/logout',
      });
    }
jim's avatar
jim committed
163 164
  };
  handleNoticeVisibleChange = visible => {
165 166 167 168 169
    if (visible) {
      this.props.dispatch({
        type: 'global/fetchNotices',
      });
    }
jim's avatar
jim committed
170
  };
171
  render() {
偏右's avatar
偏右 committed
172
    const {
jim's avatar
jim committed
173 174 175 176 177 178 179
      currentUser,
      collapsed,
      fetchingNotices,
      notices,
      routerData,
      match,
      location,
偏右's avatar
偏右 committed
180
    } = this.props;
181
    const bashRedirect = this.getBashRedirect();
afc163's avatar
afc163 committed
182 183
    const layout = (
      <Layout>
偏右's avatar
偏右 committed
184
        <SiderMenu
ddcat1115's avatar
ddcat1115 committed
185
          logo={logo}
ddcat1115's avatar
ddcat1115 committed
186 187 188 189
          // 不带Authorized参数的情况下如果没有权限,会强制跳到403界面
          // If you do not have the Authorized parameter
          // you will be forced to jump to the 403 interface without permission
          Authorized={Authorized}
ddcat1115's avatar
ddcat1115 committed
190
          menuData={getMenuData()}
afc163's avatar
afc163 committed
191
          collapsed={collapsed}
偏右's avatar
偏右 committed
192
          location={location}
jiang's avatar
jiang committed
193
          isMobile={this.state.isMobile}
194
          onCollapse={this.handleMenuCollapse}
偏右's avatar
偏右 committed
195
        />
afc163's avatar
afc163 committed
196
        <Layout>
197 198 199 200 201 202 203 204 205 206 207 208 209 210
          <Header style={{ padding: 0 }}>
            <GlobalHeader
              logo={logo}
              currentUser={currentUser}
              fetchingNotices={fetchingNotices}
              notices={notices}
              collapsed={collapsed}
              isMobile={this.state.isMobile}
              onNoticeClear={this.handleNoticeClear}
              onCollapse={this.handleMenuCollapse}
              onMenuClick={this.handleMenuClick}
              onNoticeVisibleChange={this.handleNoticeVisibleChange}
            />
          </Header>
afc163's avatar
afc163 committed
211
          <Content style={{ margin: '24px 24px 0', height: '100%' }}>
212
            <Switch>
jim's avatar
jim committed
213 214 215 216 217 218 219 220 221 222 223 224 225
              {redirectData.map(item => (
                <Redirect key={item.from} exact from={item.from} to={item.to} />
              ))}
              {getRoutes(match.path, routerData).map(item => (
                <AuthorizedRoute
                  key={item.key}
                  path={item.path}
                  component={item.component}
                  exact={item.exact}
                  authority={item.authority}
                  redirectPath="/exception/403"
                />
              ))}
226 227 228
              <Redirect exact from="/" to={bashRedirect} />
              <Route render={NotFound} />
            </Switch>
afc163's avatar
afc163 committed
229
          </Content>
230 231
          <Footer style={{ padding: 0 }}>
            <GlobalFooter
jim's avatar
jim committed
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
              links={[
                {
                  key: 'Pro 首页',
                  title: 'Pro 首页',
                  href: 'http://pro.ant.design',
                  blankTarget: true,
                },
                {
                  key: 'github',
                  title: <Icon type="github" />,
                  href: 'https://github.com/ant-design/ant-design-pro',
                  blankTarget: true,
                },
                {
                  key: 'Ant Design',
                  title: 'Ant Design',
                  href: 'http://ant.design',
                  blankTarget: true,
                },
              ]}
252
              copyright={
陈帅's avatar
陈帅 committed
253
                <Fragment>
254
                  Copyright <Icon type="copyright" /> 2018 蚂蚁金服体验技术部出品
陈帅's avatar
陈帅 committed
255
                </Fragment>
256 257 258
              }
            />
          </Footer>
259
        </Layout>
afc163's avatar
afc163 committed
260 261 262 263 264 265 266 267
      </Layout>
    );

    return (
      <DocumentTitle title={this.getPageTitle()}>
        <ContainerQuery query={query}>
          {params => <div className={classNames(params)}>{layout}</div>}
        </ContainerQuery>
268 269 270 271 272
      </DocumentTitle>
    );
  }
}

Andreas Cederström's avatar
Andreas Cederström committed
273 274 275 276 277
export default connect(({ user, global, loading }) => ({
  currentUser: user.currentUser,
  collapsed: global.collapsed,
  fetchingNotices: loading.effects['global/fetchNotices'],
  notices: global.notices,
278
}))(BasicLayout);