BasicLayout.js 8.29 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
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,
yoyo837's avatar
yoyo837 committed
79 80 81 82
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
afc163's avatar
afc163 committed
83 84 85
  },
};

jiang's avatar
jiang committed
86
let isMobile;
jim's avatar
jim committed
87
enquireScreen(b => {
jiang's avatar
jiang committed
88 89 90
  isMobile = b;
});

91 92 93 94 95 96 97
@connect(({ user, global = {}, loading }) => ({
  currentUser: user.currentUser,
  collapsed: global.collapsed,
  fetchingNotices: loading.effects['global/fetchNotices'],
  notices: global.notices,
}))
export default class BasicLayout extends React.PureComponent {
98
  static childContextTypes = {
ddcat1115's avatar
ddcat1115 committed
99 100
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
jim's avatar
jim committed
101
  };
陈帅's avatar
陈帅 committed
102

jiang's avatar
jiang committed
103 104 105
  state = {
    isMobile,
  };
陈帅's avatar
陈帅 committed
106

107
  getChildContext() {
ddcat1115's avatar
ddcat1115 committed
108 109 110
    const { location, routerData } = this.props;
    return {
      location,
111
      breadcrumbNameMap: getBreadcrumbNameMap(getMenuData(), routerData),
ddcat1115's avatar
ddcat1115 committed
112
    };
113
  }
陈帅's avatar
陈帅 committed
114

jiang's avatar
jiang committed
115
  componentDidMount() {
jljsj's avatar
jljsj committed
116
    this.enquireHandler = enquireScreen(mobile => {
jiang's avatar
jiang committed
117
      this.setState({
afc163's avatar
afc163 committed
118
        isMobile: mobile,
jiang's avatar
jiang committed
119 120
      });
    });
121 122
    const { dispatch } = this.props;
    dispatch({
123 124
      type: 'user/fetchCurrent',
    });
jiang's avatar
jiang committed
125
  }
陈帅's avatar
陈帅 committed
126

jim's avatar
jim committed
127
  componentWillUnmount() {
jljsj's avatar
jljsj committed
128 129
    unenquireScreen(this.enquireHandler);
  }
陈帅's avatar
陈帅 committed
130

131
  getPageTitle() {
ddcat1115's avatar
ddcat1115 committed
132
    const { routerData, location } = this.props;
ddcat1115's avatar
ddcat1115 committed
133 134
    const { pathname } = location;
    let title = 'Ant Design Pro';
jim's avatar
jim committed
135
    // match params path
yoyo837's avatar
find  
yoyo837 committed
136 137 138
    const currRouterData = (Object.entries(routerData).find(([key]) =>
      pathToRegexp(key).test(pathname)
    ) || [])[1];
jim's avatar
jim committed
139 140
    if (currRouterData && currRouterData.name) {
      title = `${currRouterData.name} - Ant Design Pro`;
ddcat1115's avatar
ddcat1115 committed
141
    }
ddcat1115's avatar
ddcat1115 committed
142
    return title;
143
  }
陈帅's avatar
陈帅 committed
144

wangyun122's avatar
wangyun122 committed
145
  getBaseRedirect = () => {
146 147 148
    // According to the url parameter to redirect
    // 这里是重定向的,重定向到 url 的 redirect 参数所示地址
    const urlParams = new URL(window.location.href);
jim's avatar
jim committed
149 150

    const redirect = urlParams.searchParams.get('redirect');
151
    // Remove the parameters in the url
jim's avatar
jim committed
152 153 154 155
    if (redirect) {
      urlParams.searchParams.delete('redirect');
      window.history.replaceState(null, 'redirect', urlParams.href);
    } else {
ddcat1115's avatar
ddcat1115 committed
156 157
      const { routerData } = this.props;
      // get the first authorized route path in routerData
jim's avatar
jim committed
158 159 160
      const authorizedPath = Object.keys(routerData).find(
        item => check(routerData[item].authority, item) && item !== '/'
      );
ddcat1115's avatar
ddcat1115 committed
161
      return authorizedPath;
jim's avatar
jim committed
162
    }
163
    return redirect;
jim's avatar
jim committed
164
  };
陈帅's avatar
陈帅 committed
165

jim's avatar
jim committed
166
  handleMenuCollapse = collapsed => {
167 168
    const { dispatch } = this.props;
    dispatch({
169 170 171
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
jim's avatar
jim committed
172
  };
陈帅's avatar
陈帅 committed
173

jim's avatar
jim committed
174
  handleNoticeClear = type => {
175
    message.success(`清空了${type}`);
176 177
    const { dispatch } = this.props;
    dispatch({
178 179 180
      type: 'global/clearNotices',
      payload: type,
    });
jim's avatar
jim committed
181
  };
陈帅's avatar
陈帅 committed
182

183
  handleMenuClick = ({ key }) => {
184
    const { dispatch } = this.props;
185
    if (key === 'triggerError') {
186
      dispatch(routerRedux.push('/exception/trigger'));
187 188
      return;
    }
189
    if (key === 'logout') {
190
      dispatch({
191 192 193
        type: 'login/logout',
      });
    }
jim's avatar
jim committed
194
  };
陈帅's avatar
陈帅 committed
195

jim's avatar
jim committed
196
  handleNoticeVisibleChange = visible => {
197
    const { dispatch } = this.props;
198
    if (visible) {
199
      dispatch({
200 201 202
        type: 'global/fetchNotices',
      });
    }
jim's avatar
jim committed
203
  };
陈帅's avatar
陈帅 committed
204

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

    return (
      <DocumentTitle title={this.getPageTitle()}>
        <ContainerQuery query={query}>
          {params => <div className={classNames(params)}>{layout}</div>}
        </ContainerQuery>
303 304 305 306
      </DocumentTitle>
    );
  }
}