-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
matchRoute.js
82 lines (70 loc) · 1.98 KB
/
matchRoute.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { inBrowser } from "../utils/environment-helpers";
import { validateString } from "../utils/validation-helpers";
/**
*
* @param {import('./constructRoutes').ResolvedRoutesConfig} resolvedRoutesConfig
* @param {string} path
* @returns {import('./constructRoutes').ResolvedRoutesConfig}
*/
export function matchRoute(resolvedRoutesConfig, pathMatch) {
validateString("path", pathMatch);
const result = { ...resolvedRoutesConfig };
const baseWithoutSlash = resolvedRoutesConfig.base.slice(
0,
resolvedRoutesConfig.base.length - 1
);
if (pathMatch.indexOf(baseWithoutSlash) === 0) {
const origin = inBrowser ? window.location.origin : "http://localhost";
const location = new URL(resolvePath(origin, pathMatch));
result.routes = recurseRoutes(location, resolvedRoutesConfig.routes);
} else {
result.routes = [];
}
return result;
}
/**
*
* @param {URL} location
* @param {Array<import('./constructRoutes').ResolvedRouteChild>} routes
*/
function recurseRoutes(location, routes) {
const result = [];
routes.forEach((route) => {
if (route.type === "application") {
result.push(route);
} else if (route.type === "route") {
if (route.activeWhen(location)) {
result.push({
...route,
routes: recurseRoutes(location, route.routes),
});
}
} else if (Array.isArray(route.routes)) {
result.push({
...route,
routes: recurseRoutes(location, route.routes),
});
} else {
result.push(route);
}
});
return result;
}
export function resolvePath(prefix, path) {
let result;
if (prefix.substr(-1) === "/") {
if (path[0] === "/") {
result = prefix + path.slice(1);
} else {
result = prefix + path;
}
} else if (path[0] === "/") {
result = prefix + path;
} else {
result = prefix + "/" + path;
}
if (result.substr(-1) === "/" && result.length > 1) {
result = result.slice(0, result.length - 1);
}
return result;
}