router.js 7.32 KB
Newer Older
1 2
import React, { createElement } from 'react';
import { Spin } from 'antd';
陈帅's avatar
陈帅 committed
3
import pathToRegexp from 'path-to-regexp';
4
import Loadable from 'react-loadable';
ddcat1115's avatar
ddcat1115 committed
5 6
import { getMenuData } from './menu';

偏右's avatar
偏右 committed
7 8
let routerDataCache;

9 10 11 12 13 14 15
const getRouterDataCache = app => {
  if (!routerDataCache) {
    routerDataCache = getRouterData(app);
  }
  return routerDataCache;
};

jim's avatar
jim committed
16
const modelNotExisted = (app, model) =>
偏右's avatar
偏右 committed
17
  // eslint-disable-next-line
PKAQ's avatar
PKAQ committed
18 19
  !app._models.some(({ namespace }) => {
    return namespace === model.substring(model.lastIndexOf('/') + 1);
jim's avatar
jim committed
20
  });
偏右's avatar
偏右 committed
21

ddcat1115's avatar
ddcat1115 committed
22
// wrapper of dynamic
偏右's avatar
偏右 committed
23
const dynamicWrapper = (app, models, component) => {
24 25 26 27 28 29 30 31
  // register models
  models.forEach(model => {
    if (modelNotExisted(app, model)) {
      // eslint-disable-next-line
      app.model(require(`../models/${model}`).default);
    }
  });

偏右's avatar
偏右 committed
32 33 34
  // () => require('module')
  // transformed by babel-plugin-dynamic-import-node-sync
  if (component.toString().indexOf('.then(') < 0) {
jim's avatar
jim committed
35
    return props => {
偏右's avatar
偏右 committed
36 37
      return createElement(component().default, {
        ...props,
38
        routerData: getRouterDataCache(app),
偏右's avatar
偏右 committed
39 40 41 42
      });
    };
  }
  // () => import('module')
43 44
  return Loadable({
    loader: () => {
jim's avatar
jim committed
45
      return component().then(raw => {
偏右's avatar
偏右 committed
46
        const Component = raw.default || raw;
jim's avatar
jim committed
47 48 49
        return props =>
          createElement(Component, {
            ...props,
50
            routerData: getRouterDataCache(app),
jim's avatar
jim committed
51
          });
偏右's avatar
偏右 committed
52 53
      });
    },
54 55 56
    loading: () => {
      return <Spin size="large" className="global-spin" />;
    },
偏右's avatar
偏右 committed
57 58
  });
};
ddcat1115's avatar
ddcat1115 committed
59 60 61

function getFlatMenuData(menus) {
  let keys = {};
jim's avatar
jim committed
62
  menus.forEach(item => {
ddcat1115's avatar
ddcat1115 committed
63
    if (item.children) {
ddcat1115's avatar
ddcat1115 committed
64
      keys[item.path] = { ...item };
ddcat1115's avatar
ddcat1115 committed
65 66
      keys = { ...keys, ...getFlatMenuData(item.children) };
    } else {
ddcat1115's avatar
ddcat1115 committed
67
      keys[item.path] = { ...item };
ddcat1115's avatar
ddcat1115 committed
68 69 70 71 72
    }
  });
  return keys;
}

73 74 75 76 77 78 79 80 81 82
function findMenuKey(menuData, path) {
  const menuKey = Object.keys(menuData).find(key => pathToRegexp(path).test(key));
  if (menuKey == null) {
    if (path === '/') {
      return null;
    }
    const lastIdx = path.lastIndexOf('/');
    if (lastIdx < 0) {
      return null;
    }
yoyo837's avatar
update  
yoyo837 committed
83 84 85
    if (lastIdx === 0) {
      return findMenuKey(menuData, '/');
    }
86 87 88 89 90 91
    // 如果没有,使用上一层的配置
    return findMenuKey(menuData, path.substr(0, lastIdx));
  }
  return menuKey;
}

