-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (82 loc) · 2.51 KB
/
index.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var UrlPattern = require('url-pattern');
var invariant = require('react/lib/invariant');
var Router = {
componentWillMount: function() {
this.setRoute(this.props.path);
this.shouldUpdate = true;
},
componentWillReceiveProps: function(props) {
if (!props.path) return;
this.setRoute(props.path);
this.shouldUpdate = false;
// Allow a callback to do things before changing pages
if (typeof this.routerPageChange == 'function')
this.routerPageChange(function() {
this.shouldUpdate = true;
this.forceUpdate();
}.bind(this));
else
this.shouldUpdate = true;
},
setRoutes: function(routes) {
invariant(routes, 'Must set a routes key on your Reactor class with an \
\n object containing { \'/route\': require(\'page\')');
if (this._routes) return; // already set
this._routesHash = routes;
this._routes = Object.keys(routes).map(function(path) {
return { path: path, to: routes[path] };
});
},
setRoute: function(path) {
if (this.route && path === this.props.path)
return this.route;
this.route = Router.getRoute(path);
return this.route;
},
getRoute: function(path) {
if (!this._routes) this.setRoutes();
invariant(
this._routes,
'Please run setRoutes() with a routes hash \
before calling getRoute()'
);
var path = path || window.location.pathname;
var i, len = this._routes.length;
for (i = 0; i < len; i++) {
var route = this._routes[i];
route.pattern = route.pattern || UrlPattern.newPattern(route.path);
match = route.pattern.match(path);
if (match) {
return { page: route.to, params: match };
}
}
// return 404 page
return { page: this._routesHash['404'] };
},
getPage: function(path) {
return this.getRoute(path).page;
},
getParams: function(path) {
return this.getRoute(path, true).params;
},
replaceParams: function(path, params) {
if (path.indexOf(':') !== -1)
for (var key in params)
path = path.replace(':' + key, params[key]);
return path;
},
rootUrl: function() {
if (this._rootUrl) return this._rootUrl;
try {
var protocol = (this.props.protocol || window.location.protocol) + '//';
}
catch(e) {
var protocol = 'http://';
}
var port = this.props.port ? ':' + this.props.port : '';
var host = this.props.host || window.location.host;
this._rootUrl = protocol + host + port;
return this._rootUrl;
}
};
module.exports = Router;