-
Notifications
You must be signed in to change notification settings - Fork 25
/
jquery.routes.js
339 lines (319 loc) · 9.39 KB
/
jquery.routes.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
/*
* jQuery routes - v2.0
* Routing in javascript using hashchange event.
* http://thorsteinsson.is/projects/jquery-routes/
*
* Copyright (c) 2010 Ægir Þorsteinsson
* Licensed under a Creative Commons Attribution 3.0 license
* http://creativecommons.org/licenses/by/3.0/
*/
(function($) {
var routecount = 0,
datelpad = function(d) {
d = d + '';
return d.length < 2 ? '0' + d : d;
},
legacyDateTypes = {
'date': {
regexp: /(\d{1,2})\-(\d{1,2})\-(\d{4})/,
parse: function(d, dd, mm, yyyy) {
return new Date(yyyy, datelpad(mm - 1), datelpad(dd));
},
stringify: function(date) {
return datelpad(date.getDate()) + '-' + datelpad(date.getMonth() + 1) + '-' + date.getFullYear();
}
},
'dateend': {
regexp: /(\d{1,2})\-(\d{1,2})\-(\d{4})/,
parse: function(d, dd, mm, yyyy) {
return new Date(yyyy, mm - 1, dd, 23, 59, 59, 999);
},
stringify: function(date) {
return datelpad(date.getDate()) + '-' + datelpad(date.getMonth() + 1) + '-' + date.getFullYear();
}
}
},
isoDateTypes = {
'date': {
regexp: /(\d{4})\-(\d{1,2})\-(\d{1,2})/,
parse: function(d, yyyy, mm, dd) {
return new Date(yyyy, mm - 1, dd);
},
stringify: function(date) {
return date.toISOString().split('T')[0];
}
},
'dateend': {
regexp: /(\d{4})\-(\d{1,2})\-(\d{1,2})/,
parse: function(d, yyyy, mm, dd) { return new Date(yyyy, mm - 1, dd, 23, 59, 59, 999); },
stringify: function(date) {
return date.toISOString().split('T')[0];
}
}
};
$.extend({
routes: {
useIsoDates: function(iso){
if(iso === true){
this.datatypes.date = isoDateTypes.date;
this.datatypes.dateend = isoDateTypes.dateend;
}
else {
this.datatypes.date = legacyDateTypes.date;
this.datatypes.dateend = legacyDateTypes.dateend;
}
},
// datatypes for parameters, regexp groups are passed as parameters to parsers
datatypes: {
'int': {
regexp: /\d+?/,
parse: function(d) { return parseInt(d, 10); }
},
'float': {
regexp: /\d+\.\d+?/,
parse: function(d) { return parseFloat(d); }
},
'word': {
regexp: /\w+?/
},
'string': {
regexp: /[\s\w]+?/
},
'datetime': {
regexp: /(\d{4})\-(\d{2})\-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z/,
parse: function(d, yyyy, mm, dd, hh, MM, ss, ms) {
return new Date(yyyy, mm - 1, dd, hh, MM, ss, ms);
},
stringify: function(date) {
return date.toISOString();
}
},
'date': isoDateTypes.date,
'dateend': isoDateTypes.dateend
},
// object containing all the routes by name
list: {},
// current executed route with parameter info
current: null,
// reload the current route with same or different parameters
reload: function(args) {
if (this.current) {
args = $.extend(this.current.arguments, args);
var url = this.current.url(args);
if (url !== location.hash) {
location.hash = url;
} else {
this.current.execute(args);
}
} else {
location.href.replace(location.href);
}
},
// add a route, they can be named and with default parameters
add: function(route, name, defaults, func) {
// parameter overload
if (typeof(name) === 'function') { func = name; name = undefined; }
if (typeof(defaults) === 'function') { func = defaults; defaults = undefined; }
if (typeof(name) === 'object') { defaults = name; name = undefined; }
// all routes have a name
if (name === undefined) { name = 'route' + (++routecount); }
if (route[route.length - 1] !== '/') { route += '/'; }
var regex = /\{\s*?([a-zA-Z0-9:\|\\*\?\.]*?)\s*?\}/gim;
var items = ['var s="#' + route + '";'];
var item = route;
var routeexp = '^' + route;
var vars = [];
// find parameters in route and create a regexp
while (match = regex.exec(item)) {
var arr = match[1].split(':');
var first = arr[0];
var constraint = arr[1];
items.push('s=s.replace("' + match[0] + '",p.' + first + ');');
item = item.replace(match[0], '');
if (constraint) {
// check for known datatype
if ($.routes.datatypes[constraint]) {
constraint = $.routes.datatypes[constraint].regexp.toString();
constraint = constraint.replace(/\/[gim]+$/g, ''); // Remove flags
constraint = constraint.replace(/\/$|^\//g, ''); // Wrapping slashes
constraint = constraint.replace(/[\(\)]/g, ''); // Remove groups
}
constraint = '(' + constraint + ')';
} else {
constraint = '(.*?)';
}
if(defaults && defaults[first]) {
constraint += '?'; // If there is a default, make parameter optional
}
routeexp = routeexp.replace(match[0], constraint);
vars.push(match[1].split(':'));
regex.lastIndex = match.index;
}
items.push('return s;');
// find a datatype
var getDatatype = function(parameter) {
for (var i = 0, len = vars.length; i < len; i++) {
if (vars[i][0] === parameter) {
return $.routes.datatypes[vars[i][1]];
}
}
};
// prepare parameters for url
var getParams = function(obj) {
var args = $.extend({}, defaults, obj), dt;
for (var item in args) {
if (args.hasOwnProperty(item)) {
dt = getDatatype(item);
if (dt && dt.stringify) {
args[item] = dt.stringify(args[item]);
}
}
}
return args;
};
// convert route with parameters to url
var combine = new Function('p', items.join(''));
var url = function(p) {
return combine(getParams(p));
};
// extract parameters from hash
var extract = function(hash) {
// load the defaults
var context = defaults ? defaults : {};
// get parameters
$.each(vars, function(x, vars) {
var datatype = $.routes.datatypes[vars[1]];
var val = args[x+1];
// parse parameter
if (datatype && datatype.parse) {
val = [val];
// get arguments for parse
if (datatype.regexp) {
var p = datatype.regexp.exec(args[x+1] || datatype.stringify(defaults[vars[x]]));
for (var y = 1; y < p.length; y++) {
val.push(p[y]);
}
}
val = datatype.parse.apply(datatype, val);
}
context[vars[0]] = val;
});
return context;
};
// add to list of routes
return this.list[name] = {
name: name,
exp: new RegExp(routeexp, 'i'),
route: route,
func: func,
url: url,
routeTo: function(data) {
location.href = this.url(data);
},
execute: function(data) {
this.func.apply($.extend({}, defaults, data));
},
vars: vars,
defaults: defaults,
level: route.length - route.replace(new RegExp("/", "g"), '').length,
extract: extract
};
},
addDataType: function(name, dt) {
$.routes.datatypes[name] = dt;
createDatatypeArray(name);
},
// get a registered route with name
find: function(name) {
return this.list[name];
},
findRoute: function(hash) {
var route;
// search for routes
$.each(this.list, function(i, match) {
// check for a match
var exp = match.exp.exec(hash);
if (exp) {
if ((route && match.level > route.level) || !route) {
route = match;
args = exp;
}
}
});
return route;
},
// load a hash and find the correct route to execute
load: function(hash) {
var route = $.routes.findRoute(hash.substr(1));
// route not found
if (!route) { return; }
// extract parameters from url
var params = route.extract(hash);
// execute route
$.routes.current = route;
$.routes.current.arguments = params;
route.execute(params);
}
}
});
$.expr[':'].hasRoute = function(elem, index, match) {
return $(elem).has('a[href$=' + location.hash + ']').length > 0;
};
$.fn.updateRoutes = function(params) {
$('a', this).each(function() {
var item = $(this),
hash = item.attr('href').substr(1),
route = $.routes.findRoute(hash);
if (!route) { return; }
var linkparams = route.extract(hash);
var newhash = route.url($.extend({}, linkparams, params));
item.attr('href', newhash);
});
};
function createDatatypeArray(name) {
var dt = $.routes.datatypes[name];
$.routes.datatypes[name + 'array'] = {
datatype: name,
regexp: new RegExp('[' + dt.regexp.toString().slice(1, dt.regexp.toString().length - 1) + '\\/\?]*', 'i'),
parse: function(d) {
var arr = d.split('/'),
newarr = [],
dt = $.routes.datatypes[this.datatype];
for (var i = 0; i < arr.length; i++) {
var groups = dt.regexp.exec(arr[i]).slice(1);
var args = [arr[i]].concat(groups);
newarr.push(dt.parse.apply(dt, args));
}
return newarr;
},
stringify: function(arr) {
for (var i = 0; i < arr.length; i++) {
var dt = $.routes.datatypes[this.datatype];
arr[i] = (!!dt.stringify ? dt.stringify(arr[i]) : arr[i].toString());
}
return arr.join('/');
}
};
}
// create array data types
var dts = $.extend({},$.routes.datatypes);
for (var name in dts) {
if (dts.hasOwnProperty(name)) {
createDatatypeArray(name);
}
}
// Listen for hash change event
$(window).bind('hashchange', function() {
$.routes.load(location.hash);
});
// Run route on document ready
$(function() {
var hash = location.hash;
if (hash.length > 0) {
if(hash[hash.length-1] !== '/'){
hash += '/';
}
$.routes.load(hash);
}
});
}(jQuery));