BasicLayout.js 7.18 KB
Newer Older
陈帅's avatar
陈帅 committed
1
import React, { Suspense } from 'react';
jim's avatar
jim committed
2
import { Layout } from 'antd';
3
import DocumentTitle from 'react-document-title';
afc163's avatar
afc163 committed
4
import isEqual from 'lodash/isEqual';
陈帅's avatar
陈帅 committed
5
import memoizeOne from 'memoize-one';
6
import { connect } from 'dva';
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';
陈帅's avatar
陈帅 committed
10
import Media from 'react-media';
陈帅's avatar
陈帅 committed
11
import { formatMessage } from 'umi/locale';
12
import Authorized from '@/utils/Authorized';
13
import logo from '../assets/logo.svg';
jim's avatar
jim committed
14 15
import Footer from './Footer';
import Header from './Header';
16
import Context from './MenuContext';
陈帅's avatar
陈帅 committed
17
import Exception403 from '../pages/Exception/403';
陈帅's avatar
陈帅 committed
18 19 20 21 22
import PageLoading from '@/components/PageLoading';
import SiderMenu from '@/components/SiderMenu';

// lazy load SettingDrawer
const SettingDrawer = React.lazy(() => import('@/components/SettingDrawer'));
23

jim's avatar
jim committed
24
const { Content } = Layout;
ddcat1115's avatar
ddcat1115 committed
25

26 27
function mapRoutesToMenu(routes, parentAuthority, parentName) {
  return routes
陈帅's avatar
陈帅 committed
28
    .map(item => {
陈帅's avatar
陈帅 committed
29 30 31 32
      if (!item.name || !item.path) {
        return null;
      }

陈帅's avatar
陈帅 committed
33
      let locale = 'menu';
陈帅's avatar
陈帅 committed
34
      if (parentName) {
陈帅's avatar
陈帅 committed
35
        locale = `${parentName}.${item.name}`;
陈帅's avatar
陈帅 committed
36
      } else {
陈帅's avatar
陈帅 committed
37 38 39
        locale = `menu.${item.name}`;
      }

陈帅's avatar
陈帅 committed
40 41 42 43 44 45 46
      const result = {
        ...item,
        name: formatMessage({ id: locale, defaultMessage: item.name }),
        locale,
        authority: item.authority || parentAuthority,
      };
      if (item.routes) {
47
        const children = mapRoutesToMenu(item.routes, item.authority, locale);
陈帅's avatar
陈帅 committed
48 49 50 51 52
        // Reduce memory usage
        result.children = children;
      }
      delete result.routes;
      return result;
陈帅's avatar
陈帅 committed
53 54
    })
    .filter(item => item);
afc163's avatar
afc163 committed
55 56
}

57
const memoizedMapRoutesToMenu = memoizeOne(mapRoutesToMenu, isEqual);
陈帅's avatar
陈帅 committed
58

afc163's avatar
afc163 committed
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
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
77 78 79 80
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
afc163's avatar
afc163 committed
81 82 83
  },
};

84
class BasicLayout extends React.PureComponent {
陈帅's avatar
陈帅 committed
85 86
  constructor(props) {
    super(props);
陈帅's avatar
陈帅 committed
87
    this.getPageTitle = memoizeOne(this.getPageTitle);
88 89
    this.getBreadcrumbNameMap = memoizeOne(this.getBreadcrumbNameMap, isEqual);
    this.breadcrumbNameMap = this.getBreadcrumbNameMap();
陈帅's avatar
陈帅 committed
90
    this.matchParamsPath = memoizeOne(this.matchParamsPath, isEqual);
陈帅's avatar
陈帅 committed
91
  }
92 93

  state = {
陈帅's avatar
陈帅 committed
94
    menuData: this.getMenuData(),
95 96 97
  };

  componentDidMount() {
afc163's avatar
afc163 committed
98 99 100 101 102 103 104
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetchCurrent',
    });
    dispatch({
      type: 'setting/getSetting',
    });
105 106
  }

