/
router5.js
801 lines (695 loc) · 28.9 KB
/
router5.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _slice = Array.prototype.slice;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _routeNode = require('route-node');
var _routeNode2 = _interopRequireDefault(_routeNode);
var _transition2 = require('./transition');
var _constants = require('./constants');
var _constants2 = _interopRequireDefault(_constants);
var _browser = require('./browser');
var _browser2 = _interopRequireDefault(_browser);
var makeState = function makeState(name, params, path) {
return { name: name, params: params, path: path };
};
/**
* Create a new Router5 instance
* @class
* @param {RouteNode[]|Object[]|RouteNode|Object} routes The router routes
* @param {Object} [opts={}] The router options: useHash, defaultRoute and defaultParams can be specified.
* @return {Router5} The router instance
*/
var Router5 = (function () {
_createClass(Router5, null, [{
key: 'ERR',
/**
* Error codes
* @type {Object}
*/
value: _constants2['default'],
/**
* An helper function to return instructions for a transition:
* intersection route name, route names to deactivate, route names to activate
* @param {Object} toState The state to go to
* @param {Object} fromState The state to go from
* @return {Object} An object containing 'intersection', 'toActivate' and 'toDeactivate' keys
*/
enumerable: true
}, {
key: 'transitionPath',
value: _transition2.transitionPath,
enumerable: true
}]);
function Router5(routes) {
var _this = this;
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, Router5);
this.started = false;
this._onTr = null;
this._cbs = {};
this._cmps = {};
this._canAct = {};
this.lastStateAttempt = null;
this.lastKnownState = null;
this.rootNode = routes instanceof _routeNode2['default'] ? routes : new _routeNode2['default']('', '', routes);
this.options = {
useHash: false,
hashPrefix: '',
base: '',
trailingSlash: 0
};
Object.keys(opts).forEach(function (opt) {
return _this.options[opt] = opts[opt];
});
this._setBase();
// Bind onPopState
this.boundOnPopState = this.onPopState.bind(this);
}
/**
* @private
*/
_createClass(Router5, [{
key: '_setBase',
value: function _setBase() {
if (this.options.useHash && !this.options.base) this.options.base = _browser2['default'].getBase();
}
/**
* Set an option value
* @param {String} opt The option to set
* @param {*} val The option value
* @return {Router5} The Router5 instance
*/
}, {
key: 'setOption',
value: function setOption(opt, val) {
this.options[opt] = val;
if (opt === 'useHash') this._setBase();
return this;
}
/**
* Add route(s)
* @param {RouteNode[]|Object[]|RouteNode|Object} routes Route(s) to add
* @return {Router5} The Router5 instance
*/
}, {
key: 'add',
value: function add(routes) {
this.rootNode.add(routes);
return this;
}
/**
* Add a route to the router.
* @param {String} name The route name
* @param {String} path The route path
* @param {Function} [canActivate] A function to determine if the route can be activated.
* It will be invoked during a transition with `toState`
* and `fromState` parameters.
* @return {Router5} The Router5 instance
*/
}, {
key: 'addNode',
value: function addNode(name, path, canActivate) {
this.rootNode.addNode(name, path);
if (canActivate) this._canAct[name] = canActivate;
return this;
}
/**
* @private
*/
}, {
key: 'onPopState',
value: function onPopState(evt) {
var _this2 = this;
// Do nothing if no state or if last know state is poped state (it should never happen)
var newState = !evt.state || !evt.state.name;
var state = evt.state || this.matchPath(this.getLocation());
var opts = this.options;
if (!state) {
// If current state is already the default route, we will have a double entry
// Navigating back and forth will emit SAME_STATES error
this.navigate(opts.defaultRoute, opts.defaultParams, { reload: true, replace: true });
return;
}
if (this.lastKnownState && this.areStatesEqual(state, this.lastKnownState)) {
return;
}
this._transition(state, this.lastKnownState, function (err, toState) {
if (err) {
if (err === _constants2['default'].CANNOT_DEACTIVATE) {
var url = _this2.buildUrl(_this2.lastKnownState.name, _this2.lastKnownState.params);
if (!newState) {
// Keep history state unchanged but use current URL
_this2.updateBrowserState(state, url, true);
}
// else do nothing or history will be messed up
// TODO: history.back()?
} else {
// Force navigation to default state
_this2.navigate(opts.defaultRoute, opts.defaultParams, { reload: true, replace: true });
}
} else {
_this2.updateBrowserState(toState, _this2.buildUrl(toState.name, toState.params), newState);
}
});
}
/**
* Set a transition middleware function
* @param {Function} fn The middleware function
*/
}, {
key: 'onTransition',
value: function onTransition(fn) {
this._onTr = fn;
return this;
}
/**
* Start the router
* @param {String|Object} [startPathOrState] An optional start path or state
* (use it for universal applications)
* @param {Function} [done] An optional callback which will be called
* when starting is done
* @return {Router5} The router instance
*/
}, {
key: 'start',
value: function start() {
var _this3 = this;
var args = [].concat(_slice.call(arguments));
var lastArg = args.slice(-1)[0];
var done = lastArg instanceof Function ? lastArg : null;
var startPath = undefined,
startState = undefined;
if (this.started) {
if (done) done(_constants2['default'].ROUTER_ALREADY_STARTED);
return this;
}
if (args.length > 0) {
if (typeof args[0] === 'string') startPath = args[0];
if (typeof args[0] === 'object') startState = args[0];
}
this.started = true;
var opts = this.options;
// callback
var cb = function cb(err, state) {
var invokeErrCb = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
_browser2['default'].addPopstateListener(_this3.boundOnPopState);
if (done) done(err, state);
if (err && invokeErrCb) _this3._invokeListeners('$error', state, null, err);
};
// Get start path
if (!startPath && !startState) startPath = this.getLocation();
if (!startState) {
(function () {
// If no supplied start state, get start state
startState = _this3.matchPath(startPath);
// Navigate to default function
var navigateToDefault = function navigateToDefault() {
return _this3.navigate(opts.defaultRoute, opts.defaultParams, { replace: true }, function (err, state) {
return cb(err, state, false);
});
};
// If matched start path
if (startState) {
_this3.lastStateAttempt = startState;
_this3._transition(_this3.lastStateAttempt, _this3.lastKnownState, function (err, state) {
if (!err) {
_this3.updateBrowserState(_this3.lastKnownState, _this3.buildUrl(startState.name, startState.params), true);
cb(null, state);
} else if (opts.defaultRoute) navigateToDefault();else cb(err, null, false);
});
} else if (opts.defaultRoute) {
// If default, navigate to default
navigateToDefault();
} else {
// No start match, no default => do nothing
cb(_constants2['default'].ROUTE_NOT_FOUND, null);
}
})();
} else {
// Initialise router with provided start state
this.lastKnownState = startState;
this.updateBrowserState(this.lastKnownState, this.buildUrl(startState.name, startState.params), true);
cb(null, startState);
}
// Listen to popstate
return this;
}
/**
* Stop the router
* @return {Router5} The router instance
*/
}, {
key: 'stop',
value: function stop() {
if (!this.started) return this;
this.lastKnownState = null;
this.lastStateAttempt = null;
this.started = false;
_browser2['default'].removePopstateListener(this.boundOnPopState);
return this;
}
/**
* Return the current state object
* @return {Object} The current state
*/
}, {
key: 'getState',
value: function getState() {
return this.lastKnownState;
}
/**
* Whether or not the given route name with specified params is active.
* @param {String} name The route name
* @param {Object} [params={}] The route parameters
* @param {Boolean} [strictEquality=false] If set to false (default), isActive will return true
* if the provided route name and params are descendants
* of the active state.
* @param {Boolean} [ignoreQueryParams=true] Whether or not to ignore URL query parameters when
* comparing the two states together.
* query parameters when comparing two states together.
* @return {Boolean} Whether nor not the route is active
*/
}, {
key: 'isActive',
value: function isActive(name) {
var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var strictEquality = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
var ignoreQueryParams = arguments.length <= 3 || arguments[3] === undefined ? true : arguments[3];
var activeState = this.getState();
if (!activeState) return false;
if (strictEquality || activeState.name === name) {
return this.areStatesEqual(makeState(name, params), activeState, ignoreQueryParams);
}
return this.areStatesDescendants(makeState(name, params), activeState);
}
/**
* @private
*/
}, {
key: 'areStatesEqual',
value: function areStatesEqual(state1, state2) {
var _this4 = this;
var ignoreQueryParams = arguments.length <= 2 || arguments[2] === undefined ? true : arguments[2];
if (state1.name !== state2.name) return false;
var getUrlParams = function getUrlParams(name) {
return _this4.rootNode.getSegmentsByName(name).map(function (segment) {
return segment.parser[ignoreQueryParams ? 'urlParams' : 'params'];
}).reduce(function (params, p) {
return params.concat(p);
}, []);
};
var state1Params = getUrlParams(state1.name);
var state2Params = getUrlParams(state2.name);
return state1Params.length === state2Params.length && state1Params.every(function (p) {
return state1.params[p] === state2.params[p];
});
}
/**
* Whether two states are descendants
* @param {Object} parentState The parent state
* @param {Object} childState The child state
* @return {Boolean} Whether the two provided states are related
*/
}, {
key: 'areStatesDescendants',
value: function areStatesDescendants(parentState, childState) {
var regex = new RegExp('^' + parentState.name + '\\.(.*)$');
if (!regex.test(childState.name)) return false;
// If child state name extends parent state name, and all parent state params
// are in child state params.
return Object.keys(parentState.params).every(function (p) {
return parentState.params[p] === childState.params[p];
});
}
/**
* @private
*/
}, {
key: '_invokeListeners',
value: function _invokeListeners(name) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
(this._cbs[name] || []).forEach(function (cb) {
return cb.apply(undefined, args);
});
}
/**
* @private
*/
}, {
key: '_addListener',
value: function _addListener(name, cb, replace) {
var normalizedName = name.replace(/^(\*|\^|=)/, '');
if (normalizedName && !/^\$/.test(name)) {
var segments = this.rootNode.getSegmentsByName(normalizedName);
if (!segments) console.warn('No route found for ' + normalizedName + ', listener might never be called!');
}
if (!this._cbs[name]) this._cbs[name] = [];
this._cbs[name] = (replace ? [] : this._cbs[name]).concat(cb);
return this;
}
/**
* @private
*/
}, {
key: '_removeListener',
value: function _removeListener(name, cb) {
if (this._cbs[name]) this._cbs[name] = this._cbs[name].filter(function (callback) {
return callback !== cb;
});
return this;
}
/**
* Add a route change listener
* @param {Function} cb The listener to add
* @return {Router5} The router instance
*/
}, {
key: 'addListener',
value: function addListener(cb) {
return this._addListener('*', cb);
}
/**
* Remove a route change listener
* @param {Function} cb The listener to remove
* @return {Router5} The router instance
*/
}, {
key: 'removeListener',
value: function removeListener(cb) {
return this._removeListener('*', cb);
}
/**
* Add a node change listener
* @param {String} name The route segment full name
* @param {Function} cb The listener to add
* @return {Router5} The router instance
*/
}, {
key: 'addNodeListener',
value: function addNodeListener(name, cb) {
return this._addListener('^' + name, cb, true);
}
/**
* Remove a node change listener
* @param {String} name The route segment full name
* @param {Function} cb The listener to remove
* @return {Router5} The router instance
*/
}, {
key: 'removeNodeListener',
value: function removeNodeListener(name, cb) {
this._cbs['^' + name] = [];
return this;
}
/**
* Add a route change listener
* @param {String} name The route name to listen to
* @param {Function} cb The listener to add
* @return {Router5} The router instance
*/
}, {
key: 'addRouteListener',
value: function addRouteListener(name, cb) {
return this._addListener('=' + name, cb);
}
/**
* Remove a route change listener
* @param {String} name The route name to listen to
* @param {Function} cb The listener to remove
* @return {Router5} The router instance
*/
}, {
key: 'removeRouteListener',
value: function removeRouteListener(name, cb) {
return this._removeListener('=' + name, cb);
}
/**
* Add a transition start callback
* @param {Function} cb The callback
* @return {Router5} The router instance
*/
}, {
key: 'onTransitionStart',
value: function onTransitionStart(cb) {
return this._addListener('$start', cb);
}
/**
* Remove a transition start callback
* @param {Function} cb The callback
* @return {Router5} The router instance
*/
}, {
key: 'offTransitionStart',
value: function offTransitionStart(cb) {
return this._removeListener('$start', cb);
}
/**
* Add a transition cancel callback
* @param {Function} cb The callback
* @return {Router5} The router instance
*/
}, {
key: 'onTransitionCancel',
value: function onTransitionCancel(cb) {
return this._addListener('$cancel', cb);
}
/**
* Remove a transition cancel callback
* @param {Function} cb The callback
* @return {Router5} The router instance
*/
}, {
key: 'offTransitionCancel',
value: function offTransitionCancel(cb) {
return this._removeListener('$cancel', cb);
}
/**
* Add a transition error callback
* @param {Function} cb The callback
* @return {Router5} The router instance
*/
}, {
key: 'onTransitionError',
value: function onTransitionError(cb) {
return this._addListener('$error', cb);
}
/**
* Remove a transition error callback
* @param {Function} cb The callback
* @return {Router5} The router instance
*/
}, {
key: 'offTransitionError',
value: function offTransitionError(cb) {
return this._removeListener('$error', cb);
}
/**
* Register an active component for a specific route segment
* @param {String} name The route segment full name
* @param {Object} component The component instance
*/
}, {
key: 'registerComponent',
value: function registerComponent(name, component) {
if (this._cmps[name]) console.warn('A component was alread registered for route node ' + name + '.');
this._cmps[name] = component;
return this;
}
/**
* Deregister an active component
* @param {String} name The route segment full name
* @return {Router5} The router instance
*/
}, {
key: 'deregisterComponent',
value: function deregisterComponent(name) {
delete this._cmps[name];
}
/**
* A function to determine whether or not a segment can be activated.
* @param {String} name The route name to register the canActivate method for
* @param {Function} canActivate The canActivate function. It should return `true`, `false`
* or a promise
* @return {Router5} The router instance
*/
}, {
key: 'canActivate',
value: function canActivate(name, _canActivate) {
this._canAct[name] = _canActivate;
return this;
}
/**
* @private
*/
}, {
key: 'getLocation',
value: function getLocation() {
return _browser2['default'].getLocation(this.options);
}
/**
* Generates an URL from a route name and route params.
* The generated URL will be prefixed by hash if useHash is set to true
* @param {String} route The route name
* @param {Object} params The route params (key-value pairs)
* @return {String} The built URL
*/
}, {
key: 'buildUrl',
value: function buildUrl(route, params) {
return this._buildUrl(this.rootNode.buildPath(route, params));
}
}, {
key: '_buildUrl',
value: function _buildUrl(path) {
return this.options.base + (this.options.useHash ? '#' + this.options.hashPrefix : '') + path;
}
/**
* Build a path from a route name and route params
* The generated URL will be prefixed by hash if useHash is set to true
* @param {String} route The route name
* @param {Object} params The route params (key-value pairs)
* @return {String} The built Path
*/
}, {
key: 'buildPath',
value: function buildPath(route, params) {
return this.rootNode.buildPath(route, params);
}
/**
* Match a path against the route tree.
* @param {String} path The path to match
* @return {Object} The matched state object (null if no match)
*/
}, {
key: 'matchPath',
value: function matchPath(path) {
var match = this.rootNode.matchPath(path, this.options.trailingSlash);
return match ? makeState(match.name, match.params, path) : null;
}
/**
* Parse / extract a path from an url
* @param {String} url The URL
* @return {String} The extracted path
*/
}, {
key: 'urlToPath',
value: function urlToPath(url) {
var match = url.match(/^(?:http|https)\:\/\/(?:[0-9a-z_\-\.\:]+?)(?=\/)(.*)$/);
var path = match ? match[1] : url;
var pathParts = path.match(/^(.*?)(#.*?)?(\?.*)?$/);
if (!pathParts) throw new Error('Could not parse url ' + url);
var pathname = pathParts[1];
var hash = pathParts[2];
var search = pathParts[3];
var opts = this.options;
return (opts.useHash ? hash.replace(new RegExp('^#' + opts.hashPrefix), '') : pathname.replace(new RegExp('^' + opts.base), '')) + (search || '');
}
/**
* Parse path from an url and match it against the route tree.
* @param {String} url The URL to match
* @return {Object} The matched state object (null if no match)
*/
}, {
key: 'matchUrl',
value: function matchUrl(url) {
return this.matchPath(this.urlToPath(url));
}
/**
* @private
*/
}, {
key: '_transition',
value: function _transition(toState, fromState, done) {
var _this5 = this;
// Cancel current transition
if (this._tr) this._tr();
this._invokeListeners('$start', toState, fromState);
var tr = (0, _transition2.transition)(this, toState, fromState, function (err) {
_this5._tr = null;
if (err) {
if (err === _constants2['default'].TRANSITION_CANCELLED) _this5._invokeListeners('$cancel', toState, fromState);else _this5._invokeListeners('$error', toState, fromState, err);
if (done) done(err);
return;
}
_this5.lastKnownState = toState;
_this5._invokeListeners('=' + toState.name, toState, fromState);
_this5._invokeListeners('*', toState, fromState);
if (done) done(null, toState);
});
this._tr = tr;
return function () {
return !tr || tr();
};
}
/**
* Navigate to a specific route
* @param {String} name The route name
* @param {Object} [params={}] The route params
* @param {Object} [opts={}] The route options (replace, reload)
* @param {Function} done A optional callback(err) to call when transition has been performed
* either successfully or unsuccessfully.
* @return {Function} A cancellation function
*/
}, {
key: 'navigate',
value: function navigate(name, params, opts, done) {
if (params === undefined) params = {};
var _this6 = this;
if (opts === undefined) opts = {};
if (!this.started) {
if (done) done(_constants2['default'].ROUTER_NOT_STARTED);
return;
}
if (!_browser2['default'].getState()) opts.replace = true;
var path = this.buildPath(name, params);
var url = this.buildUrl(name, params);
if (!path) {
if (done) done(_constants2['default'].ROUTE_NOT_FOUND);
this._invokeListeners('$error', null, this.lastKnownState, _constants2['default'].ROUTE_NOT_FOUND);
return;
}
var toState = makeState(name, params, path);
this.lastStateAttempt = toState;
var sameStates = this.lastKnownState ? this.areStatesEqual(this.lastKnownState, this.lastStateAttempt) : false;
// Do not proceed further if states are the same and no reload
// (no desactivation and no callbacks)
if (sameStates && !opts.reload) {
if (done) done(_constants2['default'].SAME_STATES);
this._invokeListeners('$error', toState, this.lastKnownState, _constants2['default'].SAME_STATES);
return;
}
// Transition and amend history
return this._transition(toState, sameStates ? null : this.lastKnownState, function (err, state) {
if (err) {
if (done) done(err);
return;
}
_this6.updateBrowserState(_this6.lastStateAttempt, url, opts.replace);
if (done) done(null, state);
});
}
/**
* Update the browser history
* @param {Object} stateObject State object to be used
* @param {string} url Absolute url to be used
* @param {boolean} [replace=false] If replaceState or pushState should be used
* @param {string} [title=''] The title to be used for history
*/
}, {
key: 'updateBrowserState',
value: function updateBrowserState(stateObject, url) {
var replace = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
var title = arguments.length <= 3 || arguments[3] === undefined ? '' : arguments[3];
_browser2['default'][replace ? 'replaceState' : 'pushState'](stateObject, title, url);
}
}]);
return Router5;
})();
exports['default'] = Router5;
module.exports = exports['default'];