handie-react-starter-umi
Version:
`handie-react-starter-antd` + `umi`
68 lines (67 loc) • 2.17 kB
JavaScript
import { pathToRegexp, match, compile } from 'path-to-regexp';
// @ts-ignore
import { history } from 'umi';
import { isPlainObject, } from 'handie-react-starter-antd';
let allRoutes = [];
let routeMap = {};
function resolveRouteMap(routes, map) {
return routes.reduce((prev, cur) => {
const acc = Object.assign(Object.assign({}, prev), { [cur.name || cur.path]: cur });
return (cur.routes || []).length > 0 ? resolveRouteMap(cur.routes, acc) : acc;
}, map);
}
function setRoutes(routes) {
allRoutes = routes;
routeMap = resolveRouteMap(allRoutes, {});
}
function findRouteDeeply(pathname, routes = allRoutes) {
const route = { current: undefined, ancestors: [] };
for (let i = 0; i < routes.length; i++) {
const r = routes[i];
const dynamicMatched = pathToRegexp(r.path).exec(pathname);
if (dynamicMatched || r.path === pathname) {
route.current = r;
break;
}
if ((r.routes || []).length === 0) {
continue;
}
const found = findRouteDeeply(pathname, r.routes);
if (found.current) {
route.current = found.current;
route.ancestors.unshift(r, ...found.ancestors);
break;
}
}
return route;
}
function getLocation() {
const { location: { pathname, hash, query = {} }, } = history;
const { current, ancestors } = findRouteDeeply(pathname);
const { params = {} } = match(current.path, { decode: decodeURIComponent })(pathname) || {};
return {
name: current.name,
path: pathname,
rawPath: current.path,
hash,
query,
params,
ancestors,
};
}
function resolveHistoryParams(location) {
let resolved;
if (isPlainObject(location)) {
const { name, path, query, params = {} } = location;
resolved = {
pathname: compile(name ? routeMap[name].path : path)(params),
query,
state: params,
};
}
else {
resolved = { pathname: location };
}
return resolved;
}
export { setRoutes, findRouteDeeply, getLocation, resolveHistoryParams };