jim's avatar
jim committed
92
export const getRouterData = app => {
ddcat1115's avatar
ddcat1115 committed
93
  const routerConfig = {
ddcat1115's avatar
ddcat1115 committed
94 95 96 97 98 99 100 101 102 103
    '/': {
      component: dynamicWrapper(app, ['user', 'login'], () => import('../layouts/BasicLayout')),
    },
    '/dashboard/analysis': {
      component: dynamicWrapper(app, ['chart'], () => import('../routes/Dashboard/Analysis')),
    },
    '/dashboard/monitor': {
      component: dynamicWrapper(app, ['monitor'], () => import('../routes/Dashboard/Monitor')),
    },
    '/dashboard/workplace': {
jim's avatar
jim committed
104 105 106
      component: dynamicWrapper(app, ['project', 'activities', 'chart'], () =>
        import('../routes/Dashboard/Workplace')
      ),
ddcat1115's avatar
ddcat1115 committed
107 108
      // hideInBreadcrumb: true,
      // name: '工作台',
ddcat1115's avatar
ddcat1115 committed
109
      // authority: 'admin',
ddcat1115's avatar
ddcat1115 committed
110 111 112 113 114 115 116
    },
    '/form/basic-form': {
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/BasicForm')),
    },
    '/form/step-form': {
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/StepForm')),
    },
WhatAKitty's avatar
WhatAKitty committed
117
    '/form/step-form/info': {
jim's avatar
jim committed
118
      name: '分步表单(填写转账信息)',
WhatAKitty's avatar
WhatAKitty committed
119 120
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/StepForm/Step1')),
    },
ddcat1115's avatar
ddcat1115 committed
121
    '/form/step-form/confirm': {
jim's avatar
jim committed
122
      name: '分步表单(确认转账信息)',
ddcat1115's avatar
ddcat1115 committed
123 124 125
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/StepForm/Step2')),
    },
    '/form/step-form/result': {
jim's avatar
jim committed
126
      name: '分步表单(完成)',
ddcat1115's avatar
ddcat1115 committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/StepForm/Step3')),
    },
    '/form/advanced-form': {
      component: dynamicWrapper(app, ['form'], () => import('../routes/Forms/AdvancedForm')),
    },
    '/list/table-list': {
      component: dynamicWrapper(app, ['rule'], () => import('../routes/List/TableList')),
    },
    '/list/basic-list': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/BasicList')),
    },
    '/list/card-list': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/CardList')),
    },
    '/list/search': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/List')),
    },
    '/list/search/projects': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/Projects')),
    },
    '/list/search/applications': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/Applications')),
    },
    '/list/search/articles': {
      component: dynamicWrapper(app, ['list'], () => import('../routes/List/Articles')),
    },
    '/profile/basic': {
      component: dynamicWrapper(app, ['profile'], () => import('../routes/Profile/BasicProfile')),
    },
    '/profile/advanced': {
jim's avatar
jim committed
157 158 159
      component: dynamicWrapper(app, ['profile'], () =>
        import('../routes/Profile/AdvancedProfile')
      ),
ddcat1115's avatar
ddcat1115 committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    },
    '/result/success': {
      component: dynamicWrapper(app, [], () => import('../routes/Result/Success')),
    },
    '/result/fail': {
      component: dynamicWrapper(app, [], () => import('../routes/Result/Error')),
    },
    '/exception/403': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/403')),
    },
    '/exception/404': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/404')),
    },
    '/exception/500': {
      component: dynamicWrapper(app, [], () => import('../routes/Exception/500')),
    },
陈帅's avatar
陈帅 committed
176
    '/exception/trigger': {
jim's avatar
jim committed
177 178 179
      component: dynamicWrapper(app, ['error'], () =>
        import('../routes/Exception/triggerException')
      ),
陈帅's avatar
陈帅 committed
180
    },
ddcat1115's avatar
ddcat1115 committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    '/user': {
      component: dynamicWrapper(app, [], () => import('../layouts/UserLayout')),
    },
    '/user/login': {
      component: dynamicWrapper(app, ['login'], () => import('../routes/User/Login')),
    },
    '/user/register': {
      component: dynamicWrapper(app, ['register'], () => import('../routes/User/Register')),
    },
    '/user/register-result': {
      component: dynamicWrapper(app, [], () => import('../routes/User/RegisterResult')),
    },
    // '/user/:id': {
    //   component: dynamicWrapper(app, [], () => import('../routes/User/SomeComponent')),
    // },
  };
  // Get name from ./menu.js or just set it in the router data.
  const menuData = getFlatMenuData(getMenuData());
陈帅's avatar
陈帅 committed
199 200 201

  // Route configuration data
  // eg. {name,authority ...routerConfig }
ddcat1115's avatar
ddcat1115 committed
202
  const routerData = {};
陈帅's avatar
陈帅 committed
203
  // The route matches the menu
jim's avatar
jim committed
204
  Object.keys(routerConfig).forEach(path => {
陈帅's avatar
陈帅 committed
205 206
    // Regular match item name
    // eg.  router /user/:id === /user/chen
207
    const menuKey = findMenuKey(menuData, path);
陈帅's avatar
陈帅 committed
208 209 210 211 212 213 214 215 216 217 218 219 220
    let menuItem = {};
    // If menuKey is not empty
    if (menuKey) {
      menuItem = menuData[menuKey];
    }
    let router = routerConfig[path];
    // If you need to configure complex parameter routing,
    // https://github.com/ant-design/ant-design-pro-site/blob/master/docs/router-and-nav.md#%E5%B8%A6%E5%8F%82%E6%95%B0%E7%9A%84%E8%B7%AF%E7%94%B1%E8%8F%9C%E5%8D%95
    // eg . /list/:type/user/info/:id
    router = {
      ...router,
      name: router.name || menuItem.name,
      authority: router.authority || menuItem.authority,
221
      hideInBreadcrumb: router.hideInBreadcrumb || menuItem.hideInBreadcrumb,
ddcat1115's avatar
ddcat1115 committed
222
    };
陈帅's avatar
陈帅 committed
223
    routerData[path] = router;
ddcat1115's avatar
ddcat1115 committed
224
  });
ddcat1115's avatar
ddcat1115 committed
225
  return routerData;
ddcat1115's avatar
ddcat1115 committed
226
};