-
Notifications
You must be signed in to change notification settings - Fork 0
/
react-mini-router.js
487 lines (393 loc) · 14.5 KB
/
react-mini-router.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactMiniRouter=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = {
RouterMixin: require('./lib/RouterMixin'),
navigate: require('./lib/navigate')
};
},{"./lib/RouterMixin":2,"./lib/navigate":4}],2:[function(require,module,exports){
var pathToRegexp = require('path-to-regexp'),
urllite = require('urllite/lib/core'),
detect = require('./detect');
module.exports = {
getDefaultProps: function() {
return {
routes: {}
};
},
getInitialState: function() {
return {
path: this.props.path,
root: this.props.root || '',
useHistory: this.props.history && detect.hasPushState
};
},
componentWillMount: function() {
this.setState({ _routes: processRoutes(this.state.root, this.routes, this) });
},
componentDidMount: function() {
this.getDOMNode().addEventListener('click', this.handleClick, false);
if (this.state.useHistory) {
window.addEventListener('popstate', this.onPopState, false);
} else {
if (window.location.hash.indexOf('#!') === -1) {
window.location.hash = '#!/';
}
window.addEventListener('hashchange', this.onPopState, false);
}
},
componentWillUnmount: function() {
this.getDOMNode().removeEventListener('click', this.handleClick);
if (this.state.useHistory) {
window.removeEventListener('popstate', this.onPopState);
} else {
window.removeEventListener('hashchange', this.onPopState);
}
},
onPopState: function() {
var url = urllite(window.location.href),
hash = url.hash || '',
path = this.state.useHistory ? url.pathname : hash.slice(2);
if (path.length === 0) path = '/';
this.setState({ path: path + url.search });
},
renderCurrentRoute: function() {
var path = this.state.path,
url;
if (path) {
url = urllite(path);
} else if (!path && detect.canUseDOM) {
url = urllite(window.location.href);
if (!this.state.useHistory) url = urllite(url.hash ? url.hash.slice(2) : '');
} else {
url = urllite('/');
}
url.query = parseSearch(url.search);
var parsedPath = url.pathname;
if (!parsedPath || parsedPath.length === 0) parsedPath = '/';
var matchedRoute = this.matchRoute(parsedPath);
if (matchedRoute) {
return matchedRoute.handler.apply(this, matchedRoute.params.concat(url.query));
} else if (this.notFound) {
return this.notFound(parsedPath, url.query);
} else {
throw new Error('No route matched path: ' + parsedPath);
}
},
handleClick: function(evt) {
var self = this,
url = getHref(evt);
if (url && self.matchRoute(url.pathname)) {
evt.preventDefault();
// See: http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html
// Give any component event listeners a chance to fire in the current event loop,
// since they happen at the end of the bubbling phase. (Allows an onClick prop to
// work correctly on the event target <a/> component.)
setTimeout(function() {
var pathWithSearch = url.pathname + (url.search || '');
if (pathWithSearch.length === 0) pathWithSearch = '/';
if (self.state.useHistory) {
window.history.pushState({}, '', pathWithSearch);
} else {
window.location.hash = '!' + pathWithSearch;
}
self.setState({ path: pathWithSearch});
}, 0);
}
},
matchRoute: function(path) {
if (!path) return false;
var matchedRoute = {};
this.state._routes.some(function(route) {
var matches = route.pattern.exec(path);
if (matches) {
matchedRoute.handler = route.handler;
matchedRoute.params = matches.slice(1, route.params.length + 1);
return true;
}
return false;
});
return matchedRoute.handler ? matchedRoute : false;
}
};
function getHref(evt) {
if (evt.defaultPrevented) {
return;
}
if (evt.metaKey || evt.ctrlKey || evt.shiftKey) {
return;
}
if (evt.button !== 0) {
return;
}
var elt = evt.target;
// Since a click could originate from a child element of the <a> tag,
// walk back up the tree to find it.
while (elt && elt.nodeName !== 'A') {
elt = elt.parentNode;
}
if (!elt) {
return;
}
if (elt.target && elt.target !== '_self') {
return;
}
if (!!elt.attributes.download) {
return;
}
var linkURL = urllite(elt.href);
var windowURL = urllite(window.location.href);
if (linkURL.protocol !== windowURL.protocol || linkURL.host !== windowURL.host) {
return;
}
return linkURL;
}
function processRoutes(root, routes, component) {
var patterns = [],
path, pattern, keys, handler, handlerFn;
for (path in routes) {
if (routes.hasOwnProperty(path)) {
keys = [];
pattern = pathToRegexp(root + path, keys);
handler = routes[path];
handlerFn = component[handler];
patterns.push({ pattern: pattern, params: keys, handler: handlerFn });
}
}
return patterns;
}
function parseSearch(str) {
var parsed = {};
if (str.indexOf('?') === 0) str = str.slice(1);
var pairs = str.split('&');
pairs.forEach(function(pair) {
var keyVal = pair.split('=');
parsed[decodeURIComponent(keyVal[0])] = decodeURIComponent(keyVal[1]);
});
return parsed;
}
},{"./detect":3,"path-to-regexp":5,"urllite/lib/core":6}],3:[function(require,module,exports){
var canUseDOM = !!(
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
);
module.exports = {
canUseDOM: canUseDOM,
hasPushState: canUseDOM && window.history && 'pushState' in window.history,
hasHashbang: function() {
return canUseDOM && window.location.hash.indexOf('#!') === 0;
}
};
},{}],4:[function(require,module,exports){
var detect = require('./detect');
module.exports = function triggerUrl(url, silent) {
if (detect.hasHashbang()) {
window.location.hash = '#!' + url;
} else if (detect.hasPushState) {
window.history.pushState({}, '', url);
if (!silent) window.dispatchEvent(new window.Event('popstate'));
} else {
console.error("Browser does not support pushState, and hash is missing a hashbang prefix!");
}
};
},{"./detect":3}],5:[function(require,module,exports){
/**
* Expose `pathtoRegexp`.
*/
module.exports = pathtoRegexp;
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match already escaped characters that would otherwise incorrectly appear
// in future matches. This allows the user to escape special characters that
// shouldn't be transformed.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?"]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined]
'([\\/.])?(?:\\:(\\w+)(?:\\(((?:\\\\.|[^)])*)\\))?|\\(((?:\\\\.|[^)])*)\\))([+*?])?',
// Match regexp special characters that should always be escaped.
'([.+*?=^!:${}()[\\]|\\/])'
].join('|'), 'g');
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {String} group
* @return {String}
*/
function escapeGroup (group) {
return group.replace(/([=!:$\/()])/g, '\\$1');
}
/**
* Attach the keys as a property of the regexp.
*
* @param {RegExp} re
* @param {Array} keys
* @return {RegExp}
*/
var attachKeys = function (re, keys) {
re.keys = keys;
return re;
};
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array should be passed in, which will contain the placeholder key
* names. For example `/user/:id` will then contain `["id"]`.
*
* @param {(String|RegExp|Array)} path
* @param {Array} keys
* @param {Object} options
* @return {RegExp}
*/
function pathtoRegexp (path, keys, options) {
if (keys && !Array.isArray(keys)) {
options = keys;
keys = null;
}
keys = keys || [];
options = options || {};
var strict = options.strict;
var end = options.end !== false;
var flags = options.sensitive ? '' : 'i';
var index = 0;
if (path instanceof RegExp) {
// Match all capturing groups of a regexp.
var groups = path.source.match(/\((?!\?)/g) || [];
// Map all the matches to their numeric keys and push into the keys.
keys.push.apply(keys, groups.map(function (match, index) {
return {
name: index,
delimiter: null,
optional: false,
repeat: false
};
}));
// Return the source back to the user.
return attachKeys(path, keys);
}
if (Array.isArray(path)) {
// Map array parts into regexps and return their source. We also pass
// the same keys and options instance into every generation to get
// consistent matching groups before we join the sources together.
path = path.map(function (value) {
return pathtoRegexp(value, keys, options).source;
});
// Generate a new regexp instance by joining all the parts together.
return attachKeys(new RegExp('(?:' + path.join('|') + ')', flags), keys);
}
// Alter the path string into a usable regexp.
path = path.replace(PATH_REGEXP, function (match, escaped, prefix, key, capture, group, suffix, escape) {
// Avoiding re-escaping escaped characters.
if (escaped) {
return escaped;
}
// Escape regexp special characters.
if (escape) {
return '\\' + escape;
}
var repeat = suffix === '+' || suffix === '*';
var optional = suffix === '?' || suffix === '*';
keys.push({
name: key || index++,
delimiter: prefix || '/',
optional: optional,
repeat: repeat
});
// Escape the prefix character.
prefix = prefix ? '\\' + prefix : '';
// Match using the custom capturing group, or fallback to capturing
// everything up to the next slash (or next period if the param was
// prefixed with a period).
capture = escapeGroup(capture || group || '[^' + (prefix || '\\/') + ']+?');
// Allow parameters to be repeated more than once.
if (repeat) {
capture = capture + '(?:' + prefix + capture + ')*';
}
// Allow a parameter to be optional.
if (optional) {
return '(?:' + prefix + '(' + capture + '))?';
}
// Basic parameter support.
return prefix + '(' + capture + ')';
});
// Check whether the path ends in a slash as it alters some match behaviour.
var endsWithSlash = path[path.length - 1] === '/';
// In non-strict mode we allow an optional trailing slash in the match. If
// the path to match already ended with a slash, we need to remove it for
// consistency. The slash is only valid at the very end of a path match, not
// anywhere in the middle. This is important for non-ending mode, otherwise
// "/test/" will match "/test//route".
if (!strict) {
path = (endsWithSlash ? path.slice(0, -2) : path) + '(?:\\/(?=$))?';
}
// In non-ending mode, we need prompt the capturing groups to match as much
// as possible by using a positive lookahead for the end or next path segment.
if (!end) {
path += strict && endsWithSlash ? '' : '(?=\\/|$)';
}
return attachKeys(new RegExp('^' + path + (end ? '$' : ''), flags), keys);
};
},{}],6:[function(require,module,exports){
(function() {
var URL, URL_PATTERN, defaults, urllite,
__hasProp = {}.hasOwnProperty;
URL_PATTERN = /^(?:(?:([^:\/?\#]+:)\/+|(\/\/))(?:([a-z0-9-\._~%]+)(?::([a-z0-9-\._~%]+))?@)?(([a-z0-9-\._~%!$&'()*+,;=]+)(?::([0-9]+))?)?)?([^?\#]*?)(\?[^\#]*)?(\#.*)?$/;
urllite = function(raw, opts) {
return urllite.URL.parse(raw, opts);
};
urllite.URL = URL = (function() {
function URL(props) {
var k, v, _ref;
for (k in defaults) {
if (!__hasProp.call(defaults, k)) continue;
v = defaults[k];
this[k] = (_ref = props[k]) != null ? _ref : v;
}
this.host || (this.host = this.hostname && this.port ? "" + this.hostname + ":" + this.port : this.hostname ? this.hostname : '');
this.origin || (this.origin = this.protocol ? "" + this.protocol + "//" + this.host : '');
this.isAbsolutePathRelative = !this.host && this.pathname.charAt(0) === '/';
this.isPathRelative = !this.host && this.pathname.charAt(0) !== '/';
this.isRelative = this.isSchemeRelative || this.isAbsolutePathRelative || this.isPathRelative;
this.isAbsolute = !this.isRelative;
}
URL.parse = function(raw) {
var m, pathname, protocol;
m = raw.toString().match(URL_PATTERN);
pathname = m[8] || '';
protocol = m[1];
return new urllite.URL({
protocol: protocol,
username: m[3],
password: m[4],
hostname: m[6],
port: m[7],
pathname: protocol && pathname.charAt(0) !== '/' ? "/" + pathname : pathname,
search: m[9],
hash: m[10],
isSchemeRelative: m[2] != null
});
};
return URL;
})();
defaults = {
protocol: '',
username: '',
password: '',
host: '',
hostname: '',
port: '',
pathname: '',
search: '',
hash: '',
origin: '',
isSchemeRelative: false
};
module.exports = urllite;
}).call(this);
},{}]},{},[1])(1)
});