107 108 109
  componentDidUpdate(preProps) {
    // After changing to phone mode,
    // if collapsed is true, you need to click twice to display
110
    this.breadcrumbNameMap = this.getBreadcrumbNameMap();
陈帅's avatar
陈帅 committed
111
    const { collapsed, isMobile } = this.props;
112 113 114
    if (isMobile && !preProps.isMobile && !collapsed) {
      this.handleMenuCollapse(false);
    }
115 116 117 118 119 120
  }

  componentWillUnmount() {
    cancelAnimationFrame(this.renderRef);
  }

jim's avatar
jim committed
121
  getContext() {
陈帅's avatar
陈帅 committed
122
    const { location } = this.props;
ddcat1115's avatar
ddcat1115 committed
123 124
    return {
      location,
陈帅's avatar
陈帅 committed
125
      breadcrumbNameMap: this.breadcrumbNameMap,
ddcat1115's avatar
ddcat1115 committed
126
    };
127
  }
128

129 130
  getMenuData() {
    const {
陈帅's avatar
陈帅 committed
131
      route: { routes, authority },
132
    } = this.props;
133
    return memoizedMapRoutesToMenu(routes, authority);
134 135 136 137 138 139 140 141
  }

  /**
   * 获取面包屑映射
   * @param {Object} menuData 菜单配置
   */
  getBreadcrumbNameMap() {
    const routerMap = {};
142
    const flattenMenuData = data => {
143 144
      data.forEach(menuItem => {
        if (menuItem.children) {
145
          flattenMenuData(menuItem.children);
146 147 148 149 150
        }
        // Reduce memory usage
        routerMap[menuItem.path] = menuItem;
      });
    };
151
    flattenMenuData(this.getMenuData());
152 153 154
    return routerMap;
  }

陈帅's avatar
陈帅 committed
155 156 157 158
  matchParamsPath = pathname => {
    const pathKey = Object.keys(this.breadcrumbNameMap).find(key =>
      pathToRegexp(key).test(pathname)
    );
陈帅's avatar
陈帅 committed
159
    return this.breadcrumbNameMap[pathKey];
陈帅's avatar
陈帅 committed
160 161
  };

陈帅's avatar
陈帅 committed
162
  getPageTitle = pathname => {
陈帅's avatar
陈帅 committed
163 164
    const currRouterData = this.matchParamsPath(pathname);

陈帅's avatar
陈帅 committed
165 166
    if (!currRouterData) {
      return 'Ant Design Pro';
ddcat1115's avatar
ddcat1115 committed
167
    }
xiaoiver's avatar
xiaoiver committed
168
    const pageName = formatMessage({
陈帅's avatar
陈帅 committed
169 170 171
      id: currRouterData.locale || currRouterData.name,
      defaultMessage: currRouterData.name,
    });
xiaoiver's avatar
xiaoiver committed
172
    return `${pageName} - Ant Design Pro`;
陈帅's avatar
陈帅 committed
173
  };
陈帅's avatar
陈帅 committed
174

jim's avatar
jim committed
175
  getLayoutStyle = () => {
陈帅's avatar
陈帅 committed
176
    const { fixSiderbar, isMobile, collapsed, layout } = this.props;
177
    if (fixSiderbar && layout !== 'topmenu' && !isMobile) {
jim's avatar
jim committed
178
      return {
179
        paddingLeft: collapsed ? '80px' : '256px',
jim's avatar
jim committed
180 181 182 183
      };
    }
    return null;
  };
陈帅's avatar
陈帅 committed
184

jim's avatar
jim committed
185 186 187 188 189 190 191
  getContentStyle = () => {
    const { fixedHeader } = this.props;
    return {
      margin: '24px 24px 0',
      paddingTop: fixedHeader ? 64 : 0,
    };
  };
陈帅's avatar
陈帅 committed
192

