BasicLayout.js 7.43 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

afc163's avatar
afc163 committed
23
// Conversion router to menu.
24
function formatter(data, parentAuthority, parentName) {
陈帅's avatar
陈帅 committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
  return data
    .map(item => {
      let locale = 'menu';
      if (parentName && item.name) {
        locale = `${parentName}.${item.name}`;
      } else if (item.name) {
        locale = `menu.${item.name}`;
      } else if (parentName) {
        locale = parentName;
      }
      if (item.path) {
        const result = {
          ...item,
          locale,
          authority: item.authority || parentAuthority,
        };
        if (item.routes) {
42
          const children = formatter(item.routes, item.authority, locale);
陈帅's avatar
陈帅 committed
43 44 45 46 47 48 49 50 51 52
          // Reduce memory usage
          result.children = children;
        }
        delete result.routes;
        return result;
      }

      return null;
    })
    .filter(item => item);
afc163's avatar
afc163 committed
53 54
}

陈帅's avatar
陈帅 committed
55 56
const memoizeOneFormatter = memoizeOne(formatter, isEqual);

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

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

  state = {
    rendering: true,
afc163's avatar
afc163 committed
93
    isMobile: false,
陈帅'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
    this.renderRef = requestAnimationFrame(() => {
      this.setState({
        rendering: false,
      });
    });
afc163's avatar
afc163 committed
110 111 112 113 114 115 116 117
    this.enquireHandler = enquireScreen(mobile => {
      const { isMobile } = this.state;
      if (isMobile !== mobile) {
        this.setState({
          isMobile: mobile,
        });
      }
    });
118 119
  }

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

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

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

144 145 146 147
  getMenuData() {
    const {
      route: { routes },
    } = this.props;
陈帅's avatar
陈帅 committed
148
    return memoizeOneFormatter(routes);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
  }

  /**
   * 获取面包屑映射
   * @param {Object} menuData 菜单配置
   */
  getBreadcrumbNameMap() {
    const routerMap = {};
    const mergeMenuAndRouter = data => {
      data.forEach(menuItem => {
        if (menuItem.children) {
          mergeMenuAndRouter(menuItem.children);
        }
        // Reduce memory usage
        routerMap[menuItem.path] = menuItem;
      });
    };
    mergeMenuAndRouter(this.getMenuData());
    return routerMap;
  }

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

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

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

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

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

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

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

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

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