-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathurlhub.js
311 lines (262 loc) · 6.76 KB
/
urlhub.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
var parser = require('path-to-regexp');
var qs = require('mini-querystring');
/*
routes = {
path: '/hola',
cb: fn,
children: []
}
*/
// parseUrl function needed for testing
var parseUrl;
if( typeof window !== 'undefined' ){
parseUrl = function( url ){
var a = document.createElement('a');
a.href = url;
return a;
};
}
// The lib
var urlhub = {
create: function( options ){
return new Urlhub( options );
},
joinUrls: joinUrls // just for testing never used, see helpers at bottom
}
// The class
var Urlhub = function( options ){
if( !options || !options.strategy ){
throw new Error('Router needs an strategy to listen to url changes.');
}
var s = options.strategy;
var ops = {};
Object.keys( options ).forEach( function( key ){
if( key === 'strategy' ) return;
ops[key] = options[key];
});
s.init && s.init( ops );
this.strategy = s;
// Callbacks before the route change
this.obc = [];
// Callbacks to be called on route change
this.cbs = [];
}
var prototype = {
setRoutes: function( routes ){
this.routes = this.parseRoutes( routes );
},
// Route translation methods
parseRoutes: function( routes, parent ){
if( !routes ) console.warn( 'No routes provided to parseRoutes' );
if( !routes.length ){
routes = [routes];
}
var parsedRoutes = [],
me = this
;
routes.forEach( function(r){
var path = joinUrls(parent, r.path);
var params = [],
parsed = {
regex: parser( path, params ),
id: path,
cb: r.cb
}
;
parsed.params = params.map( function(p){ return p.name } );
if( r.children && r.children.length ){
parsed.childRegex = parser( path, [], {end: false} );
parsed.children = me.parseRoutes( r.children, path );
}
parsedRoutes.push( parsed );
});
return parsedRoutes;
},
match: function( location, candidates, isChild ){
var i = 0,
url = sanitizeUrl( location ),
path, found, match, c
;
if( !candidates ){
candidates = this.routes;
}
var parsed = (this.strategy.parseUrl || parseUrl)( url );
path = parsed.pathname;
// Normalize pathname
if( path[0] !== '/' ){
path = '/' + path;
}
while( i < candidates.length && !found ){
c = candidates[i];
if( c.childRegex ){
//console.log( 'failed', c.regex, path );
found = c.childRegex.exec( path );
if( found ){
match = this.match( url, c.children, true );
if( match.matches.length ){
match.matches = [c.cb].concat( match.matches );
match.matchIds = [c.id].concat( match.matchIds );
return match; // The recursive call will give all the info
}
else {
found = false;
}
}
}
found = c.regex.exec( path );
if( found ){
found = {
id: c.id, cb: c.cb, params: found.slice(1)
};
}
if( !found ){
i++;
}
}
var matches = [];
var matchIds = [];
if( found ){
matches.push( found.cb )
matchIds.push( found.id )
}
else if( !isChild ){
console.error('There is no route match for ' + location);
}
match = {
matches: matches,
matchIds: matchIds,
pathname: path,
search: parsed.search,
query: qs.parse( parsed.search ),
hash: parsed.hash,
route: found && found.id || false,
params: {}
};
if( found ){
c.params.forEach( function( p, i ){
match.params[ p ] = found.params[i];
});
}
return match;
},
// Routing methods
start: function(){
var me = this;
this.strategy.onChange( function(){
var change = me.checkChange();
if( !change.next ) return;
if( change.current !== change.next ){
me.strategy.replace( change.next );
}
else {
me.location = change.nextLocation;
me.cbs.forEach( function( cb ){
cb( change.nextLocation );
});
}
});
this.strategy.start();
this.location = this.match( this.strategy.getLocation() );
return this.location;
},
stop: function(){
this.strategy.onChange( function(){} );
},
refresh: function(){
var change = this.checkChange();
change.next && change.current !== change.next && this.strategy.replace( change.next );
},
checkChange: function(){
var current = this.strategy.getLocation(),
nextLocation = this.runOnBeforeChange( this.match(current) ),
next = nextLocation && (nextLocation.pathname + nextLocation.search + nextLocation.hash)
;
return {current:current, next:next, nextLocation:nextLocation};
},
runOnBeforeChange: function( match ){
var me = this;
this.obc.forEach( function(cb){
if( match ){
match = cb( match );
if( typeof match === 'string' ){
match = me.match( match );
}
}
});
return match;
},
onBeforeChange: function( cb ){
this.obc.push( cb );
},
onChange: function( cb ){
this.cbs.push( cb );
},
push: function( location ){
this.updateLocation('push', location);
},
replace: function( location ){
this.updateLocation('replace', location);
},
back: function(){
this.strategy.back();
},
updateLocation: function( method, location ){
var current = this.strategy.getLocation();
var next;
if(typeof location === 'string'){
next = location;
}
else {
next = mergeLocations( this.match( current ), location );
}
var nextLocation = this.runOnBeforeChange( this.match(next) );
if( nextLocation ){
next = nextLocation.pathname + nextLocation.search + nextLocation.hash;
if( current !== next ){
this.strategy[ method ]( next );
}
}
}
}
for( var method in prototype ) Urlhub.prototype[ method ] = prototype[method];
module.exports = urlhub;
/********* HELPERS */
function joinUrls( one, two ){
var first = sanitizeUrl(one),
second = sanitizeUrl(two)
;
if( !one ) return second;
if( !two ) return first;
if( first === '/'){
return second;
}
else if( second === '/' ){
return first;
}
else {
return first + second;
}
}
function sanitizeUrl( url ){
if( !url ) return '/';
var sanitized = url;
if( sanitized[ sanitized.length - 1 ] === '/' ){
sanitized = sanitized.slice(0, sanitized.length - 1);
}
if( sanitized[0] !== '/' ){
sanitized = '/' + sanitized;
}
return sanitized;
}
function mergeLocations( prev, next ){
var location = Object.assign( prev, next ),
search = location.search
;
if( Object.keys(location.query).length ){
search = '?' + qs.stringify( location.query );
}
else {
search = '';
}
return location.pathname + search + location.hash;
}