jim's avatar
jim committed
193
  handleMenuCollapse = collapsed => {
陈帅's avatar
陈帅 committed
194 195
    const { dispatch } = this.props;
    dispatch({
196 197 198
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
jim's avatar
jim committed
199
  };
200

陈帅's avatar
陈帅 committed
201
  renderSettingDrawer = () => {
kennylbj's avatar
kennylbj committed
202 203
    // Do not render SettingDrawer in production
    // unless it is deployed in preview.pro.ant.design as demo
陈帅's avatar
陈帅 committed
204
    if (process.env.NODE_ENV === 'production' && APP_TYPE !== 'site') {
205 206 207
      return null;
    }
    return <SettingDrawer />;
陈帅's avatar
陈帅 committed
208
  };
209

210
  render() {
陈帅's avatar
陈帅 committed
211
    const {
afc163's avatar
afc163 committed
212
      navTheme,
陈帅's avatar
陈帅 committed
213
      layout: PropsLayout,
愚道's avatar
愚道 committed
214
      children,
陈帅's avatar
陈帅 committed
215
      location: { pathname },
陈帅's avatar
陈帅 committed
216
      isMobile,
陈帅's avatar
陈帅 committed
217
    } = this.props;
陈帅's avatar
陈帅 committed
218
    const { menuData } = this.state;
陈帅's avatar
陈帅 committed
219
    const isTop = PropsLayout === 'topmenu';
陈帅's avatar
陈帅 committed
220
    const routerConfig = this.matchParamsPath(pathname);
afc163's avatar
afc163 committed
221 222
    const layout = (
      <Layout>
jim's avatar
jim committed
223
        {isTop && !isMobile ? null : (
jim's avatar
jim committed
224 225 226
          <SiderMenu
            logo={logo}
            Authorized={Authorized}
afc163's avatar
afc163 committed
227
            theme={navTheme}
jim's avatar
jim committed
228
            onCollapse={this.handleMenuCollapse}
229
            menuData={menuData}
230
            isMobile={isMobile}
jim's avatar
jim committed
231
            {...this.props}
jim's avatar
jim committed
232 233
          />
        )}
陈帅's avatar
陈帅 committed
234 235 236 237 238 239
        <Layout
          style={{
            ...this.getLayoutStyle(),
            minHeight: '100vh',
          }}
        >
240 241 242 243
          <Header
            menuData={menuData}
            handleMenuCollapse={this.handleMenuCollapse}
            logo={logo}
244
            isMobile={isMobile}
245 246
            {...this.props}
          />
陈帅's avatar
陈帅 committed
247
          <Content style={this.getContentStyle()}>
陈帅's avatar
陈帅 committed
248 249 250 251
            <Authorized
              authority={routerConfig && routerConfig.authority}
              noMatch={<Exception403 />}
            >
陈帅's avatar
陈帅 committed
252 253 254
              {children}
            </Authorized>
          </Content>
jim's avatar
jim committed
255
          <Footer />
256
        </Layout>
afc163's avatar
afc163 committed
257 258 259
      </Layout>
    );
    return (
陈帅's avatar
陈帅 committed
260 261 262 263 264 265 266 267 268 269
      <React.Fragment>
        <DocumentTitle title={this.getPageTitle(pathname)}>
          <ContainerQuery query={query}>
            {params => (
              <Context.Provider value={this.getContext()}>
                <div className={classNames(params)}>{layout}</div>
              </Context.Provider>
            )}
          </ContainerQuery>
        </DocumentTitle>
陈帅's avatar
陈帅 committed
270
        <Suspense fallback={<PageLoading />}>{this.renderSettingDrawer()}</Suspense>
陈帅's avatar
陈帅 committed
271
      </React.Fragment>
272 273 274 275
    );
  }
}

jim's avatar
jim committed
276
export default connect(({ global, setting }) => ({
Andreas Cederström's avatar
Andreas Cederström committed
277
  collapsed: global.collapsed,
jim's avatar
jim committed
278 279
  layout: setting.layout,
  ...setting,
陈帅's avatar
陈帅 committed
280 281 282 283 284
}))(props => (
  <Media query="(max-width: 599px)">
    {isMobile => <BasicLayout {...props} isMobile={isMobile} />}
  </Media>
));