BasicLayout.js 7.42 KB
Newer Older
jim's avatar
jim committed
1 2
import React from 'react';
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';
afc163's avatar
afc163 committed
10
import { enquireScreen, unenquireScreen } from 'enquire-js';
陈帅's avatar
陈帅 committed
11
import { formatMessage } from 'umi/locale';
12 13
import SiderMenu from '@/components/SiderMenu';
import Authorized from '@/utils/Authorized';
14
import SettingDrawer from '@/components/SettingDrawer';
15
import logo from '../assets/logo.svg';
jim's avatar
jim committed
16 17
import Footer from './Footer';
import Header from './Header';
18
import Context from './MenuContext';
陈帅's avatar
陈帅 committed
19
import Exception403 from '../pages/Exception/403';
20

jim's avatar
jim committed
21
const { Content } = Layout;
ddcat1115's avatar
ddcat1115 committed
22

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

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

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

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

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

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

  state = {
    rendering: true,
afc163's avatar
afc163 committed
92
    isMobile: false,
陈帅's avatar
陈帅 committed
93
    menuData: this.getMenuData(),
94 95 96
  };

  componentDidMount() {
afc163's avatar
afc163 committed
97 98 99 100 101 102 103
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetchCurrent',
    });
    dispatch({
      type: 'setting/getSetting',
    });
104 105 106 107 108
    this.renderRef = requestAnimationFrame(() => {
      this.setState({
        rendering: false,
      });
    });
afc163's avatar
afc163 committed
109 110 111 112 113 114 115 116
    this.enquireHandler = enquireScreen(mobile => {
      const { isMobile } = this.state;
      if (isMobile !== mobile) {
        this.setState({
          isMobile: mobile,
        });
      }
    });
117 118
  }

119 120 121
  componentDidUpdate(preProps) {
    // After changing to phone mode,
    // if collapsed is true, you need to click twice to display
122
    this.breadcrumbNameMap = this.getBreadcrumbNameMap();
123 124 125 126 127
    const { isMobile } = this.state;
    const { collapsed } = this.props;
    if (isMobile && !preProps.isMobile && !collapsed) {
      this.handleMenuCollapse(false);
    }
128 129 130 131
  }

  componentWillUnmount() {
    cancelAnimationFrame(this.renderRef);
afc163's avatar
afc163 committed
132
    unenquireScreen(this.enquireHandler);
133 134
  }

jim's avatar
jim committed
135
  getContext() {
陈帅's avatar
陈帅 committed
136
    const { location } = this.props;
ddcat1115's avatar
ddcat1115 committed
137 138
    return {
      location,
陈帅's avatar
陈帅 committed
139
      breadcrumbNameMap: this.breadcrumbNameMap,
ddcat1115's avatar
ddcat1115 committed
140
    };
141
  }
142

143 144
  getMenuData() {
    const {
陈帅's avatar
陈帅 committed
145
      route: { routes, authority },
146
    } = this.props;
147
    return memoizedMapRoutesToMenu(routes, authority);
148 149 150 151 152 153 154 155
  }

  /**
   * 获取面包屑映射
   * @param {Object} menuData 菜单配置
   */
  getBreadcrumbNameMap() {
    const routerMap = {};
156
    const flattenMenuData = data => {
157 158
      data.forEach(menuItem => {
        if (menuItem.children) {
159
          flattenMenuData(menuItem.children);
160 161 162 163 164
        }
        // Reduce memory usage
        routerMap[menuItem.path] = menuItem;
      });
    };
165
    flattenMenuData(this.getMenuData());
166 167 168
    return routerMap;
  }

陈帅's avatar
陈帅 committed
169 170 171 172
  matchParamsPath = pathname => {
    const pathKey = Object.keys(this.breadcrumbNameMap).find(key =>
      pathToRegexp(key).test(pathname)
    );
陈帅's avatar
陈帅 committed
173
    return this.breadcrumbNameMap[pathKey];
陈帅's avatar
陈帅 committed
174 175
  };

陈帅's avatar
陈帅 committed
176
  getPageTitle = pathname => {
陈帅's avatar
陈帅 committed
177 178
    const currRouterData = this.matchParamsPath(pathname);

陈帅's avatar
陈帅 committed
179 180
    if (!currRouterData) {
      return 'Ant Design Pro';
ddcat1115's avatar
ddcat1115 committed
181
    }
xiaoiver's avatar
xiaoiver committed
182
    const pageName = formatMessage({
陈帅's avatar
陈帅 committed
183 184 185
      id: currRouterData.locale || currRouterData.name,
      defaultMessage: currRouterData.name,
    });
xiaoiver's avatar
xiaoiver committed
186
    return `${pageName} - Ant Design Pro`;
陈帅's avatar
陈帅 committed
187
  };
