/
router5.js
1608 lines (1396 loc) · 63.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
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
/**
* @license
* @version 0.9.1
* The MIT License (MIT)
*
* Copyright (c) 2015 Thomas Roch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function (window) {
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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var defaultOrConstrained = function defaultOrConstrained(match) {
return '(' + (match ? match.replace(/(^<|>$)/g, '') : '[a-zA-Z0-9-_.~]+') + ')';
};
var rules = [{
// An URL can contain a parameter :paramName
// - and _ are allowed but not in last position
name: 'url-parameter',
pattern: /^:([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})(<(.+?)>)?/,
regex: function regex(match) {
return new RegExp(defaultOrConstrained(match[2]));
}
}, {
// Url parameter (splat)
name: 'url-parameter-splat',
pattern: /^\*([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})/,
regex: /([^\?]*)/
}, {
name: 'url-parameter-matrix',
pattern: /^\;([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})(<(.+?)>)?/,
regex: function regex(match) {
return new RegExp(';' + match[1] + '=' + defaultOrConstrained(match[2]));
}
}, {
// Query parameter: ?param1¶m2
// ?:param1&:param2
name: 'query-parameter',
pattern: /^(?:\?|&)(?:\:)?([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})/
}, // regex: match => new RegExp('(?=(\?|.*&)' + match[0] + '(?=(\=|&|$)))')
{
// Delimiter /
name: 'delimiter',
pattern: /^(\/|\?)/,
regex: function regex(match) {
return new RegExp('\\' + match[0]);
}
}, {
// Sub delimiters
name: 'sub-delimiter',
pattern: /^(\!|\&|\-|_|\.|;)/,
regex: function regex(match) {
return new RegExp(match[0]);
}
}, {
// Unmatched fragment (until delimiter is found)
name: 'fragment',
pattern: /^([0-9a-zA-Z]+?)/,
regex: function regex(match) {
return new RegExp(match[0]);
}
}];
var tokenise = function tokenise(str) {
var tokens = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
// Look for a matching rule
var matched = rules.some(function (rule) {
var match = str.match(rule.pattern);
if (!match) return false;
tokens.push({
type: rule.name,
match: match[0],
val: match.slice(1, 2),
otherVal: match.slice(2),
regex: rule.regex instanceof Function ? rule.regex(match) : rule.regex
});
if (match[0].length < str.length) tokens = tokenise(str.substr(match[0].length), tokens);
return true;
});
// If no rules matched, throw an error (possible malformed path)
if (!matched) {
throw new Error('Could not parse path.');
}
// Return tokens
return tokens;
};
var optTrailingSlash = function optTrailingSlash(source, trailingSlash) {
if (!trailingSlash) return source;
return source.replace(/\\\/$/, '') + '(?:\\/)?';
};
var appendQueryParam = function appendQueryParam(params, param) {
var val = arguments.length <= 2 || arguments[2] === undefined ? '' : arguments[2];
var existingVal = params[param];
if (existingVal === undefined) params[param] = val;else params[param] = Array.isArray(existingVal) ? existingVal.concat(val) : [existingVal, val];
return params;
};
var parseQueryParams = function parseQueryParams(path) {
var searchPart = path.split('?')[1];
if (!searchPart) return {};
return searchPart.split('&').map(function (_) {
return _.split('=');
}).reduce(function (obj, m) {
return appendQueryParam(obj, m[0], m[1]);
}, {});
};
var toSerialisable = function toSerialisable(val) {
return val !== undefined && val !== null && val !== '' ? '=' + val : '';
};
var _serialise = function _serialise(key, val) {
return Array.isArray(val) ? val.map(function (v) {
return _serialise(key, v);
}).join('&') : key + toSerialisable(val);
};
var Path = (function () {
_createClass(Path, null, [{
key: 'createPath',
value: function createPath(path) {
return new Path(path);
}
}, {
key: 'serialise',
value: function serialise(key, val) {
return _serialise(key, val);
}
}]);
function Path(path) {
_classCallCheck(this, Path);
if (!path) throw new Error('Please supply a path');
this.path = path;
this.tokens = tokenise(path);
this.hasUrlParams = this.tokens.filter(function (t) {
return (/^url-parameter/.test(t.type)
);
}).length > 0;
this.hasSpatParam = this.tokens.filter(function (t) {
return (/splat$/.test(t.type)
);
}).length > 0;
this.hasMatrixParams = this.tokens.filter(function (t) {
return (/matrix$/.test(t.type)
);
}).length > 0;
this.hasQueryParams = this.tokens.filter(function (t) {
return t.type === 'query-parameter';
}).length > 0;
// Extract named parameters from tokens
this.urlParams = !this.hasUrlParams ? [] : this.tokens.filter(function (t) {
return (/^url-parameter/.test(t.type)
);
}).map(function (t) {
return t.val.slice(0, 1);
})
// Flatten
.reduce(function (r, v) {
return r.concat(v);
});
// Query params
this.queryParams = !this.hasQueryParams ? [] : this.tokens.filter(function (t) {
return t.type === 'query-parameter';
}).map(function (t) {
return t.val;
})
// Flatten
.reduce(function (r, v) {
return r.concat(v);
});
this.params = this.urlParams.concat(this.queryParams);
// Check if hasQueryParams
// Regular expressions for url part only (full and partial match)
this.source = this.tokens.filter(function (t) {
return t.regex !== undefined;
}).map(function (r) {
return r.regex.source;
}).join('');
}
_createClass(Path, [{
key: '_urlMatch',
value: function _urlMatch(path, regex) {
var _this = this;
var match = path.match(regex);
if (!match) return null;else if (!this.urlParams.length) return {};
// Reduce named params to key-value pairs
return match.slice(1, this.urlParams.length + 1).reduce(function (params, m, i) {
params[_this.urlParams[i]] = m;
return params;
}, {});
}
}, {
key: 'match',
value: function match(path) {
var _this2 = this;
var trailingSlash = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];
// trailingSlash: falsy => non optional, truthy => optional
var source = optTrailingSlash(this.source, trailingSlash);
// Check if exact match
var match = this._urlMatch(path, new RegExp('^' + source + (this.hasQueryParams ? '\\?.*$' : '$')));
// If no match, or no query params, no need to go further
if (!match || !this.hasQueryParams) return match;
// Extract query params
var queryParams = parseQueryParams(path);
var unexpectedQueryParams = Object.keys(queryParams).filter(function (p) {
return _this2.queryParams.indexOf(p) === -1;
});
if (unexpectedQueryParams.length === 0) {
// Extend url match
Object.keys(queryParams).forEach(function (p) {
return match[p] = queryParams[p];
});
return match;
}
return null;
}
}, {
key: 'partialMatch',
value: function partialMatch(path) {
var _this3 = this;
var trailingSlash = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];
// Check if partial match (start of given path matches regex)
// trailingSlash: falsy => non optional, truthy => optional
var source = optTrailingSlash(this.source, trailingSlash);
var match = this._urlMatch(path, new RegExp('^' + source));
if (!match) return match;
if (!this.hasQueryParams) return match;
var queryParams = parseQueryParams(path);
Object.keys(queryParams).filter(function (p) {
return _this3.queryParams.indexOf(p) >= 0;
}).forEach(function (p) {
return appendQueryParam(match, p, queryParams[p]);
});
return match;
}
}, {
key: 'build',
value: function build() {
var params = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var opts = arguments.length <= 1 || arguments[1] === undefined ? { ignoreConstraints: false, ignoreSearch: false } : arguments[1];
// Check all params are provided (not search parameters which are optional)
if (this.urlParams.some(function (p) {
return params[p] === undefined;
})) throw new Error('Missing parameters');
// Check constraints
if (!opts.ignoreConstraints) {
var constraintsPassed = this.tokens.filter(function (t) {
return (/^url-parameter/.test(t.type) && !/-splat$/.test(t.type)
);
}).every(function (t) {
return new RegExp('^' + defaultOrConstrained(t.otherVal[0]) + '$').test(params[t.val]);
});
if (!constraintsPassed) throw new Error('Some parameters are of invalid format');
}
var base = this.tokens.filter(function (t) {
return t.type !== 'query-parameter';
}).map(function (t) {
if (t.type === 'url-parameter-matrix') return ';' + t.val[0] + '=' + params[t.val[0]];
return (/^url-parameter/.test(t.type) ? params[t.val[0]] : t.match
);
}).join('');
if (opts.ignoreSearch) return base;
var searchPart = this.queryParams.filter(function (p) {
return Object.keys(params).indexOf(p) !== -1;
}).map(function (p) {
return _serialise(p, params[p]);
}).join('&');
return base + (searchPart ? '?' + searchPart : '');
}
}]);
return Path;
})();
var isSerialisable = function isSerialisable(val) {
return val !== undefined && val !== null && val !== '';
};
var removeQueryParamsFromPath = function removeQueryParamsFromPath(path, params) {
if (path.indexOf('?') === -1) return path;
var splitPath = path.split('?');
var pathPart = splitPath[0];
var searchPart = splitPath[1];
var remainingSearchParams = searchPart.split('&').reduce(function (obj, p) {
var splitParam = p.split('=');
var key = splitParam[0];
var val = splitParam[1];
if (params.indexOf(key) === -1) obj[key] = val || '';
return obj;
}, {});
var remainingSearchPart = Object.keys(remainingSearchParams).map(function (p) {
return [p].concat(isSerialisable(remainingSearchParams[p]) ? remainingSearchParams[p] : []);
}).map(function (p) {
return p.join('=');
}).join('&');
return pathPart + (remainingSearchPart ? '?' + remainingSearchPart : '');
};
var RouteNode = (function () {
function RouteNode() {
var name = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
var path = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
var childRoutes = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2];
_classCallCheck(this, RouteNode);
this.name = name;
this.path = path;
this.parser = path ? new Path(path) : null;
this.children = [];
this.add(childRoutes);
return this;
}
_createClass(RouteNode, [{
key: 'add',
value: function add(route) {
var _this = this;
if (route === undefined || route === null) return;
if (route instanceof Array) {
route.forEach(function (r) {
return _this.add(r);
});
return;
}
if (!(route instanceof RouteNode) && !(route instanceof Object)) {
throw new Error('RouteNode.add() expects routes to be an Object or an instance of RouteNode.');
}
if (route instanceof Object) {
if (!route.name || !route.path) {
throw new Error('RouteNode.add() expects routes to have a name and a path defined.');
}
route = new RouteNode(route.name, route.path, route.children);
}
// Check duplicated routes
if (this.children.map(function (child) {
return child.name;
}).indexOf(route.name) !== -1) {
throw new Error('Alias "' + route.name + '" is already defined in route node');
}
// Check duplicated paths
if (this.children.map(function (child) {
return child.path;
}).indexOf(route.path) !== -1) {
throw new Error('Path "' + route.path + '" is already defined in route node');
}
var names = route.name.split('.');
if (names.length === 1) {
this.children.push(route);
// Push greedy spats to the bottom of the pile
this.children.sort(function (a, b) {
// '/' last
if (a.path === '/') return 1;
if (b.path === '/') return -1;
var aHasParams = a.parser.hasUrlParams || a.parser.hasSpatParam;
var bHasParams = b.parser.hasUrlParams || b.parser.hasSpatParam;
// No params first, sort by length descending
if (!aHasParams && !bHasParams) {
return a.path && b.path ? a.path.length < b.path.length ? 1 : -1 : 0;
}
// Params last
if (aHasParams && !bHasParams) return 1;
if (!aHasParams && bHasParams) return -1;
// Spat params last
if (!a.parser.hasSpatParam && b.parser.hasSpatParam) return -1;
if (!b.parser.hasSpatParam && a.parser.hasSpatParam) return 1;
// Sort by number of segments descending
var aSegments = (a.path.match(/\//g) || []).length;
var bSegments = (b.path.match(/\//g) || []).length;
if (aSegments < bSegments) return 1;
return 0;
});
} else {
// Locate parent node
var segments = this.getSegmentsByName(names.slice(0, -1).join('.'));
if (segments) {
segments[segments.length - 1].add(new RouteNode(names[names.length - 1], route.path, route.children));
} else {
throw new Error('Could not add route named \'' + route.name + '\', parent is missing.');
}
}
return this;
}
}, {
key: 'addNode',
value: function addNode(name, params) {
this.add(new RouteNode(name, params));
return this;
}
}, {
key: 'getSegmentsByName',
value: function getSegmentsByName(routeName) {
var findSegmentByName = function findSegmentByName(name, routes) {
var filteredRoutes = routes.filter(function (r) {
return r.name === name;
});
return filteredRoutes.length ? filteredRoutes[0] : undefined;
};
var segments = [];
var names = routeName.split('.');
var routes = this.children;
var matched = names.every(function (name) {
var segment = findSegmentByName(name, routes);
if (segment) {
routes = segment.children;
segments.push(segment);
return true;
}
return false;
});
return matched ? segments : null;
}
}, {
key: 'getSegmentsMatchingPath',
value: function getSegmentsMatchingPath(path) {
var trailingSlash = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var matchChildren = function matchChildren(nodes, pathSegment, segments) {
var _loop = function (i) {
var child = nodes[i];
// Partially match path
var match = child.parser.partialMatch(pathSegment);
var remainingPath = undefined,
remainingSearch = undefined;
if (!match && trailingSlash) {
// Try with optional trailing slash
match = child.parser.match(pathSegment, true);
remainingPath = '';
} else if (match) {
// Remove consumed segment from path
var consumedPath = child.parser.build(match, { ignoreSearch: true });
remainingPath = removeQueryParamsFromPath(pathSegment.replace(consumedPath, ''), child.parser.queryParams);
if (trailingSlash && remainingPath === '/' && !/\/$/.test(consumedPath)) {
remainingPath = '';
}
}
if (match) {
segments.push(child);
Object.keys(match).forEach(function (param) {
return segments.params[param] = match[param];
});
// If fully matched
if (!remainingPath.length) {
return {
v: segments
};
}
// If no children to match against but unmatched path left
if (!child.children.length) {
return {
v: null
};
}
// Else: remaining path and children
return {
v: matchChildren(child.children, remainingPath, segments)
};
}
};
// for (child of node.children) {
for (var i in nodes) {
var _ret = _loop(i);
if (typeof _ret === 'object') return _ret.v;
}
return null;
};
var startingNodes = this.parser ? [this] : this.children;
var segments = [];
segments.params = {};
return matchChildren(startingNodes, path, segments);
}
}, {
key: 'getPathFromSegments',
value: function getPathFromSegments(segments) {
return segments ? segments.map(function (segment) {
return segment.path;
}).join('') : null;
}
}, {
key: 'getPath',
value: function getPath(routeName) {
return this.getPathFromSegments(this.getSegmentsByName(routeName));
}
}, {
key: 'buildPathFromSegments',
value: function buildPathFromSegments(segments) {
var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (!segments) return null;
var searchParams = segments.filter(function (s) {
return s.parser.hasQueryParams;
}).map(function (s) {
return s.parser.queryParams;
});
var searchPart = !searchParams.length ? null : searchParams.reduce(function (queryParams, params) {
return queryParams.concat(params);
}).filter(function (p) {
return Object.keys(params).indexOf(p) !== -1;
}).map(function (p) {
return Path.serialise(p, params[p]);
}).join('&');
return segments.map(function (segment) {
return segment.parser.build(params, { ignoreSearch: true });
}).join('') + (searchPart ? '?' + searchPart : '');
}
}, {
key: 'buildPath',
value: function buildPath(routeName) {
var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
return this.buildPathFromSegments(this.getSegmentsByName(routeName), params);
}
}, {
key: 'getMatchPathFromSegments',
value: function getMatchPathFromSegments(segments) {
if (!segments || !segments.length) return null;
var name = segments.map(function (segment) {
return segment.name;
}).join('.');
var params = segments.params;
return { name: name, params: params };
}
}, {
key: 'matchPath',
value: function matchPath(path) {
var trailingSlash = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
return this.getMatchPathFromSegments(this.getSegmentsMatchingPath(path, trailingSlash));
}
}]);
return RouteNode;
})();
var constants = {
ROUTER_NOT_STARTED: 'NOT_STARTED',
ROUTER_ALREADY_STARTED: 'ALREADY_STARTED',
ROUTE_NOT_FOUND: 'ROUTE_NOT_FOUND',
SAME_STATES: 'SAME_STATES',
CANNOT_DEACTIVATE: 'CANNOT_DEACTIVATE',
CANNOT_ACTIVATE: 'CANNOT_ACTIVATE',
TRANSITION_ERR: 'TRANSITION_ERR',
NODE_LISTENER_ERR: 'NODE_ERR',
TRANSITION_CANCELLED: 'CANCELLED'
};/**
* Dumb functions
*/
function identity() {
var _arguments = arguments;
return function () {
return _arguments[0];
};
}
var noop = function noop() {};
/**
* Browser detection
*/
var isBrowser = typeof window !== 'undefined';
/**
* Browser functions needed by router5
*/
var getBase = function getBase() {
return window.location.pathname.replace(/\/$/, '');
};
var pushState = function pushState(state, title, path) {
return window.history.pushState(state, title, path);
};
var replaceState = function replaceState(state, title, path) {
return window.history.replaceState(state, title, path);
};
var addPopstateListener = function addPopstateListener(fn) {
return window.addEventListener('popstate', fn);
};
var removePopstateListener = function removePopstateListener(fn) {
return window.removeEventListener('popstate', fn);
};
var getLocation = function getLocation(opts) {
var path = opts.useHash ? window.location.hash.replace(new RegExp('^#' + opts.hashPrefix), '') : window.location.pathname.replace(new RegExp('^' + opts.base), '');
return path + window.location.search;
};
var getState = function getState() {
return window.history.state;
};
/**
* Export browser object
*/
var browser = {};
if (isBrowser) {
browser = { getBase: getBase, pushState: pushState, replaceState: replaceState, addPopstateListener: addPopstateListener, removePopstateListener: removePopstateListener, getLocation: getLocation, getState: getState };
} else {
browser = {
getBase: identity(''),
pushState: noop,
replaceState: noop,
addPopstateListener: noop,
removePopstateListener: noop,
getLocation: identity(''),
getState: identity(null)
};
}
function asyncProcess(isCancelled, functions, toState, fromState, callback) {
var allowNoResult = arguments.length <= 5 || arguments[5] === undefined ? false : arguments[5];
isCancelled = isCancelled || function () {
return false;
};
var remainingSteps = functions || [];
var processFn = function processFn(done) {
if (!remainingSteps.length) return true;
var len = remainingSteps[0].length;
var res = remainingSteps[0](toState, fromState, done);
if (typeof res === 'boolean') {
done(res ? null : true);
} else if (res && typeof res.then === 'function') {
res.then(function () {
return done(null);
}, function () {
return done(true);
});
} else if (len < 3 && allowNoResult) {
done(null);
}
return false;
};
var iterate = function iterate(err) {
if (err) callback(err);else {
remainingSteps = remainingSteps.slice(1);
next();
}
};
var next = function next() {
if (isCancelled()) {
callback(null);
} else {
var finished = processFn(iterate);
if (finished) callback(null);
}
};
next();
}
function transitionPath(toState, fromState) {
var nameToIDs = function nameToIDs(name) {
return name.split('.').reduce(function (ids, name) {
return ids.concat(ids.length ? ids[ids.length - 1] + '.' + name : name);
}, []);
};
var i = undefined;
var fromStateIds = fromState ? nameToIDs(fromState.name) : [];
var toStateIds = nameToIDs(toState.name);
var maxI = Math.min(fromStateIds.length, toStateIds.length);
if (fromState && fromState.name === toState.name) i = Math.max(maxI - 1, 0);else {
for (i = 0; i < maxI; i += 1) {
if (fromStateIds[i] !== toStateIds[i]) break;
}
}
var toDeactivate = fromStateIds.slice(i).reverse();
var toActivate = toStateIds.slice(i);
var intersection = fromState && i > 0 ? fromStateIds[i - 1] : '';
return { intersection: intersection, toDeactivate: toDeactivate, toActivate: toActivate };
}
function transition(router, toState, fromState, callback) {
var cancelled = false;
var isCancelled = function isCancelled() {
return cancelled;
};
var cancel = function cancel() {
return cancelled = true;
};
var done = function done(err) {
return callback(cancelled ? constants.TRANSITION_CANCELLED : err);
};
var _transitionPath = transitionPath(toState, fromState);
var intersection = _transitionPath.intersection;
var toDeactivate = _transitionPath.toDeactivate;
var toActivate = _transitionPath.toActivate;
var canDeactivate = function canDeactivate(toState, fromState, cb) {
var canDeactivateFunctions = toDeactivate.map(function (name) {
return router._cmps[name];
}).filter(function (comp) {
return comp && comp.canDeactivate;
}).map(function (comp) {
return comp.canDeactivate;
});
asyncProcess(isCancelled, canDeactivateFunctions, toState, fromState, function (err) {
return cb(err ? constants.CANNOT_DEACTIVATE : null);
});
};
var canActivate = function canActivate(toState, fromState, cb) {
var canActivateFunctions = toActivate.map(function (name) {
return router._canAct[name];
}).filter(function (_) {
return _;
});
asyncProcess(isCancelled, canActivateFunctions, toState, fromState, function (err) {
return cb(err ? constants.CANNOT_ACTIVATE : null);
});
};
var middlewareFn = router._onTr;
var middleware = function middleware(toState, fromState, cb) {
var mwareFunction = [middlewareFn];
asyncProcess(isCancelled, mwareFunction, toState, fromState, function (err) {
return cb(err ? constants.TRANSITION_ERR : null);
});
};
var nodeListenerFn = router._cbs['^' + intersection];
var nodeListener = function nodeListener(toState, fromState, cb) {
var listeners = nodeListenerFn;
asyncProcess(isCancelled, listeners, toState, fromState, function (err) {
return cb(err ? constants.NODE_LISTENER_ERR : null);
}, true);
};
var pipeline = (fromState ? [canDeactivate] : []).concat(canActivate).concat(middlewareFn ? middleware : []).concat(nodeListenerFn && nodeListenerFn.length ? nodeListener : []);
asyncProcess(isCancelled, pipeline, toState, fromState, done);
return cancel;
}
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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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: constants,
/**
* 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: 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 RouteNode ? routes : new RouteNode('', '', 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 = browser.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 === constants.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) {