-
Notifications
You must be signed in to change notification settings - Fork 1
/
vue-router.js
2709 lines (2357 loc) · 75.5 KB
/
vue-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
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
/*!
* vue-router v0.7.13
* (c) 2016 Evan You
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
global.VueRouter = factory();
}(this, function () { 'use strict';
var babelHelpers = {};
babelHelpers.classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
function Target(path, matcher, delegate) {
this.path = path;
this.matcher = matcher;
this.delegate = delegate;
}
Target.prototype = {
to: function to(target, callback) {
var delegate = this.delegate;
if (delegate && delegate.willAddRoute) {
target = delegate.willAddRoute(this.matcher.target, target);
}
this.matcher.add(this.path, target);
if (callback) {
if (callback.length === 0) {
throw new Error("You must have an argument in the function passed to `to`");
}
this.matcher.addChild(this.path, target, callback, this.delegate);
}
return this;
}
};
function Matcher(target) {
this.routes = {};
this.children = {};
this.target = target;
}
Matcher.prototype = {
add: function add(path, handler) {
this.routes[path] = handler;
},
addChild: function addChild(path, target, callback, delegate) {
var matcher = new Matcher(target);
this.children[path] = matcher;
var match = generateMatch(path, matcher, delegate);
if (delegate && delegate.contextEntered) {
delegate.contextEntered(target, match);
}
callback(match);
}
};
function generateMatch(startingPath, matcher, delegate) {
return function (path, nestedCallback) {
var fullPath = startingPath + path;
if (nestedCallback) {
nestedCallback(generateMatch(fullPath, matcher, delegate));
} else {
return new Target(startingPath + path, matcher, delegate);
}
};
}
function addRoute(routeArray, path, handler) {
var len = 0;
for (var i = 0, l = routeArray.length; i < l; i++) {
len += routeArray[i].path.length;
}
path = path.substr(len);
var route = { path: path, handler: handler };
routeArray.push(route);
}
function eachRoute(baseRoute, matcher, callback, binding) {
var routes = matcher.routes;
for (var path in routes) {
if (routes.hasOwnProperty(path)) {
var routeArray = baseRoute.slice();
addRoute(routeArray, path, routes[path]);
if (matcher.children[path]) {
eachRoute(routeArray, matcher.children[path], callback, binding);
} else {
callback.call(binding, routeArray);
}
}
}
}
function map (callback, addRouteCallback) {
var matcher = new Matcher();
callback(generateMatch("", matcher, this.delegate));
eachRoute([], matcher, function (route) {
if (addRouteCallback) {
addRouteCallback(this, route);
} else {
this.add(route);
}
}, this);
}
var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
var noWarning = false;
function warn(msg) {
if (!noWarning && typeof console !== 'undefined') {
console.error('[vue-router] ' + msg);
}
}
function tryDecode(uri, asComponent) {
try {
return asComponent ? decodeURIComponent(uri) : decodeURI(uri);
} catch (e) {
warn('malformed URI' + (asComponent ? ' component: ' : ': ') + uri);
}
}
function isArray(test) {
return Object.prototype.toString.call(test) === "[object Array]";
}
// A Segment represents a segment in the original route description.
// Each Segment type provides an `eachChar` and `regex` method.
//
// The `eachChar` method invokes the callback with one or more character
// specifications. A character specification consumes one or more input
// characters.
//
// The `regex` method returns a regex fragment for the segment. If the
// segment is a dynamic of star segment, the regex fragment also includes
// a capture.
//
// A character specification contains:
//
// * `validChars`: a String with a list of all valid characters, or
// * `invalidChars`: a String with a list of all invalid characters
// * `repeat`: true if the character specification can repeat
function StaticSegment(string) {
this.string = string;
}
StaticSegment.prototype = {
eachChar: function eachChar(callback) {
var string = this.string,
ch;
for (var i = 0, l = string.length; i < l; i++) {
ch = string.charAt(i);
callback({ validChars: ch });
}
},
regex: function regex() {
return this.string.replace(escapeRegex, '\\$1');
},
generate: function generate() {
return this.string;
}
};
function DynamicSegment(name) {
this.name = name;
}
DynamicSegment.prototype = {
eachChar: function eachChar(callback) {
callback({ invalidChars: "/", repeat: true });
},
regex: function regex() {
return "([^/]+)";
},
generate: function generate(params) {
var val = params[this.name];
return val == null ? ":" + this.name : val;
}
};
function StarSegment(name) {
this.name = name;
}
StarSegment.prototype = {
eachChar: function eachChar(callback) {
callback({ invalidChars: "", repeat: true });
},
regex: function regex() {
return "(.+)";
},
generate: function generate(params) {
var val = params[this.name];
return val == null ? ":" + this.name : val;
}
};
function EpsilonSegment() {}
EpsilonSegment.prototype = {
eachChar: function eachChar() {},
regex: function regex() {
return "";
},
generate: function generate() {
return "";
}
};
function parse(route, names, specificity) {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (route.charAt(0) === "/") {
route = route.substr(1);
}
var segments = route.split("/"),
results = [];
// A routes has specificity determined by the order that its different segments
// appear in. This system mirrors how the magnitude of numbers written as strings
// works.
// Consider a number written as: "abc". An example would be "200". Any other number written
// "xyz" will be smaller than "abc" so long as `a > z`. For instance, "199" is smaller
// then "200", even though "y" and "z" (which are both 9) are larger than "0" (the value
// of (`b` and `c`). This is because the leading symbol, "2", is larger than the other
// leading symbol, "1".
// The rule is that symbols to the left carry more weight than symbols to the right
// when a number is written out as a string. In the above strings, the leading digit
// represents how many 100's are in the number, and it carries more weight than the middle
// number which represents how many 10's are in the number.
// This system of number magnitude works well for route specificity, too. A route written as
// `a/b/c` will be more specific than `x/y/z` as long as `a` is more specific than
// `x`, irrespective of the other parts.
// Because of this similarity, we assign each type of segment a number value written as a
// string. We can find the specificity of compound routes by concatenating these strings
// together, from left to right. After we have looped through all of the segments,
// we convert the string to a number.
specificity.val = '';
for (var i = 0, l = segments.length; i < l; i++) {
var segment = segments[i],
match;
if (match = segment.match(/^:([^\/]+)$/)) {
results.push(new DynamicSegment(match[1]));
names.push(match[1]);
specificity.val += '3';
} else if (match = segment.match(/^\*([^\/]+)$/)) {
results.push(new StarSegment(match[1]));
specificity.val += '2';
names.push(match[1]);
} else if (segment === "") {
results.push(new EpsilonSegment());
specificity.val += '1';
} else {
results.push(new StaticSegment(segment));
specificity.val += '4';
}
}
specificity.val = +specificity.val;
return results;
}
// A State has a character specification and (`charSpec`) and a list of possible
// subsequent states (`nextStates`).
//
// If a State is an accepting state, it will also have several additional
// properties:
//
// * `regex`: A regular expression that is used to extract parameters from paths
// that reached this accepting state.
// * `handlers`: Information on how to convert the list of captures into calls
// to registered handlers with the specified parameters
// * `types`: How many static, dynamic or star segments in this route. Used to
// decide which route to use if multiple registered routes match a path.
//
// Currently, State is implemented naively by looping over `nextStates` and
// comparing a character specification against a character. A more efficient
// implementation would use a hash of keys pointing at one or more next states.
function State(charSpec) {
this.charSpec = charSpec;
this.nextStates = [];
}
State.prototype = {
get: function get(charSpec) {
var nextStates = this.nextStates;
for (var i = 0, l = nextStates.length; i < l; i++) {
var child = nextStates[i];
var isEqual = child.charSpec.validChars === charSpec.validChars;
isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars;
if (isEqual) {
return child;
}
}
},
put: function put(charSpec) {
var state;
// If the character specification already exists in a child of the current
// state, just return that state.
if (state = this.get(charSpec)) {
return state;
}
// Make a new state for the character spec
state = new State(charSpec);
// Insert the new state as a child of the current state
this.nextStates.push(state);
// If this character specification repeats, insert the new state as a child
// of itself. Note that this will not trigger an infinite loop because each
// transition during recognition consumes a character.
if (charSpec.repeat) {
state.nextStates.push(state);
}
// Return the new state
return state;
},
// Find a list of child states matching the next character
match: function match(ch) {
// DEBUG "Processing `" + ch + "`:"
var nextStates = this.nextStates,
child,
charSpec,
chars;
// DEBUG " " + debugState(this)
var returned = [];
for (var i = 0, l = nextStates.length; i < l; i++) {
child = nextStates[i];
charSpec = child.charSpec;
if (typeof (chars = charSpec.validChars) !== 'undefined') {
if (chars.indexOf(ch) !== -1) {
returned.push(child);
}
} else if (typeof (chars = charSpec.invalidChars) !== 'undefined') {
if (chars.indexOf(ch) === -1) {
returned.push(child);
}
}
}
return returned;
}
/** IF DEBUG
, debug: function() {
var charSpec = this.charSpec,
debug = "[",
chars = charSpec.validChars || charSpec.invalidChars;
if (charSpec.invalidChars) { debug += "^"; }
debug += chars;
debug += "]";
if (charSpec.repeat) { debug += "+"; }
return debug;
}
END IF **/
};
/** IF DEBUG
function debug(log) {
console.log(log);
}
function debugState(state) {
return state.nextStates.map(function(n) {
if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; }
return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )";
}).join(", ")
}
END IF **/
// Sort the routes by specificity
function sortSolutions(states) {
return states.sort(function (a, b) {
return b.specificity.val - a.specificity.val;
});
}
function recognizeChar(states, ch) {
var nextStates = [];
for (var i = 0, l = states.length; i < l; i++) {
var state = states[i];
nextStates = nextStates.concat(state.match(ch));
}
return nextStates;
}
var oCreate = Object.create || function (proto) {
function F() {}
F.prototype = proto;
return new F();
};
function RecognizeResults(queryParams) {
this.queryParams = queryParams || {};
}
RecognizeResults.prototype = oCreate({
splice: Array.prototype.splice,
slice: Array.prototype.slice,
push: Array.prototype.push,
length: 0,
queryParams: null
});
function findHandler(state, path, queryParams) {
var handlers = state.handlers,
regex = state.regex;
var captures = path.match(regex),
currentCapture = 1;
var result = new RecognizeResults(queryParams);
for (var i = 0, l = handlers.length; i < l; i++) {
var handler = handlers[i],
names = handler.names,
params = {};
for (var j = 0, m = names.length; j < m; j++) {
params[names[j]] = captures[currentCapture++];
}
result.push({ handler: handler.handler, params: params, isDynamic: !!names.length });
}
return result;
}
function addSegment(currentState, segment) {
segment.eachChar(function (ch) {
var state;
currentState = currentState.put(ch);
});
return currentState;
}
function decodeQueryParamPart(part) {
// http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
part = part.replace(/\+/gm, '%20');
return tryDecode(part, true);
}
// The main interface
var RouteRecognizer = function RouteRecognizer() {
this.rootState = new State();
this.names = {};
};
RouteRecognizer.prototype = {
add: function add(routes, options) {
var currentState = this.rootState,
regex = "^",
specificity = {},
handlers = [],
allSegments = [],
name;
var isEmpty = true;
for (var i = 0, l = routes.length; i < l; i++) {
var route = routes[i],
names = [];
var segments = parse(route.path, names, specificity);
allSegments = allSegments.concat(segments);
for (var j = 0, m = segments.length; j < m; j++) {
var segment = segments[j];
if (segment instanceof EpsilonSegment) {
continue;
}
isEmpty = false;
// Add a "/" for the new segment
currentState = currentState.put({ validChars: "/" });
regex += "/";
// Add a representation of the segment to the NFA and regex
currentState = addSegment(currentState, segment);
regex += segment.regex();
}
var handler = { handler: route.handler, names: names };
handlers.push(handler);
}
if (isEmpty) {
currentState = currentState.put({ validChars: "/" });
regex += "/";
}
currentState.handlers = handlers;
currentState.regex = new RegExp(regex + "$");
currentState.specificity = specificity;
if (name = options && options.as) {
this.names[name] = {
segments: allSegments,
handlers: handlers
};
}
},
handlersFor: function handlersFor(name) {
var route = this.names[name],
result = [];
if (!route) {
throw new Error("There is no route named " + name);
}
for (var i = 0, l = route.handlers.length; i < l; i++) {
result.push(route.handlers[i]);
}
return result;
},
hasRoute: function hasRoute(name) {
return !!this.names[name];
},
generate: function generate(name, params) {
var route = this.names[name],
output = "";
if (!route) {
throw new Error("There is no route named " + name);
}
var segments = route.segments;
for (var i = 0, l = segments.length; i < l; i++) {
var segment = segments[i];
if (segment instanceof EpsilonSegment) {
continue;
}
output += "/";
output += segment.generate(params);
}
if (output.charAt(0) !== '/') {
output = '/' + output;
}
if (params && params.queryParams) {
output += this.generateQueryString(params.queryParams);
}
return output;
},
generateQueryString: function generateQueryString(params) {
var pairs = [];
var keys = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
keys.push(key);
}
}
keys.sort();
for (var i = 0, len = keys.length; i < len; i++) {
key = keys[i];
var value = params[key];
if (value == null) {
continue;
}
var pair = encodeURIComponent(key);
if (isArray(value)) {
for (var j = 0, l = value.length; j < l; j++) {
var arrayPair = key + '[]' + '=' + encodeURIComponent(value[j]);
pairs.push(arrayPair);
}
} else {
pair += "=" + encodeURIComponent(value);
pairs.push(pair);
}
}
if (pairs.length === 0) {
return '';
}
return "?" + pairs.join("&");
},
parseQueryString: function parseQueryString(queryString) {
var pairs = queryString.split("&"),
queryParams = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('='),
key = decodeQueryParamPart(pair[0]),
keyLength = key.length,
isArray = false,
value;
if (pair.length === 1) {
value = 'true';
} else {
//Handle arrays
if (keyLength > 2 && key.slice(keyLength - 2) === '[]') {
isArray = true;
key = key.slice(0, keyLength - 2);
if (!queryParams[key]) {
queryParams[key] = [];
}
}
value = pair[1] ? decodeQueryParamPart(pair[1]) : '';
}
if (isArray) {
queryParams[key].push(value);
} else {
queryParams[key] = value;
}
}
return queryParams;
},
recognize: function recognize(path, silent) {
noWarning = silent;
var states = [this.rootState],
pathLen,
i,
l,
queryStart,
queryParams = {},
isSlashDropped = false;
queryStart = path.indexOf('?');
if (queryStart !== -1) {
var queryString = path.substr(queryStart + 1, path.length);
path = path.substr(0, queryStart);
if (queryString) {
queryParams = this.parseQueryString(queryString);
}
}
path = tryDecode(path);
if (!path) return;
// DEBUG GROUP path
if (path.charAt(0) !== "/") {
path = "/" + path;
}
pathLen = path.length;
if (pathLen > 1 && path.charAt(pathLen - 1) === "/") {
path = path.substr(0, pathLen - 1);
isSlashDropped = true;
}
for (i = 0, l = path.length; i < l; i++) {
states = recognizeChar(states, path.charAt(i));
if (!states.length) {
break;
}
}
// END DEBUG GROUP
var solutions = [];
for (i = 0, l = states.length; i < l; i++) {
if (states[i].handlers) {
solutions.push(states[i]);
}
}
states = sortSolutions(solutions);
var state = solutions[0];
if (state && state.handlers) {
// if a trailing slash was dropped and a star segment is the last segment
// specified, put the trailing slash back
if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") {
path = path + "/";
}
return findHandler(state, path, queryParams);
}
}
};
RouteRecognizer.prototype.map = map;
var genQuery = RouteRecognizer.prototype.generateQueryString;
// export default for holding the Vue reference
var exports$1 = {};
/**
* Warn stuff.
*
* @param {String} msg
*/
function warn$1(msg) {
/* istanbul ignore next */
if (typeof console !== 'undefined') {
console.error('[vue-router] ' + msg);
}
}
/**
* Resolve a relative path.
*
* @param {String} base
* @param {String} relative
* @param {Boolean} append
* @return {String}
*/
function resolvePath(base, relative, append) {
var query = base.match(/(\?.*)$/);
if (query) {
query = query[1];
base = base.slice(0, -query.length);
}
// a query!
if (relative.charAt(0) === '?') {
return base + relative;
}
var stack = base.split('/');
// remove trailing segment if:
// - not appending
// - appending to trailing slash (last segment is empty)
if (!append || !stack[stack.length - 1]) {
stack.pop();
}
// resolve relative path
var segments = relative.replace(/^\//, '').split('/');
for (var i = 0; i < segments.length; i++) {
var segment = segments[i];
if (segment === '.') {
continue;
} else if (segment === '..') {
stack.pop();
} else {
stack.push(segment);
}
}
// ensure leading slash
if (stack[0] !== '') {
stack.unshift('');
}
return stack.join('/');
}
/**
* Forgiving check for a promise
*
* @param {Object} p
* @return {Boolean}
*/
function isPromise(p) {
return p && typeof p.then === 'function';
}
/**
* Retrive a route config field from a component instance
* OR a component contructor.
*
* @param {Function|Vue} component
* @param {String} name
* @return {*}
*/
function getRouteConfig(component, name) {
var options = component && (component.$options || component.options);
return options && options.route && options.route[name];
}
/**
* Resolve an async component factory. Have to do a dirty
* mock here because of Vue core's internal API depends on
* an ID check.
*
* @param {Object} handler
* @param {Function} cb
*/
var resolver = undefined;
function resolveAsyncComponent(handler, cb) {
if (!resolver) {
resolver = {
resolve: exports$1.Vue.prototype._resolveComponent,
$options: {
components: {
_: handler.component
}
}
};
} else {
resolver.$options.components._ = handler.component;
}
resolver.resolve('_', function (Component) {
handler.component = Component;
cb(Component);
});
}
/**
* Map the dynamic segments in a path to params.
*
* @param {String} path
* @param {Object} params
* @param {Object} query
*/
function mapParams(path, params, query) {
if (params === undefined) params = {};
path = path.replace(/:([^\/]+)/g, function (_, key) {
var val = params[key];
/* istanbul ignore if */
if (!val) {
warn$1('param "' + key + '" not found when generating ' + 'path for "' + path + '" with params ' + JSON.stringify(params));
}
return val || '';
});
if (query) {
path += genQuery(query);
}
return path;
}
var hashRE = /#.*$/;
var HTML5History = (function () {
function HTML5History(_ref) {
var root = _ref.root;
var onChange = _ref.onChange;
babelHelpers.classCallCheck(this, HTML5History);
if (root && root !== '/') {
// make sure there's the starting slash
if (root.charAt(0) !== '/') {
root = '/' + root;
}
// remove trailing slash
this.root = root.replace(/\/$/, '');
this.rootRE = new RegExp('^\\' + this.root);
} else {
this.root = null;
}
this.onChange = onChange;
// check base tag
var baseEl = document.querySelector('base');
this.base = baseEl && baseEl.getAttribute('href');
}
HTML5History.prototype.start = function start() {
var _this = this;
this.listener = function (e) {
var url = location.pathname + location.search;
if (_this.root) {
url = url.replace(_this.rootRE, '');
}
_this.onChange(url, e && e.state, location.hash);
};
window.addEventListener('popstate', this.listener);
this.listener();
};
HTML5History.prototype.stop = function stop() {
window.removeEventListener('popstate', this.listener);
};
HTML5History.prototype.go = function go(path, replace, append) {
var url = this.formatPath(path, append);
if (replace) {
history.replaceState({}, '', url);
} else {
// record scroll position by replacing current state
history.replaceState({
pos: {
x: window.pageXOffset,
y: window.pageYOffset
}
}, '', location.href);
// then push new state
history.pushState({}, '', url);
}
var hashMatch = path.match(hashRE);
var hash = hashMatch && hashMatch[0];
path = url
// strip hash so it doesn't mess up params
.replace(hashRE, '')
// remove root before matching
.replace(this.rootRE, '');
this.onChange(path, null, hash);
};
HTML5History.prototype.formatPath = function formatPath(path, append) {
return path.charAt(0) === '/'
// absolute path
? this.root ? this.root + '/' + path.replace(/^\//, '') : path : resolvePath(this.base || location.pathname, path, append);
};
return HTML5History;
})();
var HashHistory = (function () {
function HashHistory(_ref) {
var hashbang = _ref.hashbang;
var onChange = _ref.onChange;
babelHelpers.classCallCheck(this, HashHistory);
this.hashbang = hashbang;
this.onChange = onChange;
}
HashHistory.prototype.start = function start() {
var self = this;
this.listener = function () {
var path = location.hash;
var raw = path.replace(/^#!?/, '');
// always
if (raw.charAt(0) !== '/') {
raw = '/' + raw;
}
var formattedPath = self.formatPath(raw);
if (formattedPath !== path) {
location.replace(formattedPath);
return;
}
// determine query
// note it's possible to have queries in both the actual URL
// and the hash fragment itself.
var query = location.search && path.indexOf('?') > -1 ? '&' + location.search.slice(1) : location.search;
self.onChange(path.replace(/^#!?/, '') + query);
};
window.addEventListener('hashchange', this.listener);
this.listener();
};
HashHistory.prototype.stop = function stop() {
window.removeEventListener('hashchange', this.listener);
};
HashHistory.prototype.go = function go(path, replace, append) {
path = this.formatPath(path, append);
if (replace) {
location.replace(path);
} else {
location.hash = path;
}
};
HashHistory.prototype.formatPath = function formatPath(path, append) {
var isAbsoloute = path.charAt(0) === '/';
var prefix = '#' + (this.hashbang ? '!' : '');