陈帅's avatar
陈帅 committed
188

jim's avatar
jim committed
189
  getLayoutStyle = () => {
190
    const { isMobile } = this.state;
陈帅's avatar
陈帅 committed
191
    const { fixSiderbar, collapsed, layout } = this.props;
192
    if (fixSiderbar && layout !== 'topmenu' && !isMobile) {
jim's avatar
jim committed
193
      return {
194
        paddingLeft: collapsed ? '80px' : '256px',
jim's avatar
jim committed
195 196 197 198
      };
    }
    return null;
  };
陈帅's avatar
陈帅 committed
199

jim's avatar
jim committed
200 201 202 203 204 205 206
  getContentStyle = () => {
    const { fixedHeader } = this.props;
    return {
      margin: '24px 24px 0',
      paddingTop: fixedHeader ? 64 : 0,
    };
  };
陈帅's avatar
陈帅 committed
207

jim's avatar
jim committed
208
  handleMenuCollapse = collapsed => {
陈帅's avatar
陈帅 committed
209 210
    const { dispatch } = this.props;
    dispatch({
211 212 213
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
jim's avatar
jim committed
214
  };
215

216
  renderSettingDrawer() {
kennylbj's avatar
kennylbj committed
217 218
    // Do not render SettingDrawer in production
    // unless it is deployed in preview.pro.ant.design as demo
219 220 221 222 223 224 225
    const { rendering } = this.state;
    if ((rendering || process.env.NODE_ENV === 'production') && APP_TYPE !== 'site') {
      return null;
    }
    return <SettingDrawer />;
  }

226
  render() {
陈帅's avatar
陈帅 committed
227
    const {
afc163's avatar
afc163 committed
228
      navTheme,
陈帅's avatar
陈帅 committed
229
      layout: PropsLayout,
愚道's avatar
愚道 committed
230
      children,
陈帅's avatar
陈帅 committed
231
      location: { pathname },
陈帅's avatar
陈帅 committed
232
    } = this.props;
陈帅's avatar
陈帅 committed
233
    const { isMobile, menuData } = this.state;
陈帅's avatar
陈帅 committed
234
    const isTop = PropsLayout === 'topmenu';
陈帅's avatar
陈帅 committed
235
    const routerConfig = this.matchParamsPath(pathname);
afc163's avatar
afc163 committed
236 237
    const layout = (
      <Layout>
jim's avatar
jim committed
238
        {isTop && !isMobile ? null : (
jim's avatar
jim committed
239 240 241
          <SiderMenu
            logo={logo}
            Authorized={Authorized}
afc163's avatar
afc163 committed
242
            theme={navTheme}
jim's avatar
jim committed
243
            onCollapse={this.handleMenuCollapse}
244
            menuData={menuData}
245
            isMobile={isMobile}
jim's avatar
jim committed
246
            {...this.props}
jim's avatar
jim committed
247 248
          />
        )}
陈帅's avatar
陈帅 committed
249 250 251 252 253 254
        <Layout
          style={{
            ...this.getLayoutStyle(),
            minHeight: '100vh',
          }}
        >
255 256 257 258
          <Header
            menuData={menuData}
            handleMenuCollapse={this.handleMenuCollapse}
            logo={logo}
259
            isMobile={isMobile}
260 261
            {...this.props}
          />
陈帅's avatar
陈帅 committed
262
          <Content style={this.getContentStyle()}>
陈帅's avatar
陈帅 committed
263 264 265 266
            <Authorized
              authority={routerConfig && routerConfig.authority}
              noMatch={<Exception403 />}
            >
陈帅's avatar
陈帅 committed
267 268 269
              {children}
            </Authorized>
          </Content>
jim's avatar
jim committed
270
          <Footer />
271
        </Layout>
afc163's avatar
afc163 committed
272 273 274
      </Layout>
    );
    return (
陈帅's avatar
陈帅 committed
275 276 277 278 279 280 281 282 283 284
      <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>
285
        {this.renderSettingDrawer()}
陈帅's avatar
陈帅 committed
286
      </React.Fragment>
287 288 289 290
    );
  }
}

jim's avatar
jim committed
291
export default connect(({ global, setting }) => ({
Andreas Cederström's avatar
Andreas Cederström committed
292
  collapsed: global.collapsed,
jim's avatar
jim committed
293 294
  layout: setting.layout,
  ...setting,
陈帅's avatar
陈帅 committed
295
}))(BasicLayout);