forked from atotic/excess-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexcess-route-manager.html
1204 lines (1075 loc) · 34.1 KB
/
excess-route-manager.html
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<link rel="import" href="../polymer/polymer.html">
<script src="pathToRegexp.js"></script>
<script>
(function() {
'use strict';
function regexKeysToArray(regexKeys) {
var keys = [];
for (var i=0; i<regexKeys.length; i++) {
if (regexKeys[i].name) {
keys.push(regexKeys[i].name);
}
}
return keys;
}
/** ES6 [].find polyfill */
function ArrayFind(array, compareFn) {
for (var i=0; i<array.length; i++) {
if (compareFn(array[i]))
return array[i];
}
}
/** ES6 "".startsWith polyfill */
function StringStartsWith(str, search) {
if (str == null) {
throw TypeError();
}
var stringLength = str.length;
var searchString = String(search);
var searchLength = searchString.length;
// `ToInteger`
var pos = 0;
var start = Math.min(Math.max(pos, 0), stringLength);
// Avoid the `indexOf` call if no match is possible
if (searchLength + start > stringLength) {
return false;
}
var index = -1;
while (++index < searchLength) {
if (str.charCodeAt(start + index) != searchString.charCodeAt(index)) {
return false;
}
}
return true;
};
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomString += charSet.substring(randomPoz,randomPoz+1);
}
return randomString;
};
/**
RouterState stores RouteManager configuration.
It provides utility routines for state manipulation.
Use the routines, instead of manipulating state directly.
*/
var RouterState = {
// registered routes (excluding aliased)
routes: [],
// registered alias routes
aliasRoutes: [],
// alias routes without a parent
orphanAliasRoutes: [],
// registered routes alias map -- Map(alias->Route)
routesByAlias: {},
// active routes
activeRoutes: [],
// current transition
activeTransition: null,
// Configuration variables
// anchorRouting
anchorRouting: true,
// true if routing should start automatically on WebComponentsReady
autoStart: true,
// base path for path routing
basePath: '',
// prefix for hash paths
hashPrefix: '#',
// Routes starting with aliasPathPrefix will be interpreted as aliases
aliasPathPrefix: '@',
// hash|path
pathStyle: 'hash',
// Routes starting with token prefix are tokens
tokenPrefix: 'toke-',
addRoute: function(route) {
// register route's alias
if (route.alias) {
if (this.routesByAlias[route.alias]) {
console.error(this._routesByAlias[route.alias]);
throw new Error("Cant register two routes with same alias. "
+ route.alias + "has already been registered.");
}
this.routesByAlias[route.alias] = route;
}
this.routes.push(route);
// process orphan routes
if (route.alias) {
var x = this.orphanAliasRoutes
.filter(function(o) {
return o.alias === route.alias;
});
this.orphanAliasRoutes
.filter(function(o) {
return o.alias === route.alias;
})
.forEach(function(o) {
this.orphanAliasRoutes.splice( this.orphanAliasRoutes.indexOf(o), 1);
o.setParent(route);
}.bind(this));
}
},
removeRoute: function(route) {
var idx = this.routes.indexOf(route);
var activeIdx = this.activeRoutes ? this.activeRoutes.indexOf(route) : -1;
if (activeIdx != -1) {
// console.warn('removing currently active route');
this.activeRoutes.splice(activeIdx, 1);
RouteManager._setRouteFromLocation();
}
var route = this.routes[idx];
var alias;
// orphan routes aliased to this one
while (alias = route.aliasRoutes[0]) {
alias.setParent(null);
this.addOrphanRoute(alias);
}
// if route was aliased, remove it from the list
if (route.alias) {
delete this.routesByAlias[route.alias];
}
this.routes.splice(idx, 1);
},
addAliasRoute: function(route) {
var parent = this.routesByAlias[route.alias];
if (parent) {
this.aliasRoutes.push(route);
route.setParent(parent);
}
else {
this.addOrphanRoute(route);
}
},
removeAliasRoute: function(route) {
var idx = this.aliasRoutes.indexOf(route);
this.aliasRoutes[idx].setParent(null);
this.aliasRoutes.splice(idx, 1);
},
addOrphanRoute: function(route) {
this.orphanAliasRoutes.push(route);
},
removeOrphanRoute: function(route) {
var idx = this.orphanAliasRoutes.indexOf(route);
this.orphanAliasRoutes.splice(idx, 1);
},
removeToken: function(token) {
var compare = Route.compareByToken(token);
var route = ArrayFind(this.routes, compare);
if (route) {
this.removeRoute(route);
return;
}
route = ArrayFind(this.aliasRoutes, compare);
if (route) {
this.removeAliasRoute(route);
return;
}
route = ArrayFind( this.orphanAliasRoutes, compare);
if (route) {
this.removeOrphanRoute(route);
return;
}
console.warn('Could not remove route with token', token);
},
cancelActiveTransition: function() {
if (!this.activeTransition) {
return;
}
this.activeTransition.abort();
},
startTransition: function(transition) {
this.cancelActiveTransition();
this.activeTransition = transition;
transition.start();
},
completeTransition: function(transition) {
if (this.activeTransition === transition)
this.activeTransition = null;
},
setActiveRoutes: function(routes) {
this.activeRoutes = routes;
},
}
/**
RouteManagerTest is a collection of functions only used in tests
*/
var RouteManagerTest = {
reset: function() {
RouterState.routes = [];
RouterState.aliasRoutes = [];
RouterState.orphanAliasRoutes = [];
RouterState.routesByAlias = {};
RouterState.activeRoutes = null;
RouterState.pathStyle = 'hash';
RouterState.basePath = '';
RouterState.autoStart = true;
RouterState.hashPrefix = '#';
RouterState.aliasPathPrefix = '@';
},
routeType: function(token) {
var compare = Route.compareByToken(token);
if( ArrayFind(RouterState.routes, compare)) {
return 'standard';
}
else if (ArrayFind(RouterState.orphanAliasRoutes, compare)) {
return 'orphan';
}
else if (ArrayFind(RouterState.aliasRoutes, compare)) {
return 'alias';
}
return null;
},
routeFromToken: function(token) {
var compare = Route.compareByToken(token);
return ArrayFind(RouterState.routes, compare) ||
ArrayFind(RouterState.aliasRoutes, compare) ||
null;
},
print: function() {
console.log("RouteManager");
RouterState.routes.forEach(function(r) {
console.log(r.toString());
});
if (RouterState.orphanAliasRoutes.length > 0) {
console.log('orphans');
RouterState.orphanAliasRoutes.forEach(function(r) {
console.log(r.toString());
});
}
},
updateStateCb: null // can be replaced with function(url) {} for testing
}
/**
RouteManager is a JavaScript routing library.
### Features:
- Express-style path matching
'/foo/:bar/:baz', '/foo/*'
- '/' or '#!' paths
- route transition callbacks: willDeactivate, willActivate, deactivate, activate
callbacks are sync|async
transitions can be aborted, redirected
- route aliases:
register('/home/login', { alias: 'login'}); transitionTo('@login');
- navigation API: transitionTo, replaceWith
- anchor tag routing, intercepts clicks
### Path spec:
Paths are Express-style path strings, such as `/user/:id`.
See [path-to-regex library](https://github.com/pillarjs/path-to-regexp)
for detailed Express-style path information.
### Configuration:
- `anchorRouting: true`. If true, will trap anchor clicks and attempt to route them.
- `autoStart: true`. If true, will start routing on WebComponentsReady. If your
routes are not ready by then, set to false, and call RouteManager.start() when ready.
- `basePath: ''`. base path for path style routing. Set to your app's root path.
- `hashPrefix: '#'`. Prefix for hash paths. You might also like '#!'
- `aliasPathPrefix: '@'`. Routes starting with aliasPathPrefix will be interpreted as aliases
- `pathStyle: 'hash'`. Are your paths hashes, or real paths? 'hash'|'path'
- `tokenPrefix: 'toke-'`. Routes starting with token prefix are tokens. You can ignore this
setting unless you get conflicts
### Tips:
- To redirect a route
- Register the route
- Inside routes's activate handler, abort the transition with 'redirectTo' path
- Debugging
- print all paths with `Excess.RouteManagerTest.print()`
- 'no routes matched' error on startup
- if you see this error on startup, your routes might be registering too late. Set `autoStart` to false,'
and start your router manually with `Excess.RouteManager.start()`
@polymerBehavior Excess.RouteManager
*/
var RouteManager = {
/**
* @param {object} options --
* @param {boolean} options.anchorRouting -- true if anchor clicks should be intercepted
* @param {string} options.autoStart -- automatically start on WebComponentsReady
* @param {string} options.pathStyle -- hash/path
* @param {string} options.basePath -- base path for path routing
* @param {string} options.hashPrefix -- hash prefix: default '#', set '#!' if you need it
* @param {string} options.aliasPathPrefix -- paths with this prefix are considered alias. default '@'
*/
configure: function(options) {
[
'anchorRouting',
'autoStart',
'basePath',
'hashPrefix',
'aliasPathPrefix',
'pathStyle',
'tokenPrefix'
].forEach( function(p) {
if (p in options) {
RouterState[p] = options[p];
}
});
if (!StringStartsWith(RouterState.hashPrefix,'#')) {
throw new Error('hashPrefix must start with #');
}
},
/**
* Registers a route. See source for options documentation, since Polymer docs are borked when it comes to options.
*
* @param {string} path -- Path string
* @param {object} options --
* @param {string} options.alias -- route alias
* @param {boolean} options.isAliasRoute -- true if this is a aliased route
* @param {boolean} option.activateExclusive -- true if this route can only be activated on its own
* @param {boolean} option.activateStopPropagation -- true if no routes will match after this one
* @return {string}} -- token, you need this to unregister
*/
register: function(path, options) {
options = options || {};
var route;
if (options.isAliasRoute || this._getRouteType(path) === 'alias') {
route = new AliasRoute(path, options);
RouterState.addAliasRoute(route);
if (this._started &&
route.parent && route.parent.match(this._extractLocationPath())) {
this._setRouteFromLocation();
}
}
else {
route = new Route(path, options);
RouterState.addRoute(route);
try {
// activate route if matches
if (this._started && route.match(this._extractLocationPath()))
this._setRouteFromLocation();
}
catch(err) {
console.warn(err); // new code, see if something breaks
}
}
return route.token;
},
/**
* the opposite of `register()`
*/
unregister: function(token) {
RouterState.removeToken(token);
},
_findRouteByToken: function(token) {
var compare = Route.compareByToken(token);
var destination = ArrayFind(RouterState.routes, compare);
if (!destination) {
destination = ArrayFind(RouterState.aliasRoutes, compare);
if (!destination) {
throw new Error('route not found ' + token);
}
}
return destination;
},
_findRouteByAlias: function(alias) {
var compare = Route.compareByAlias(alias);
var destination = ArrayFind(RouterState.routes, compare);
return destination;
},
_urlFromRoutePath: function(routePath) {
if (RouterState.pathStyle === 'hash') {
return RouterState.hashPrefix + routePath;
}
else {
return RouterState.basePath + routePath;
}
},
_getPushStateCallback: function() {
return RouteManagerTest.updateStateCb ||
function(routePath) {
window.history.pushState(null, "",
RouteManager._urlFromRoutePath(routePath));
}
},
_getReplaceStateCallback: function() {
return RouteManagerTest.updateStateCb ||
function(routePath) {
window.history.replaceState(null, "",
RouteManager._urlFromRoutePath(routePath));
}
},
/**
* @param {string} -- route. Can be token ('toke-AV213'), alias ('@user'), or path ('/this/is/path')
* @return {'alias'|'token'|'path'} -- kind of path this is
*/
_getRouteType: function(routeSpecifier) {
if (routeSpecifier === null) {
return null;
}
else if (RouterState.aliasPathPrefix &&
StringStartsWith(routeSpecifier, RouterState.aliasPathPrefix)) {
return 'alias';
}
else if (RouterState.tokenPrefix &&
StringStartsWith(routeSpecifier, RouterState.tokenPrefix)) {
return 'token';
}
else {
return 'path';
}
},
/**
*
* @return {array} -- array of keys for given route
*/
getRouteKeys: function(routeSpecifier) {
switch(this._getRouteType(routeSpecifier)) {
case 'alias':
var r = this._findRouteByAlias(routeSpecifier);
if (!r) {
throw new Error("Route alias not registered");
}
return r.keys();
case 'token':
var r = this._findRouteByToken(routeSpecifier).resolveAlias();
if (!r) {
throw new Error("Route, or route's alias not registered");
}
return r.keys();
case 'path':
var keys = [];
pathToRegexp(routeSpecifier, keys, { sensitive: true, strict: true });
return regexKeysToArray(keys);
}
},
/**
* Concatenates paths, taking into account route type. You can use it with all route
* specifiers understood by RouteManager
*/
concatPaths: function(parentPath, childPath) {
if (!childPath) {
return null;
}
switch(this._getRouteType(childPath)) {
case 'alias':
return childPath;
case 'token':
throw new Error('Child path cannot be a path token');
case 'path':
return parentPath ? parentPath + childPath : childPath;
}
},
/**
* finds matching route given a path
* @return {{route: route, routeParams: params}}
*/
_matchRoutes: function(path) {
var routes = [];
for (var i=0; i<RouterState.routes.length; i++) {
var route = RouterState.routes[i];
var routeParams = route.match(path);
if (routeParams) {
routes.push( { route: route, routeParams: routeParams } );
if (route.activateStopPropagation) {
break; // stop searching for routes only this route
}
}
}
// eliminate activateExclusives if more than one
if (routes.length > 1) {
for (var i=0; i<routes.length; i++) {
if (routes[i].route.activateExclusive)
routes.splice(i--, 1);
}
}
if (routes.length > 0) {
return {
routes: routes,
destinationPath: path // RouterState.routes[i].getRoutePath(routeParams)
}
}
return null;
},
_findDestinations: function(destination, routeParams) {
switch( this._getRouteType(destination)) {
case 'alias':
var route = this._findRouteByAlias(destination);
if (route) {
return {
routes: [{ route: route, routeParams: routeParams }],
destinationPath: route.getRoutePath(routeParams)
}
}
return;
case 'token':
var route = this._findRouteByToken(destination).resolveAlias();
if (route) {
return {
routes: [{ route: route, routeParams: routeParams}],
destinationPath: route.getRoutePath(routeParams)
}
}
return;
case 'path':
return this._matchRoutes(destination);
}
},
/**
* Transition to new route,
* @param {token|alias|path} -- destination can be token,alias,or path
*/
transitionTo: function(destination, routeParams) {
var dest = this._findDestinations(destination, routeParams);
if (!dest) {
throw new Error("Transition destination not found");
}
var transition = new Transition(
RouterState.activeRoutes,
dest.routes,
{
destinationPath: dest.destinationPath,
updateLocationCb: this._getPushStateCallback()
}
);
RouterState.startTransition(transition);
},
/**
* Transition to new route, but replace existing URL in place (no history)
*/
replaceWith: function(destination, routeParams) {
var dest = this._findDestinations(destination, routeParams);
if (!dest) {
throw new Error("Transition destination not found");
}
var transition = new Transition(
RouterState.activeRoutes,
dest.routes,
{
destinationPath: dest.destinationPath,
updateLocationCb: this._getPushStateCallback()
}
);
RouterState.startTransition(transition);
},
_setRouteFromLocation: function() {
var path = this._extractLocationPath();
if (!path) {
console.warn('popstate could not extract path',
window.location.pathname);
return;
}
var dest = this._matchRoutes(path);
if (dest) {
var transition = new Transition(
RouterState.activeRoutes,
dest.routes,
{
destinationPath: dest.destinationPath
}
);
RouterState.startTransition(transition);
}
else {
console.warn('no matching routes found in popstate');
}
},
_routeAnchor: function(anchor) {
if (anchor.protocol === 'javascript:')
return false;
var route;
switch(RouterState.pathStyle) {
case 'hash':
route = anchor.hash;
if (StringStartsWith(route, RouterState.hashPrefix)) {
route = route.replace(RouterState.hashPrefix, '');
}
break;
case 'path':
route = anchor.pathname;
if (StringStartsWith(route,RouterState.basePath)) {
route = route.replace(RouterState.basePath, '');
}
break;
}
if (route) {
try {
this.transitionTo(route);
return true;
}
catch(err) {
console.warn('anchor route not found', route);
return false;
}
}
return false;
},
_startAnchorRouting: function() {
if (!RouterState.anchorRouting) {
if (this._anchorRoutingListener) {
document.removeEventListener(this._anchorRoutingListener);
delete this._anchorRoutingListener;
}
}
else {
if (!this._anchorRoutingListener) {
this._anchorRoutingListener = document.addEventListener('click', function(ev) {
if (ev.target.nodeName === 'A') {
if (this._routeAnchor(ev.target)) {
ev.preventDefault();
}
}
}.bind(this));
}
}
},
/**
* Starts routing. Gets called automatically on WebComponentsReady unless autoStart is false,
* Then you have to call it manually when your routes are ready.
*/
start: function() {
if (this._started) {
console.warn('RouteManager.start called more than once');
return;
}
this._started = true;
this._setRouteFromLocation();
this._startAnchorRouting();
},
/**
* gets canonical path from window.location
*/
_extractLocationPath: function() {
var path;
if (RouterState.pathStyle === 'path') {
// Parse path-style path
if (!window.location.pathname) {
path = '/';
}
else if (RouterState.basePath) {
var match = window.location.pathname.match(RouterState.basePath + "(.*)");
if (!match) {
console.error("Base path does not match window.location");
}
else
path = match[1];
}
else { // no basePath
path = window.location.pathname;
}
}
else { // _pathStyle === 'hash'
// Parse hash-style path
if (!window.location.hash) {
path = '/';
} else {
path = window.location.hash.replace(RouterState.hashPrefix, '');
if (path[0] != '/') // ordinary hash?
path = undefined;
}
}
return path;
},
_handlePopState: function(ev) {
this._setRouteFromLocation();
},
_handleHashChange: function(ev) {
if (RouterState.pathStyle !== 'hash') {
return;
}
var path = this._extractLocationPath();
if (!path) {
console.warn('hashchange could not extract path',
window.location.hash);
}
},
_decodeAliasPath: function(path) {
if (StringStartsWith(path, RouterState.aliasPathPrefix)) {
return path.replace(RouterState.aliasPathPrefix, '');
}
else {
console.warn('alias path without prefix', path);
return path;
}
}
}
window.addEventListener('WebComponentsReady', function() {
if (RouterState.autoStart) {
RouteManager.start();
}
}.bind(RouteManager));
window.addEventListener('popstate',
RouteManager._handlePopState.bind(RouteManager));
window.addEventListener('hashchange',
RouteManager._handleHashChange.bind(RouteManager));
/**
* Route represents a single route
*/
var Route = function(path, options) {
this.token = RouterState.tokenPrefix + randomString(6);
this.path = path;
this.regexKeys = []; // keys from pathToRegexp
this.regexp = pathToRegexp(this.path, this.regexKeys,
{ sensitive: true, strict: true });
this.pathGenerator = pathToRegexp.compile(this.path);
this.aliasRoutes = []; // routes that are aliased to this one
this.alias = options ? options.alias : undefined;
this.activateExclusive = options ? options.activateExclusive : false;
this.activateStopPropagation = options ? options.activateStopPropagation : false;
this.willDeactivate = options ? options.willDeactivate : undefined;
this.deactivate = options ? options.deactivate : undefined;
this.willActivate = options ? options.willActivate : undefined;
this.activate = options ? options.activate : undefined;
}
/**
* token comparasance routine for [].find
*/
Route.compareByToken = function(token) {
return function(r) {
return r.token === token;
}
}
Route.compareByAlias = function(alias) {
if (!StringStartsWith(alias, RouterState.aliasPathPrefix)) {
throw new Error("compareByAlias called without alias");
}
alias = alias.replace(RouterState.aliasPathPrefix, '');
return function(r) {
return r.alias === alias;
}
}
Route.prototype = {
/**
* @return {array|null} -- routeParams if route matches path
*/
match: function(path) {
var m = this.regexp.exec(path);
if (m) {
return this._matchToRouteParams(m);
}
else {
return null;
}
},
/**
* converts regex match to routeParams map
*/
_matchToRouteParams: function(match) {
var routeParams = {};
for (var i=1; i<match.length; i++) {
if (this.regexKeys[i-1].name) {
routeParams[this.regexKeys[i-1].name] = match[i];
}
else {
routeParams[i-1] = match[i]; // anonymous parameters
}
}
return routeParams;
},
toString: function() {
var s = this.path;
if (this.alias) {
s += ' ' + this.alias;
}
if (this.aliasRoutes.length > 0) {
s += '\n';
this.aliasRoutes.forEach(function(r) {
s += '\t' + r.toString() + '\n';
});
}
return s;
},
addAliasRoute: function(route) {
if (route.alias != this.alias) {
throw new Error("mismatched alias route ", + route.alias + " " + this.alias);
}
this.aliasRoutes.push(route);
},
removeAliasRoute: function(route) {
var idx = this.aliasRoutes.indexOf(route);
if (idx === -1) {
console.warn("removeAliasRoute: nonexistent route", route);
}
else {
this.aliasRoutes.splice(idx, 1);
}
},
getRoutePath: function(routeParams) {
return this.pathGenerator(routeParams);
},
resolveAlias: function() {
return this;
},
/**
* @return {array} -- names of all route parameters. Ex: "/:foo/:bar" => ['foo', 'bar']
*/
keys: function() {
return regexKeysToArray(this.regexKeys);
}
}
var AliasRoute = function(path, options) {
this.token = RouterState.tokenPrefix + randomString(6);
this.alias = RouteManager._decodeAliasPath(path);
this.willDeactivate = options ? options.willDeactivate : undefined;
this.deactivate = options ? options.deactivate : undefined;
this.willActivate = options ? options.willActivate : undefined;
this.activate = options ? options.activate : undefined;
return this.token;
}
AliasRoute.prototype = {
setParent: function(parent) {
if (this.parent) {
this.parent.removeAliasRoute(this);
}
this.parent = parent;
if (this.parent) {
this.parent.addAliasRoute(this);
}
},
toString: function() {
return this.alias;
},
resolveAlias: function() {
if (!this.parent) {
throw new Error('alias cant be resolved');
}
return this.parent;
}
}
/**
* Transition oversees transition lifecycle:
* The lifecycle is:
* source.willDeactivate
* source.deactivate
* destination.willActivate
* destination.activate
*
* willDeactivate/willActivate
*
*/
/**
* @callback Transition~callback
* @param {Transition} transition -- Transition
* @param {function} done -- optional async callback, if omitted call is sync
*
* Call transaction.abort to abort transition in the callback
*
* Recognized errors:
* RedirectError: -- redirect to another route
* DoThisFirstError --
*/
/**
* @param {Route} sources -- [ { route: Route, routeParams: Map }*] sources routes
* @param {Route} destinations -- [ { route: Route, routeParams: Map } * ] destination routes
* @param {object} options
* @param {function} options.updateLocationCb -- function(destinationPath), called when transition is complete
* @param {string} options.destinationPath -- path transitioning to
* @param {function} updateLocationCb --
*/
var Transition = function(sources, destinations, options) {
this.sources = sources;
if (!destinations) {
throw new Error('Transition without destination');
}
this.destinations = destinations;
this._updateLocationCb = options ? options.updateLocationCb : null;
this._destinationPath = options ? options.destinationPath : null;
}
Transition.prototype = {
/**
* @param {object} abortOptions
* @param {string} abortOptions.redirectTo -- abort existing transaction and redirectTo
*/
abort: function(abortOptions) {
if (this.aborted) // only first abort counts
return;
// console.log('abort');
this.aborted = true;
if (abortOptions) {
if (abortOptions.redirectTo) {
RouteManager.transitionTo(abortOptions.redirectTo, abortOptions.redirectParams);
} else if (abortOptions.prerequisite) {
TODO("handle prerequisite");
}
}
this._complete();
},
start: function() {
// if (!this._destinationPath)
// debugger;
// console.log('transition.start', this._destinationPath);
this._willDeactivate();
},
/**
* get callbacks from route, and all its aliasRoutes
* @return {array[callbacks]}
*/
_gatherCallbacks: function(route, callbackName) {