Lines of Code | 63 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 1 |
1 | import React from 'react'; |
||
2 | import PropTypes from 'prop-types'; |
||
3 | |||
4 | function getParams(activeRoute, path) { |
||
5 | const splitRoute = activeRoute.split('/'); |
||
6 | const splitPath = path.split('/'); |
||
7 | const params = splitRoute.reduce((param, route, index) => { |
||
8 | if (route.match(':')) { |
||
9 | param[route.substr(1)] = splitPath[index]; |
||
10 | } |
||
11 | return param; |
||
12 | }, {}); |
||
13 | const trueRoute = splitRoute.reduce((newRoute, routeFrag) => { |
||
14 | newRoute.push(params[routeFrag.substr(1)] || routeFrag) |
||
15 | return newRoute; |
||
16 | }, []).join('/'); |
||
17 | return { trueRoute, params }; |
||
18 | } |
||
19 | |||
20 | |||
21 | class Routes extends React.Component { |
||
22 | |||
23 | render () { |
||
24 | const path = this.context.location.path; |
||
25 | let routeParams; |
||
26 | let fourOhFour; |
||
27 | const activeRoute = this.props.routes(path).filter((route) => { |
||
28 | if (route[0] === '*') { |
||
29 | fourOhFour = route; |
||
30 | return false; |
||
31 | } |
||
32 | const hasParams = route[0].match(':'); |
||
33 | if (hasParams) { |
||
34 | const { trueRoute, params } = getParams(route[0], path); |
||
35 | routeParams = params; |
||
36 | return trueRoute === path; |
||
37 | } |
||
38 | return route[0] === path; |
||
39 | }); |
||
40 | |||
41 | const props = JSON.parse(JSON.stringify(this.context)); |
||
42 | |||
43 | if (!activeRoute.length) { |
||
44 | return fourOhFour[1](props); |
||
45 | } |
||
46 | |||
47 | props.location.params = activeRoute[0][0].match(':') ? routeParams : {}; |
||
48 | return activeRoute[0][1](props); |
||
49 | } |
||
50 | } |
||
51 | |||
52 | Routes.contextTypes = { |
||
53 | location: PropTypes.shape({ |
||
54 | path: PropTypes.string, |
||
55 | push: PropTypes.func |
||
56 | }) |
||
57 | }; |
||
58 | |||
59 | Routes.propTypes = { |
||
60 | routes: PropTypes.func |
||
61 | }; |
||
62 | |||
63 | export default Routes; |
||
64 |