-
Notifications
You must be signed in to change notification settings - Fork 156
/
crossroads.js
357 lines (297 loc) · 11.6 KB
/
crossroads.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/** @license
* Crossroads.js <http://millermedeiros.github.com/crossroads.js>
* Released under the MIT license
* Author: Miller Medeiros
* Version: 0.6.0 - Build: 77 (2011/08/31 11:12 PM)
*/
(function(def){
def(['signals'], function(signals){
var crossroads,
patternLexer,
BOOL_REGEXP = /^(true|false)$/i;
// Helpers -----------
//====================
function arrayIndexOf(arr, val){
var n = arr.length;
//Array.indexOf doesn't work on IE 6-7
while(n--){
if(arr[n] === val) return n;
}
return -1;
}
function isType(type, val){
return '[object '+ type +']' === Object.prototype.toString.call(val);
}
function isRegExp(val){
return isType('RegExp', val);
}
function isArray(val){
return isType('Array', val);
}
function isFunction(val){
return isType('Function', val);
}
function typecastValue(val){
return (val === null)? val : (
BOOL_REGEXP.test(val)? (val.toLowerCase() === 'true') : (
(val === '' || isNaN(val))? val : parseFloat(val) //parseFloat(null || '') returns NaN, isNaN('') returns false
)
);
}
function typecastArrayValues(values){
var n = values.length,
result = [];
while(n--){
result[n] = typecastValue(values[n]);
}
return result;
}
// Crossroads --------
//====================
/**
* @constructor
*/
function Crossroads(){
this._routes = [];
this.bypassed = new signals.Signal();
this.routed = new signals.Signal();
}
Crossroads.prototype = {
create : function(){
return new Crossroads();
},
shouldTypecast : false,
addRoute : function(pattern, callback, priority){
var route = new Route(pattern, callback, priority, this);
this._sortedInsert(route);
return route;
},
removeRoute : function(route){
var i = arrayIndexOf(this._routes, route);
if(i >= 0) this._routes.splice(i, 1);
route._destroy();
},
removeAllRoutes : function(){
var n = this.getNumRoutes();
while(n--){
this._routes[n]._destroy();
}
this._routes.length = 0;
},
parse : function(request){
request = request || '';
var route = this._getMatchedRoute(request),
params = route? route._getParamsArray(request) : null;
if(route){
params? route.matched.dispatch.apply(route.matched, params) : route.matched.dispatch();
this.routed.dispatch(request, route, params);
}else{
this.bypassed.dispatch(request);
}
},
getNumRoutes : function(){
return this._routes.length;
},
_sortedInsert : function(route){
//simplified insertion sort
var routes = this._routes,
n = routes.length;
do { --n; } while (routes[n] && route._priority <= routes[n]._priority);
routes.splice(n+1, 0, route);
},
_getMatchedRoute : function(request){
var routes = this._routes,
n = routes.length,
route;
while(route = routes[--n]){ //should be decrement loop since higher priorities are added at the end of array
if(route.match(request)) return route;
}
return null;
},
toString : function(){
return '[crossroads numRoutes:'+ this.getNumRoutes() +']';
}
};
//"static" instance
crossroads = new Crossroads();
crossroads.VERSION = '0.6.0';
// Route --------------
//=====================
/**
* @constructor
*/
function Route(pattern, callback, priority, router){
var isRegexPattern = isRegExp(pattern);
this._router = router;
this._pattern = pattern;
this._paramsIds = isRegexPattern? null : patternLexer.getParamIds(this._pattern);
this._optionalParamsIds = isRegexPattern? null : patternLexer.getOptionalParamsIds(this._pattern);
this._matchRegexp = isRegexPattern? pattern : patternLexer.compilePattern(pattern);
this.matched = new signals.Signal();
if(callback) this.matched.add(callback);
this._priority = priority || 0;
}
Route.prototype = {
rules : void(0),
match : function(request){
return this._matchRegexp.test(request) && this._validateParams(request); //validate params even if regexp because of `request_` rule.
},
_validateParams : function(request){
var rules = this.rules,
values = this._getParamValuesObject(request),
prop;
for(prop in rules){
if(rules.hasOwnProperty(prop) && ! this._isValidParam(request, prop, values)){ //filter prototype
return false;
}
}
return true;
},
_isValidParam : function(request, prop, values){
var validationRule = this.rules[prop],
val = values[prop],
isValid;
if ( val == null && this._optionalParamsIds && arrayIndexOf(this._optionalParamsIds, prop) !== -1) {
isValid = true;
}
else if (isRegExp(validationRule)) {
isValid = validationRule.test(val);
}
else if (isArray(validationRule)) {
isValid = arrayIndexOf(validationRule, val || '') !== -1; //adding empty string since optional rule can be empty
}
else if (isFunction(validationRule)) {
isValid = validationRule(val, request, values);
}
return isValid || false; //fail silently if validationRule is from an unsupported type
},
_getParamValuesObject : function(request){
var shouldTypecast = this._router.shouldTypecast,
values = patternLexer.getParamValues(request, this._matchRegexp, shouldTypecast),
o = {},
n = values.length;
while(n--){
o[n] = values[n]; //for RegExp pattern and also alias to normal paths
if(this._paramsIds){
o[this._paramsIds[n]] = values[n];
}
}
o.request_ = shouldTypecast? typecastValue(request) : request;
return o;
},
_getParamsArray : function(request){
var vals = this._getParamValuesObject(request),
norm = this.rules? this.rules.normalize_ : null,
params;
if(isFunction(norm)){
params = norm(request, vals);
} else {
params = patternLexer.getParamValues(request, this._matchRegexp, this._router.shouldTypecast);
}
return params;
},
dispose : function(){
this._router.removeRoute(this);
},
_destroy : function(){
this.matched.dispose();
this.matched = this._pattern = this._matchRegexp = null;
},
toString : function(){
return '[Route pattern:"'+ this._pattern +'", numListeners:'+ this.matched.getNumListeners() +']';
}
};
// Pattern Lexer ------
//=====================
patternLexer = crossroads.patternLexer = (function(){
var ESCAPE_CHARS_REGEXP = /[\\.+*?\^$\[\](){}\/'#]/g, //match chars that should be escaped on string regexp
UNNECESSARY_SLASHES_REGEXP = /\/$/g, //trailing slash
OPTIONAL_SLASHES_REGEXP = /([:}]|\w(?=\/))\/?(:)/g, //slash between `::` or `}:` or `\w:`. $1 = before, $2 = after
REQUIRED_SLASHES_REGEXP = /([:}])\/?(\{)/g,
REQUIRED_PARAMS_REGEXP = /\{([^}]+)\}/g, //match everything between `{ }`
OPTIONAL_PARAMS_REGEXP = /:([^:]+):/g, //match everything between `: :`
PARAMS_REGEXP = /(?:\{|:)([^}:]+)(?:\}|:)/g, //capture everything between `{ }` or `: :`
//used to save params during compile (avoid escaping things that shouldn't be escaped)
SAVE_REQUIRED_PARAMS = '___CR_REQ___',
SAVE_OPTIONAL_PARAMS = '___CR_OPT___',
SAVE_OPTIONAL_SLASHES = '___CR_OPT_SLASH___',
SAVE_REQUIRED_SLASHES = '___CR_REQ_SLASH___',
SAVED_REQUIRED_REGEXP = new RegExp(SAVE_REQUIRED_PARAMS, 'g'),
SAVED_OPTIONAL_REGEXP = new RegExp(SAVE_OPTIONAL_PARAMS, 'g'),
SAVED_OPTIONAL_SLASHES_REGEXP = new RegExp(SAVE_OPTIONAL_SLASHES, 'g'),
SAVED_REQUIRED_SLASHES_REGEXP = new RegExp(SAVE_REQUIRED_SLASHES, 'g');
function getParamIds(pattern){
var ids = [], match;
while(match = PARAMS_REGEXP.exec(pattern)){
ids.push(match[1]);
}
return ids;
}
function getOptionalParamsIds(pattern){
var ids = [], match;
while(match = OPTIONAL_PARAMS_REGEXP.exec(pattern)){
ids.push(match[1]);
}
return ids;
}
function compilePattern(pattern){
pattern = pattern || '';
if(pattern){
pattern = pattern.replace(UNNECESSARY_SLASHES_REGEXP, '');
pattern = tokenize(pattern);
pattern = pattern.replace(ESCAPE_CHARS_REGEXP, '\\$&');
pattern = untokenize(pattern);
}
return new RegExp('^'+ pattern + '/?$'); //trailing slash is optional
}
function tokenize(pattern){
pattern = pattern.replace(OPTIONAL_SLASHES_REGEXP, '$1'+ SAVE_OPTIONAL_SLASHES +'$2');
pattern = pattern.replace(REQUIRED_SLASHES_REGEXP, '$1'+ SAVE_REQUIRED_SLASHES +'$2');
pattern = pattern.replace(OPTIONAL_PARAMS_REGEXP, SAVE_OPTIONAL_PARAMS);
return pattern.replace(REQUIRED_PARAMS_REGEXP, SAVE_REQUIRED_PARAMS);
}
function untokenize(pattern){
pattern = pattern.replace(SAVED_OPTIONAL_SLASHES_REGEXP, '\\/?');
pattern = pattern.replace(SAVED_REQUIRED_SLASHES_REGEXP, '\\/');
pattern = pattern.replace(SAVED_OPTIONAL_REGEXP, '([^\\/]+)?\/?');
return pattern.replace(SAVED_REQUIRED_REGEXP, '([^\\/]+)');
}
function getParamValues(request, regexp, shouldTypecast){
var vals = regexp.exec(request);
if(vals){
vals.shift();
if(shouldTypecast){
vals = typecastArrayValues(vals);
}
}
return vals;
}
//API
return {
getParamIds : getParamIds,
getOptionalParamsIds : getOptionalParamsIds,
getParamValues : getParamValues,
compilePattern : compilePattern
};
}());
return crossroads;
});
}(
// wrapper to run code everywhere
// based on http://bit.ly/c7U4h5
typeof require === 'undefined'?
//Browser (regular script tag)
function(deps, factory){
this.crossroads = factory(signals);
} :
((typeof exports === 'undefined')?
//AMD
function(deps, factory){
define('crossroads', deps, factory);
} :
//CommonJS
function(deps, factory){
module.exports = factory.apply(this, deps.map(require));
}
)
));