BasicLayout.js 8.17 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';
jim's avatar
jim committed
9
import pathToRegexp from 'path-to-regexp';
jljsj's avatar
jljsj committed
10
import { enquireScreen, unenquireScreen } from 'enquire-js';
偏右's avatar
偏右 committed
11
import GlobalHeader from '../components/GlobalHeader';
12
import GlobalFooter from '../components/GlobalFooter';
偏右's avatar
偏右 committed
13
import SiderMenu from '../components/SiderMenu';
afc163's avatar
afc163 committed
14
import NotFound from '../routes/Exception/404';
ddcat1115's avatar
ddcat1115 committed
15
import { getRoutes } from '../utils/utils';
ddcat1115's avatar
ddcat1115 committed
16
import Authorized from '../utils/Authorized';
陈帅's avatar
陈帅 committed
17
import { getMenuData } from '../common/menu';
18
import logo from '../assets/logo.svg';
19

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

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

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
/**
 * 获取面包屑映射
 * @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
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
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
82
let isMobile;
jim's avatar
jim committed
83
enquireScreen(b => {
jiang's avatar
jiang committed
84 85 86
  isMobile = b;
});

87 88
class BasicLayout extends React.PureComponent {
  static childContextTypes = {
ddcat1115's avatar
ddcat1115 committed
89 90
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
jim's avatar
jim committed
91
  };
陈帅's avatar
陈帅 committed
92

jiang's avatar
jiang committed
93 94 95
  state = {
    isMobile,
  };
陈帅's avatar
陈帅 committed
96

97
  getChildContext() {
ddcat1115's avatar
ddcat1115 committed
98 99 100
    const { location, routerData } = this.props;
    return {
      location,
101
      breadcrumbNameMap: getBreadcrumbNameMap(getMenuData(), routerData),
ddcat1115's avatar
ddcat1115 committed
102
    };
103
  }
陈帅's avatar
陈帅 committed
104

jiang's avatar
jiang committed
105
  componentDidMount() {
jljsj's avatar
jljsj committed
106
    this.enquireHandler = enquireScreen(mobile => {
jiang's avatar
jiang committed
107
      this.setState({
afc163's avatar
afc163 committed
108
        isMobile: mobile,
jiang's avatar
jiang committed
109 110
      });
    });
111 112 113
    this.props.dispatch({
      type: 'user/fetchCurrent',
    });
jiang's avatar
jiang committed
114
  }
陈帅's avatar
陈帅 committed
115

jim's avatar
jim committed
116
  componentWillUnmount() {
jljsj's avatar
jljsj committed
117 118
    unenquireScreen(this.enquireHandler);
  }
陈帅's avatar
陈帅 committed
119

120
  getPageTitle() {
ddcat1115's avatar
ddcat1115 committed
121
    const { routerData, location } = this.props;
ddcat1115's avatar
ddcat1115 committed
122 123
    const { pathname } = location;
    let title = 'Ant Design Pro';
jim's avatar
jim committed
124 125 126 127 128 129 130 131 132
    let currRouterData = null;
    // match params path
    Object.keys(routerData).forEach(key => {
      if (pathToRegexp(key).test(pathname)) {
        currRouterData = routerData[key];
      }
    });
    if (currRouterData && currRouterData.name) {
      title = `${currRouterData.name} - Ant Design Pro`;
ddcat1115's avatar
ddcat1115 committed
133
    }
ddcat1115's avatar
ddcat1115 committed
134
    return title;
135
  }
陈帅's avatar
陈帅 committed
136

wangyun122's avatar
wangyun122 committed
137
  getBaseRedirect = () => {
138 139 140
    // According to the url parameter to redirect
    // 这里是重定向的,重定向到 url 的 redirect 参数所示地址
    const urlParams = new URL(window.location.href);
jim's avatar
jim committed
141 142

    const redirect = urlParams.searchParams.get('redirect');
143
    // Remove the parameters in the url
jim's avatar
jim committed
144 145 146 147
    if (redirect) {
      urlParams.searchParams.delete('redirect');
      window.history.replaceState(null, 'redirect', urlParams.href);
    } else {
ddcat1115's avatar
ddcat1115 committed
148 149
      const { routerData } = this.props;
      // get the first authorized route path in routerData
jim's avatar
jim committed
150 151 152
      const authorizedPath = Object.keys(routerData).find(
        item => check(routerData[item].authority, item) && item !== '/'
      );
ddcat1115's avatar
ddcat1115 committed
153
      return authorizedPath;
jim's avatar
jim committed
154
    }
155
    return redirect;
jim's avatar
jim committed
156
  };
陈帅's avatar
陈帅 committed
157

jim's avatar
jim committed
158
  handleMenuCollapse = collapsed => {
159 160 161 162
    this.props.dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
jim's avatar
jim committed
163
  };
陈帅's avatar
陈帅 committed
164

jim's avatar
jim committed
165
  handleNoticeClear = type => {
166 167 168 169 170
    message.success(`清空了${type}`);
    this.props.dispatch({
      type: 'global/clearNotices',
      payload: type,
    });
jim's avatar
jim committed
171
  };
陈帅's avatar
陈帅 committed
172

173
  handleMenuClick = ({ key }) => {
174 175 176 177
    if (key === 'triggerError') {
      this.props.dispatch(routerRedux.push('/exception/trigger'));
      return;
    }
178 179 180 181 182
    if (key === 'logout') {
      this.props.dispatch({
        type: 'login/logout',
      });
    }
jim's avatar
jim committed
183
  };
陈帅's avatar
陈帅 committed
184

jim's avatar
jim committed
185
  handleNoticeVisibleChange = visible => {
186 187 188 189 190
    if (visible) {
      this.props.dispatch({
        type: 'global/fetchNotices',
      });
    }
jim's avatar
jim committed
191
  };
陈帅's avatar
陈帅 committed
192

193
  render() {
偏右's avatar
偏右 committed
194
    const {
jim's avatar
jim committed
195 196 197 198 199 200 201
      currentUser,
      collapsed,
      fetchingNotices,
      notices,
      routerData,
      match,
      location,
偏右's avatar
偏右 committed
202
    } = this.props;
wangyun122's avatar
wangyun122 committed
203
    const bashRedirect = this.getBaseRedirect();
afc163's avatar
afc163 committed
204 205
    const layout = (
      <Layout>
偏右's avatar
偏右 committed
206
        <SiderMenu
ddcat1115's avatar
ddcat1115 committed
207
          logo={logo}
ddcat1115's avatar
ddcat1115 committed
208 209 210 211
          // 不带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
212
          menuData={getMenuData()}
afc163's avatar
afc163 committed
213
          collapsed={collapsed}
偏右's avatar
偏右 committed
214
          location={location}
jiang's avatar
jiang committed
215
          isMobile={this.state.isMobile}
216
          onCollapse={this.handleMenuCollapse}
偏右's avatar
偏右 committed
217
        />
afc163's avatar
afc163 committed
218
        <Layout>
219 220 221 222 223 224 225 226 227 228 229 230 231 232
          <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
233
          <Content style={{ margin: '24px 24px 0', height: '100%' }}>
234
            <Switch>
jim's avatar
jim committed
235 236 237 238 239 240 241 242 243 244 245 246 247
              {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"
                />
              ))}
248 249 250
              <Redirect exact from="/" to={bashRedirect} />
              <Route render={NotFound} />
            </Switch>
afc163's avatar
afc163 committed
251
          </Content>
252 253
          <Footer style={{ padding: 0 }}>
            <GlobalFooter
jim's avatar
jim committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
              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,
                },
              ]}
274
              copyright={
陈帅's avatar
陈帅 committed
275
                <Fragment>
276
                  Copyright <Icon type="copyright" /> 2018 蚂蚁金服体验技术部出品
陈帅's avatar
陈帅 committed
277
                </Fragment>
278 279 280
              }
            />
          </Footer>
281
        </Layout>
afc163's avatar
afc163 committed
282 283 284 285 286 287 288 289
      </Layout>
    );

    return (
      <DocumentTitle title={this.getPageTitle()}>
        <ContainerQuery query={query}>
          {params => <div className={classNames(params)}>{layout}</div>}
        </ContainerQuery>
290 291 292 293 294
      </DocumentTitle>
    );
  }
}

Amumu's avatar
Amumu committed
295
export default connect(({ user, global = {}, loading }) => ({
Andreas Cederström's avatar
Andreas Cederström committed
296 297 298 299
  currentUser: user.currentUser,
  collapsed: global.collapsed,
  fetchingNotices: loading.effects['global/fetchNotices'],
  notices: global.notices,
300
}))(BasicLayout);