kdu-router 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2505 @@
1
+ /**
2
+ * kdu-router v2.7.0
3
+ * (c) 2022 NKDuy
4
+ * @license MIT
5
+ */
6
+ /* */
7
+
8
+ function assert (condition, message) {
9
+ if (!condition) {
10
+ throw new Error(("[kdu-router] " + message))
11
+ }
12
+ }
13
+
14
+ function warn (condition, message) {
15
+ if (process.env.NODE_ENV !== 'production' && !condition) {
16
+ typeof console !== 'undefined' && console.warn(("[kdu-router] " + message));
17
+ }
18
+ }
19
+
20
+ function isError (err) {
21
+ return Object.prototype.toString.call(err).indexOf('Error') > -1
22
+ }
23
+
24
+ var View = {
25
+ name: 'router-view',
26
+ functional: true,
27
+ props: {
28
+ name: {
29
+ type: String,
30
+ default: 'default'
31
+ }
32
+ },
33
+ render: function render (_, ref) {
34
+ var props = ref.props;
35
+ var children = ref.children;
36
+ var parent = ref.parent;
37
+ var data = ref.data;
38
+
39
+ data.routerView = true;
40
+
41
+ // directly use parent context's createElement() function
42
+ // so that components rendered by router-view can resolve named slots
43
+ var h = parent.$createElement;
44
+ var name = props.name;
45
+ var route = parent.$route;
46
+ var cache = parent._routerViewCache || (parent._routerViewCache = {});
47
+
48
+ // determine current view depth, also check to see if the tree
49
+ // has been toggled inactive but kept-alive.
50
+ var depth = 0;
51
+ var inactive = false;
52
+ while (parent && parent._routerRoot !== parent) {
53
+ if (parent.$vnode && parent.$vnode.data.routerView) {
54
+ depth++;
55
+ }
56
+ if (parent._inactive) {
57
+ inactive = true;
58
+ }
59
+ parent = parent.$parent;
60
+ }
61
+ data.routerViewDepth = depth;
62
+
63
+ // render previous view if the tree is inactive and kept-alive
64
+ if (inactive) {
65
+ return h(cache[name], data, children)
66
+ }
67
+
68
+ var matched = route.matched[depth];
69
+ // render empty node if no matched route
70
+ if (!matched) {
71
+ cache[name] = null;
72
+ return h()
73
+ }
74
+
75
+ var component = cache[name] = matched.components[name];
76
+
77
+ // attach instance registration hook
78
+ // this will be called in the instance's injected lifecycle hooks
79
+ data.registerRouteInstance = function (vm, val) {
80
+ // val could be undefined for unregistration
81
+ var current = matched.instances[name];
82
+ if (
83
+ (val && current !== vm) ||
84
+ (!val && current === vm)
85
+ ) {
86
+ matched.instances[name] = val;
87
+ }
88
+ }
89
+
90
+ // also regiseter instance in prepatch hook
91
+ // in case the same component instance is reused across different routes
92
+ ;(data.hook || (data.hook = {})).prepatch = function (_, vnode) {
93
+ matched.instances[name] = vnode.componentInstance;
94
+ };
95
+
96
+ // resolve props
97
+ data.props = resolveProps(route, matched.props && matched.props[name]);
98
+
99
+ return h(component, data, children)
100
+ }
101
+ };
102
+
103
+ function resolveProps (route, config) {
104
+ switch (typeof config) {
105
+ case 'undefined':
106
+ return
107
+ case 'object':
108
+ return config
109
+ case 'function':
110
+ return config(route)
111
+ case 'boolean':
112
+ return config ? route.params : undefined
113
+ default:
114
+ if (process.env.NODE_ENV !== 'production') {
115
+ warn(
116
+ false,
117
+ "props in \"" + (route.path) + "\" is a " + (typeof config) + ", " +
118
+ "expecting an object, function or boolean."
119
+ );
120
+ }
121
+ }
122
+ }
123
+
124
+ /* */
125
+
126
+ var encodeReserveRE = /[!'()*]/g;
127
+ var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); };
128
+ var commaRE = /%2C/g;
129
+
130
+ // fixed encodeURIComponent which is more conformant to RFC3986:
131
+ // - escapes [!'()*]
132
+ // - preserve commas
133
+ var encode = function (str) { return encodeURIComponent(str)
134
+ .replace(encodeReserveRE, encodeReserveReplacer)
135
+ .replace(commaRE, ','); };
136
+
137
+ var decode = decodeURIComponent;
138
+
139
+ function resolveQuery (
140
+ query,
141
+ extraQuery,
142
+ _parseQuery
143
+ ) {
144
+ if ( extraQuery === void 0 ) extraQuery = {};
145
+
146
+ var parse = _parseQuery || parseQuery;
147
+ var parsedQuery;
148
+ try {
149
+ parsedQuery = parse(query || '');
150
+ } catch (e) {
151
+ process.env.NODE_ENV !== 'production' && warn(false, e.message);
152
+ parsedQuery = {};
153
+ }
154
+ for (var key in extraQuery) {
155
+ var val = extraQuery[key];
156
+ parsedQuery[key] = Array.isArray(val) ? val.slice() : val;
157
+ }
158
+ return parsedQuery
159
+ }
160
+
161
+ function parseQuery (query) {
162
+ var res = {};
163
+
164
+ query = query.trim().replace(/^(\?|#|&)/, '');
165
+
166
+ if (!query) {
167
+ return res
168
+ }
169
+
170
+ query.split('&').forEach(function (param) {
171
+ var parts = param.replace(/\+/g, ' ').split('=');
172
+ var key = decode(parts.shift());
173
+ var val = parts.length > 0
174
+ ? decode(parts.join('='))
175
+ : null;
176
+
177
+ if (res[key] === undefined) {
178
+ res[key] = val;
179
+ } else if (Array.isArray(res[key])) {
180
+ res[key].push(val);
181
+ } else {
182
+ res[key] = [res[key], val];
183
+ }
184
+ });
185
+
186
+ return res
187
+ }
188
+
189
+ function stringifyQuery (obj) {
190
+ var res = obj ? Object.keys(obj).map(function (key) {
191
+ var val = obj[key];
192
+
193
+ if (val === undefined) {
194
+ return ''
195
+ }
196
+
197
+ if (val === null) {
198
+ return encode(key)
199
+ }
200
+
201
+ if (Array.isArray(val)) {
202
+ var result = [];
203
+ val.forEach(function (val2) {
204
+ if (val2 === undefined) {
205
+ return
206
+ }
207
+ if (val2 === null) {
208
+ result.push(encode(key));
209
+ } else {
210
+ result.push(encode(key) + '=' + encode(val2));
211
+ }
212
+ });
213
+ return result.join('&')
214
+ }
215
+
216
+ return encode(key) + '=' + encode(val)
217
+ }).filter(function (x) { return x.length > 0; }).join('&') : null;
218
+ return res ? ("?" + res) : ''
219
+ }
220
+
221
+ /* */
222
+
223
+
224
+ var trailingSlashRE = /\/?$/;
225
+
226
+ function createRoute (
227
+ record,
228
+ location,
229
+ redirectedFrom,
230
+ router
231
+ ) {
232
+ var stringifyQuery$$1 = router && router.options.stringifyQuery;
233
+ var route = {
234
+ name: location.name || (record && record.name),
235
+ meta: (record && record.meta) || {},
236
+ path: location.path || '/',
237
+ hash: location.hash || '',
238
+ query: location.query || {},
239
+ params: location.params || {},
240
+ fullPath: getFullPath(location, stringifyQuery$$1),
241
+ matched: record ? formatMatch(record) : []
242
+ };
243
+ if (redirectedFrom) {
244
+ route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery$$1);
245
+ }
246
+ return Object.freeze(route)
247
+ }
248
+
249
+ // the starting route that represents the initial state
250
+ var START = createRoute(null, {
251
+ path: '/'
252
+ });
253
+
254
+ function formatMatch (record) {
255
+ var res = [];
256
+ while (record) {
257
+ res.unshift(record);
258
+ record = record.parent;
259
+ }
260
+ return res
261
+ }
262
+
263
+ function getFullPath (
264
+ ref,
265
+ _stringifyQuery
266
+ ) {
267
+ var path = ref.path;
268
+ var query = ref.query; if ( query === void 0 ) query = {};
269
+ var hash = ref.hash; if ( hash === void 0 ) hash = '';
270
+
271
+ var stringify = _stringifyQuery || stringifyQuery;
272
+ return (path || '/') + stringify(query) + hash
273
+ }
274
+
275
+ function isSameRoute (a, b) {
276
+ if (b === START) {
277
+ return a === b
278
+ } else if (!b) {
279
+ return false
280
+ } else if (a.path && b.path) {
281
+ return (
282
+ a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') &&
283
+ a.hash === b.hash &&
284
+ isObjectEqual(a.query, b.query)
285
+ )
286
+ } else if (a.name && b.name) {
287
+ return (
288
+ a.name === b.name &&
289
+ a.hash === b.hash &&
290
+ isObjectEqual(a.query, b.query) &&
291
+ isObjectEqual(a.params, b.params)
292
+ )
293
+ } else {
294
+ return false
295
+ }
296
+ }
297
+
298
+ function isObjectEqual (a, b) {
299
+ if ( a === void 0 ) a = {};
300
+ if ( b === void 0 ) b = {};
301
+
302
+ var aKeys = Object.keys(a);
303
+ var bKeys = Object.keys(b);
304
+ if (aKeys.length !== bKeys.length) {
305
+ return false
306
+ }
307
+ return aKeys.every(function (key) {
308
+ var aVal = a[key];
309
+ var bVal = b[key];
310
+ // check nested equality
311
+ if (typeof aVal === 'object' && typeof bVal === 'object') {
312
+ return isObjectEqual(aVal, bVal)
313
+ }
314
+ return String(aVal) === String(bVal)
315
+ })
316
+ }
317
+
318
+ function isIncludedRoute (current, target) {
319
+ return (
320
+ current.path.replace(trailingSlashRE, '/').indexOf(
321
+ target.path.replace(trailingSlashRE, '/')
322
+ ) === 0 &&
323
+ (!target.hash || current.hash === target.hash) &&
324
+ queryIncludes(current.query, target.query)
325
+ )
326
+ }
327
+
328
+ function queryIncludes (current, target) {
329
+ for (var key in target) {
330
+ if (!(key in current)) {
331
+ return false
332
+ }
333
+ }
334
+ return true
335
+ }
336
+
337
+ /* */
338
+
339
+ // work around weird flow bug
340
+ var toTypes = [String, Object];
341
+ var eventTypes = [String, Array];
342
+
343
+ var Link = {
344
+ name: 'router-link',
345
+ props: {
346
+ to: {
347
+ type: toTypes,
348
+ required: true
349
+ },
350
+ tag: {
351
+ type: String,
352
+ default: 'a'
353
+ },
354
+ exact: Boolean,
355
+ append: Boolean,
356
+ replace: Boolean,
357
+ activeClass: String,
358
+ exactActiveClass: String,
359
+ event: {
360
+ type: eventTypes,
361
+ default: 'click'
362
+ }
363
+ },
364
+ render: function render (h) {
365
+ var this$1 = this;
366
+
367
+ var router = this.$router;
368
+ var current = this.$route;
369
+ var ref = router.resolve(this.to, current, this.append);
370
+ var location = ref.location;
371
+ var route = ref.route;
372
+ var href = ref.href;
373
+
374
+ var classes = {};
375
+ var globalActiveClass = router.options.linkActiveClass;
376
+ var globalExactActiveClass = router.options.linkExactActiveClass;
377
+ // Support global empty active class
378
+ var activeClassFallback = globalActiveClass == null
379
+ ? 'router-link-active'
380
+ : globalActiveClass;
381
+ var exactActiveClassFallback = globalExactActiveClass == null
382
+ ? 'router-link-exact-active'
383
+ : globalExactActiveClass;
384
+ var activeClass = this.activeClass == null
385
+ ? activeClassFallback
386
+ : this.activeClass;
387
+ var exactActiveClass = this.exactActiveClass == null
388
+ ? exactActiveClassFallback
389
+ : this.exactActiveClass;
390
+ var compareTarget = location.path
391
+ ? createRoute(null, location, null, router)
392
+ : route;
393
+
394
+ classes[exactActiveClass] = isSameRoute(current, compareTarget);
395
+ classes[activeClass] = this.exact
396
+ ? classes[exactActiveClass]
397
+ : isIncludedRoute(current, compareTarget);
398
+
399
+ var handler = function (e) {
400
+ if (guardEvent(e)) {
401
+ if (this$1.replace) {
402
+ router.replace(location);
403
+ } else {
404
+ router.push(location);
405
+ }
406
+ }
407
+ };
408
+
409
+ var on = { click: guardEvent };
410
+ if (Array.isArray(this.event)) {
411
+ this.event.forEach(function (e) { on[e] = handler; });
412
+ } else {
413
+ on[this.event] = handler;
414
+ }
415
+
416
+ var data = {
417
+ class: classes
418
+ };
419
+
420
+ if (this.tag === 'a') {
421
+ data.on = on;
422
+ data.attrs = { href: href };
423
+ } else {
424
+ // find the first <a> child and apply listener and href
425
+ var a = findAnchor(this.$slots.default);
426
+ if (a) {
427
+ // in case the <a> is a static node
428
+ a.isStatic = false;
429
+ var extend = _Kdu.util.extend;
430
+ var aData = a.data = extend({}, a.data);
431
+ aData.on = on;
432
+ var aAttrs = a.data.attrs = extend({}, a.data.attrs);
433
+ aAttrs.href = href;
434
+ } else {
435
+ // doesn't have <a> child, apply listener to self
436
+ data.on = on;
437
+ }
438
+ }
439
+
440
+ return h(this.tag, data, this.$slots.default)
441
+ }
442
+ };
443
+
444
+ function guardEvent (e) {
445
+ // don't redirect with control keys
446
+ if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return }
447
+ // don't redirect when preventDefault called
448
+ if (e.defaultPrevented) { return }
449
+ // don't redirect on right click
450
+ if (e.button !== undefined && e.button !== 0) { return }
451
+ // don't redirect if `target="_blank"`
452
+ if (e.currentTarget && e.currentTarget.getAttribute) {
453
+ var target = e.currentTarget.getAttribute('target');
454
+ if (/\b_blank\b/i.test(target)) { return }
455
+ }
456
+ // this may be a Weex event which doesn't have this method
457
+ if (e.preventDefault) {
458
+ e.preventDefault();
459
+ }
460
+ return true
461
+ }
462
+
463
+ function findAnchor (children) {
464
+ if (children) {
465
+ var child;
466
+ for (var i = 0; i < children.length; i++) {
467
+ child = children[i];
468
+ if (child.tag === 'a') {
469
+ return child
470
+ }
471
+ if (child.children && (child = findAnchor(child.children))) {
472
+ return child
473
+ }
474
+ }
475
+ }
476
+ }
477
+
478
+ var _Kdu;
479
+
480
+ function install (Kdu) {
481
+ if (install.installed) { return }
482
+ install.installed = true;
483
+
484
+ _Kdu = Kdu;
485
+
486
+ var isDef = function (v) { return v !== undefined; };
487
+
488
+ var registerInstance = function (vm, callVal) {
489
+ var i = vm.$options._parentVnode;
490
+ if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
491
+ i(vm, callVal);
492
+ }
493
+ };
494
+
495
+ Kdu.mixin({
496
+ beforeCreate: function beforeCreate () {
497
+ if (isDef(this.$options.router)) {
498
+ this._routerRoot = this;
499
+ this._router = this.$options.router;
500
+ this._router.init(this);
501
+ Kdu.util.defineReactive(this, '_route', this._router.history.current);
502
+ } else {
503
+ this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
504
+ }
505
+ registerInstance(this, this);
506
+ },
507
+ destroyed: function destroyed () {
508
+ registerInstance(this);
509
+ }
510
+ });
511
+
512
+ Object.defineProperty(Kdu.prototype, '$router', {
513
+ get: function get () { return this._routerRoot._router }
514
+ });
515
+
516
+ Object.defineProperty(Kdu.prototype, '$route', {
517
+ get: function get () { return this._routerRoot._route }
518
+ });
519
+
520
+ Kdu.component('router-view', View);
521
+ Kdu.component('router-link', Link);
522
+
523
+ var strats = Kdu.config.optionMergeStrategies;
524
+ // use the same hook merging strategy for route hooks
525
+ strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
526
+ }
527
+
528
+ /* */
529
+
530
+ var inBrowser = typeof window !== 'undefined';
531
+
532
+ /* */
533
+
534
+ function resolvePath (
535
+ relative,
536
+ base,
537
+ append
538
+ ) {
539
+ var firstChar = relative.charAt(0);
540
+ if (firstChar === '/') {
541
+ return relative
542
+ }
543
+
544
+ if (firstChar === '?' || firstChar === '#') {
545
+ return base + relative
546
+ }
547
+
548
+ var stack = base.split('/');
549
+
550
+ // remove trailing segment if:
551
+ // - not appending
552
+ // - appending to trailing slash (last segment is empty)
553
+ if (!append || !stack[stack.length - 1]) {
554
+ stack.pop();
555
+ }
556
+
557
+ // resolve relative path
558
+ var segments = relative.replace(/^\//, '').split('/');
559
+ for (var i = 0; i < segments.length; i++) {
560
+ var segment = segments[i];
561
+ if (segment === '..') {
562
+ stack.pop();
563
+ } else if (segment !== '.') {
564
+ stack.push(segment);
565
+ }
566
+ }
567
+
568
+ // ensure leading slash
569
+ if (stack[0] !== '') {
570
+ stack.unshift('');
571
+ }
572
+
573
+ return stack.join('/')
574
+ }
575
+
576
+ function parsePath (path) {
577
+ var hash = '';
578
+ var query = '';
579
+
580
+ var hashIndex = path.indexOf('#');
581
+ if (hashIndex >= 0) {
582
+ hash = path.slice(hashIndex);
583
+ path = path.slice(0, hashIndex);
584
+ }
585
+
586
+ var queryIndex = path.indexOf('?');
587
+ if (queryIndex >= 0) {
588
+ query = path.slice(queryIndex + 1);
589
+ path = path.slice(0, queryIndex);
590
+ }
591
+
592
+ return {
593
+ path: path,
594
+ query: query,
595
+ hash: hash
596
+ }
597
+ }
598
+
599
+ function cleanPath (path) {
600
+ return path.replace(/\/\//g, '/')
601
+ }
602
+
603
+ var index$1 = Array.isArray || function (arr) {
604
+ return Object.prototype.toString.call(arr) == '[object Array]';
605
+ };
606
+
607
+ /**
608
+ * Expose `pathToRegexp`.
609
+ */
610
+ var index = pathToRegexp;
611
+ var parse_1 = parse;
612
+ var compile_1 = compile;
613
+ var tokensToFunction_1 = tokensToFunction;
614
+ var tokensToRegExp_1 = tokensToRegExp;
615
+
616
+ /**
617
+ * The main path matching regexp utility.
618
+ *
619
+ * @type {RegExp}
620
+ */
621
+ var PATH_REGEXP = new RegExp([
622
+ // Match escaped characters that would otherwise appear in future matches.
623
+ // This allows the user to escape special characters that won't transform.
624
+ '(\\\\.)',
625
+ // Match Express-style parameters and un-named parameters with a prefix
626
+ // and optional suffixes. Matches appear as:
627
+ //
628
+ // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
629
+ // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
630
+ // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
631
+ '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
632
+ ].join('|'), 'g');
633
+
634
+ /**
635
+ * Parse a string for the raw tokens.
636
+ *
637
+ * @param {string} str
638
+ * @param {Object=} options
639
+ * @return {!Array}
640
+ */
641
+ function parse (str, options) {
642
+ var tokens = [];
643
+ var key = 0;
644
+ var index = 0;
645
+ var path = '';
646
+ var defaultDelimiter = options && options.delimiter || '/';
647
+ var res;
648
+
649
+ while ((res = PATH_REGEXP.exec(str)) != null) {
650
+ var m = res[0];
651
+ var escaped = res[1];
652
+ var offset = res.index;
653
+ path += str.slice(index, offset);
654
+ index = offset + m.length;
655
+
656
+ // Ignore already escaped sequences.
657
+ if (escaped) {
658
+ path += escaped[1];
659
+ continue
660
+ }
661
+
662
+ var next = str[index];
663
+ var prefix = res[2];
664
+ var name = res[3];
665
+ var capture = res[4];
666
+ var group = res[5];
667
+ var modifier = res[6];
668
+ var asterisk = res[7];
669
+
670
+ // Push the current path onto the tokens.
671
+ if (path) {
672
+ tokens.push(path);
673
+ path = '';
674
+ }
675
+
676
+ var partial = prefix != null && next != null && next !== prefix;
677
+ var repeat = modifier === '+' || modifier === '*';
678
+ var optional = modifier === '?' || modifier === '*';
679
+ var delimiter = res[2] || defaultDelimiter;
680
+ var pattern = capture || group;
681
+
682
+ tokens.push({
683
+ name: name || key++,
684
+ prefix: prefix || '',
685
+ delimiter: delimiter,
686
+ optional: optional,
687
+ repeat: repeat,
688
+ partial: partial,
689
+ asterisk: !!asterisk,
690
+ pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
691
+ });
692
+ }
693
+
694
+ // Match any characters still remaining.
695
+ if (index < str.length) {
696
+ path += str.substr(index);
697
+ }
698
+
699
+ // If the path exists, push it onto the end.
700
+ if (path) {
701
+ tokens.push(path);
702
+ }
703
+
704
+ return tokens
705
+ }
706
+
707
+ /**
708
+ * Compile a string to a template function for the path.
709
+ *
710
+ * @param {string} str
711
+ * @param {Object=} options
712
+ * @return {!function(Object=, Object=)}
713
+ */
714
+ function compile (str, options) {
715
+ return tokensToFunction(parse(str, options))
716
+ }
717
+
718
+ /**
719
+ * Prettier encoding of URI path segments.
720
+ *
721
+ * @param {string}
722
+ * @return {string}
723
+ */
724
+ function encodeURIComponentPretty (str) {
725
+ return encodeURI(str).replace(/[\/?#]/g, function (c) {
726
+ return '%' + c.charCodeAt(0).toString(16).toUpperCase()
727
+ })
728
+ }
729
+
730
+ /**
731
+ * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
732
+ *
733
+ * @param {string}
734
+ * @return {string}
735
+ */
736
+ function encodeAsterisk (str) {
737
+ return encodeURI(str).replace(/[?#]/g, function (c) {
738
+ return '%' + c.charCodeAt(0).toString(16).toUpperCase()
739
+ })
740
+ }
741
+
742
+ /**
743
+ * Expose a method for transforming tokens into the path function.
744
+ */
745
+ function tokensToFunction (tokens) {
746
+ // Compile all the tokens into regexps.
747
+ var matches = new Array(tokens.length);
748
+
749
+ // Compile all the patterns before compilation.
750
+ for (var i = 0; i < tokens.length; i++) {
751
+ if (typeof tokens[i] === 'object') {
752
+ matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
753
+ }
754
+ }
755
+
756
+ return function (obj, opts) {
757
+ var path = '';
758
+ var data = obj || {};
759
+ var options = opts || {};
760
+ var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
761
+
762
+ for (var i = 0; i < tokens.length; i++) {
763
+ var token = tokens[i];
764
+
765
+ if (typeof token === 'string') {
766
+ path += token;
767
+
768
+ continue
769
+ }
770
+
771
+ var value = data[token.name];
772
+ var segment;
773
+
774
+ if (value == null) {
775
+ if (token.optional) {
776
+ // Prepend partial segment prefixes.
777
+ if (token.partial) {
778
+ path += token.prefix;
779
+ }
780
+
781
+ continue
782
+ } else {
783
+ throw new TypeError('Expected "' + token.name + '" to be defined')
784
+ }
785
+ }
786
+
787
+ if (index$1(value)) {
788
+ if (!token.repeat) {
789
+ throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
790
+ }
791
+
792
+ if (value.length === 0) {
793
+ if (token.optional) {
794
+ continue
795
+ } else {
796
+ throw new TypeError('Expected "' + token.name + '" to not be empty')
797
+ }
798
+ }
799
+
800
+ for (var j = 0; j < value.length; j++) {
801
+ segment = encode(value[j]);
802
+
803
+ if (!matches[i].test(segment)) {
804
+ throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
805
+ }
806
+
807
+ path += (j === 0 ? token.prefix : token.delimiter) + segment;
808
+ }
809
+
810
+ continue
811
+ }
812
+
813
+ segment = token.asterisk ? encodeAsterisk(value) : encode(value);
814
+
815
+ if (!matches[i].test(segment)) {
816
+ throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
817
+ }
818
+
819
+ path += token.prefix + segment;
820
+ }
821
+
822
+ return path
823
+ }
824
+ }
825
+
826
+ /**
827
+ * Escape a regular expression string.
828
+ *
829
+ * @param {string} str
830
+ * @return {string}
831
+ */
832
+ function escapeString (str) {
833
+ return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
834
+ }
835
+
836
+ /**
837
+ * Escape the capturing group by escaping special characters and meaning.
838
+ *
839
+ * @param {string} group
840
+ * @return {string}
841
+ */
842
+ function escapeGroup (group) {
843
+ return group.replace(/([=!:$\/()])/g, '\\$1')
844
+ }
845
+
846
+ /**
847
+ * Attach the keys as a property of the regexp.
848
+ *
849
+ * @param {!RegExp} re
850
+ * @param {Array} keys
851
+ * @return {!RegExp}
852
+ */
853
+ function attachKeys (re, keys) {
854
+ re.keys = keys;
855
+ return re
856
+ }
857
+
858
+ /**
859
+ * Get the flags for a regexp from the options.
860
+ *
861
+ * @param {Object} options
862
+ * @return {string}
863
+ */
864
+ function flags (options) {
865
+ return options.sensitive ? '' : 'i'
866
+ }
867
+
868
+ /**
869
+ * Pull out keys from a regexp.
870
+ *
871
+ * @param {!RegExp} path
872
+ * @param {!Array} keys
873
+ * @return {!RegExp}
874
+ */
875
+ function regexpToRegexp (path, keys) {
876
+ // Use a negative lookahead to match only capturing groups.
877
+ var groups = path.source.match(/\((?!\?)/g);
878
+
879
+ if (groups) {
880
+ for (var i = 0; i < groups.length; i++) {
881
+ keys.push({
882
+ name: i,
883
+ prefix: null,
884
+ delimiter: null,
885
+ optional: false,
886
+ repeat: false,
887
+ partial: false,
888
+ asterisk: false,
889
+ pattern: null
890
+ });
891
+ }
892
+ }
893
+
894
+ return attachKeys(path, keys)
895
+ }
896
+
897
+ /**
898
+ * Transform an array into a regexp.
899
+ *
900
+ * @param {!Array} path
901
+ * @param {Array} keys
902
+ * @param {!Object} options
903
+ * @return {!RegExp}
904
+ */
905
+ function arrayToRegexp (path, keys, options) {
906
+ var parts = [];
907
+
908
+ for (var i = 0; i < path.length; i++) {
909
+ parts.push(pathToRegexp(path[i], keys, options).source);
910
+ }
911
+
912
+ var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
913
+
914
+ return attachKeys(regexp, keys)
915
+ }
916
+
917
+ /**
918
+ * Create a path regexp from string input.
919
+ *
920
+ * @param {string} path
921
+ * @param {!Array} keys
922
+ * @param {!Object} options
923
+ * @return {!RegExp}
924
+ */
925
+ function stringToRegexp (path, keys, options) {
926
+ return tokensToRegExp(parse(path, options), keys, options)
927
+ }
928
+
929
+ /**
930
+ * Expose a function for taking tokens and returning a RegExp.
931
+ *
932
+ * @param {!Array} tokens
933
+ * @param {(Array|Object)=} keys
934
+ * @param {Object=} options
935
+ * @return {!RegExp}
936
+ */
937
+ function tokensToRegExp (tokens, keys, options) {
938
+ if (!index$1(keys)) {
939
+ options = /** @type {!Object} */ (keys || options);
940
+ keys = [];
941
+ }
942
+
943
+ options = options || {};
944
+
945
+ var strict = options.strict;
946
+ var end = options.end !== false;
947
+ var route = '';
948
+
949
+ // Iterate over the tokens and create our regexp string.
950
+ for (var i = 0; i < tokens.length; i++) {
951
+ var token = tokens[i];
952
+
953
+ if (typeof token === 'string') {
954
+ route += escapeString(token);
955
+ } else {
956
+ var prefix = escapeString(token.prefix);
957
+ var capture = '(?:' + token.pattern + ')';
958
+
959
+ keys.push(token);
960
+
961
+ if (token.repeat) {
962
+ capture += '(?:' + prefix + capture + ')*';
963
+ }
964
+
965
+ if (token.optional) {
966
+ if (!token.partial) {
967
+ capture = '(?:' + prefix + '(' + capture + '))?';
968
+ } else {
969
+ capture = prefix + '(' + capture + ')?';
970
+ }
971
+ } else {
972
+ capture = prefix + '(' + capture + ')';
973
+ }
974
+
975
+ route += capture;
976
+ }
977
+ }
978
+
979
+ var delimiter = escapeString(options.delimiter || '/');
980
+ var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
981
+
982
+ // In non-strict mode we allow a slash at the end of match. If the path to
983
+ // match already ends with a slash, we remove it for consistency. The slash
984
+ // is valid at the end of a path match, not in the middle. This is important
985
+ // in non-ending mode, where "/test/" shouldn't match "/test//route".
986
+ if (!strict) {
987
+ route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
988
+ }
989
+
990
+ if (end) {
991
+ route += '$';
992
+ } else {
993
+ // In non-ending mode, we need the capturing groups to match as much as
994
+ // possible by using a positive lookahead to the end or next path segment.
995
+ route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
996
+ }
997
+
998
+ return attachKeys(new RegExp('^' + route, flags(options)), keys)
999
+ }
1000
+
1001
+ /**
1002
+ * Normalize the given path string, returning a regular expression.
1003
+ *
1004
+ * An empty array can be passed in for the keys, which will hold the
1005
+ * placeholder key descriptions. For example, using `/user/:id`, `keys` will
1006
+ * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
1007
+ *
1008
+ * @param {(string|RegExp|Array)} path
1009
+ * @param {(Array|Object)=} keys
1010
+ * @param {Object=} options
1011
+ * @return {!RegExp}
1012
+ */
1013
+ function pathToRegexp (path, keys, options) {
1014
+ if (!index$1(keys)) {
1015
+ options = /** @type {!Object} */ (keys || options);
1016
+ keys = [];
1017
+ }
1018
+
1019
+ options = options || {};
1020
+
1021
+ if (path instanceof RegExp) {
1022
+ return regexpToRegexp(path, /** @type {!Array} */ (keys))
1023
+ }
1024
+
1025
+ if (index$1(path)) {
1026
+ return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
1027
+ }
1028
+
1029
+ return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
1030
+ }
1031
+
1032
+ index.parse = parse_1;
1033
+ index.compile = compile_1;
1034
+ index.tokensToFunction = tokensToFunction_1;
1035
+ index.tokensToRegExp = tokensToRegExp_1;
1036
+
1037
+ /* */
1038
+
1039
+ var regexpCompileCache = Object.create(null);
1040
+
1041
+ function fillParams (
1042
+ path,
1043
+ params,
1044
+ routeMsg
1045
+ ) {
1046
+ try {
1047
+ var filler =
1048
+ regexpCompileCache[path] ||
1049
+ (regexpCompileCache[path] = index.compile(path));
1050
+ return filler(params || {}, { pretty: true })
1051
+ } catch (e) {
1052
+ if (process.env.NODE_ENV !== 'production') {
1053
+ warn(false, ("missing param for " + routeMsg + ": " + (e.message)));
1054
+ }
1055
+ return ''
1056
+ }
1057
+ }
1058
+
1059
+ /* */
1060
+
1061
+ function createRouteMap (
1062
+ routes,
1063
+ oldPathList,
1064
+ oldPathMap,
1065
+ oldNameMap
1066
+ ) {
1067
+ // the path list is used to control path matching priority
1068
+ var pathList = oldPathList || [];
1069
+ var pathMap = oldPathMap || Object.create(null);
1070
+ var nameMap = oldNameMap || Object.create(null);
1071
+
1072
+ routes.forEach(function (route) {
1073
+ addRouteRecord(pathList, pathMap, nameMap, route);
1074
+ });
1075
+
1076
+ // ensure wildcard routes are always at the end
1077
+ for (var i = 0, l = pathList.length; i < l; i++) {
1078
+ if (pathList[i] === '*') {
1079
+ pathList.push(pathList.splice(i, 1)[0]);
1080
+ l--;
1081
+ i--;
1082
+ }
1083
+ }
1084
+
1085
+ return {
1086
+ pathList: pathList,
1087
+ pathMap: pathMap,
1088
+ nameMap: nameMap
1089
+ }
1090
+ }
1091
+
1092
+ function addRouteRecord (
1093
+ pathList,
1094
+ pathMap,
1095
+ nameMap,
1096
+ route,
1097
+ parent,
1098
+ matchAs
1099
+ ) {
1100
+ var path = route.path;
1101
+ var name = route.name;
1102
+ if (process.env.NODE_ENV !== 'production') {
1103
+ assert(path != null, "\"path\" is required in a route configuration.");
1104
+ assert(
1105
+ typeof route.component !== 'string',
1106
+ "route config \"component\" for path: " + (String(path || name)) + " cannot be a " +
1107
+ "string id. Use an actual component instead."
1108
+ );
1109
+ }
1110
+
1111
+ var normalizedPath = normalizePath(path, parent);
1112
+ var pathToRegexpOptions = route.pathToRegexpOptions || {};
1113
+
1114
+ if (typeof route.caseSensitive === 'boolean') {
1115
+ pathToRegexpOptions.sensitive = route.caseSensitive;
1116
+ }
1117
+
1118
+ var record = {
1119
+ path: normalizedPath,
1120
+ regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
1121
+ components: route.components || { default: route.component },
1122
+ instances: {},
1123
+ name: name,
1124
+ parent: parent,
1125
+ matchAs: matchAs,
1126
+ redirect: route.redirect,
1127
+ beforeEnter: route.beforeEnter,
1128
+ meta: route.meta || {},
1129
+ props: route.props == null
1130
+ ? {}
1131
+ : route.components
1132
+ ? route.props
1133
+ : { default: route.props }
1134
+ };
1135
+
1136
+ if (route.children) {
1137
+ // Warn if route is named, does not redirect and has a default child route.
1138
+ // If users navigate to this route by name, the default child will
1139
+ // not be rendered (GH Issue #629)
1140
+ if (process.env.NODE_ENV !== 'production') {
1141
+ if (route.name && !route.redirect && route.children.some(function (child) { return /^\/?$/.test(child.path); })) {
1142
+ warn(
1143
+ false,
1144
+ "Named Route '" + (route.name) + "' has a default child route. " +
1145
+ "When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " +
1146
+ "the default child route will not be rendered. Remove the name from " +
1147
+ "this route and use the name of the default child route for named " +
1148
+ "links instead."
1149
+ );
1150
+ }
1151
+ }
1152
+ route.children.forEach(function (child) {
1153
+ var childMatchAs = matchAs
1154
+ ? cleanPath((matchAs + "/" + (child.path)))
1155
+ : undefined;
1156
+ addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
1157
+ });
1158
+ }
1159
+
1160
+ if (route.alias !== undefined) {
1161
+ var aliases = Array.isArray(route.alias)
1162
+ ? route.alias
1163
+ : [route.alias];
1164
+
1165
+ aliases.forEach(function (alias) {
1166
+ var aliasRoute = {
1167
+ path: alias,
1168
+ children: route.children
1169
+ };
1170
+ addRouteRecord(
1171
+ pathList,
1172
+ pathMap,
1173
+ nameMap,
1174
+ aliasRoute,
1175
+ parent,
1176
+ record.path || '/' // matchAs
1177
+ );
1178
+ });
1179
+ }
1180
+
1181
+ if (!pathMap[record.path]) {
1182
+ pathList.push(record.path);
1183
+ pathMap[record.path] = record;
1184
+ }
1185
+
1186
+ if (name) {
1187
+ if (!nameMap[name]) {
1188
+ nameMap[name] = record;
1189
+ } else if (process.env.NODE_ENV !== 'production' && !matchAs) {
1190
+ warn(
1191
+ false,
1192
+ "Duplicate named routes definition: " +
1193
+ "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
1194
+ );
1195
+ }
1196
+ }
1197
+ }
1198
+
1199
+ function compileRouteRegex (path, pathToRegexpOptions) {
1200
+ var regex = index(path, [], pathToRegexpOptions);
1201
+ if (process.env.NODE_ENV !== 'production') {
1202
+ var keys = {};
1203
+ regex.keys.forEach(function (key) {
1204
+ warn(!keys[key.name], ("Duplicate param keys in route with path: \"" + path + "\""));
1205
+ keys[key.name] = true;
1206
+ });
1207
+ }
1208
+ return regex
1209
+ }
1210
+
1211
+ function normalizePath (path, parent) {
1212
+ path = path.replace(/\/$/, '');
1213
+ if (path[0] === '/') { return path }
1214
+ if (parent == null) { return path }
1215
+ return cleanPath(((parent.path) + "/" + path))
1216
+ }
1217
+
1218
+ /* */
1219
+
1220
+
1221
+ function normalizeLocation (
1222
+ raw,
1223
+ current,
1224
+ append,
1225
+ router
1226
+ ) {
1227
+ var next = typeof raw === 'string' ? { path: raw } : raw;
1228
+ // named target
1229
+ if (next.name || next._normalized) {
1230
+ return next
1231
+ }
1232
+
1233
+ // relative params
1234
+ if (!next.path && next.params && current) {
1235
+ next = assign({}, next);
1236
+ next._normalized = true;
1237
+ var params = assign(assign({}, current.params), next.params);
1238
+ if (current.name) {
1239
+ next.name = current.name;
1240
+ next.params = params;
1241
+ } else if (current.matched.length) {
1242
+ var rawPath = current.matched[current.matched.length - 1].path;
1243
+ next.path = fillParams(rawPath, params, ("path " + (current.path)));
1244
+ } else if (process.env.NODE_ENV !== 'production') {
1245
+ warn(false, "relative params navigation requires a current route.");
1246
+ }
1247
+ return next
1248
+ }
1249
+
1250
+ var parsedPath = parsePath(next.path || '');
1251
+ var basePath = (current && current.path) || '/';
1252
+ var path = parsedPath.path
1253
+ ? resolvePath(parsedPath.path, basePath, append || next.append)
1254
+ : basePath;
1255
+
1256
+ var query = resolveQuery(
1257
+ parsedPath.query,
1258
+ next.query,
1259
+ router && router.options.parseQuery
1260
+ );
1261
+
1262
+ var hash = next.hash || parsedPath.hash;
1263
+ if (hash && hash.charAt(0) !== '#') {
1264
+ hash = "#" + hash;
1265
+ }
1266
+
1267
+ return {
1268
+ _normalized: true,
1269
+ path: path,
1270
+ query: query,
1271
+ hash: hash
1272
+ }
1273
+ }
1274
+
1275
+ function assign (a, b) {
1276
+ for (var key in b) {
1277
+ a[key] = b[key];
1278
+ }
1279
+ return a
1280
+ }
1281
+
1282
+ /* */
1283
+
1284
+
1285
+ function createMatcher (
1286
+ routes,
1287
+ router
1288
+ ) {
1289
+ var ref = createRouteMap(routes);
1290
+ var pathList = ref.pathList;
1291
+ var pathMap = ref.pathMap;
1292
+ var nameMap = ref.nameMap;
1293
+
1294
+ function addRoutes (routes) {
1295
+ createRouteMap(routes, pathList, pathMap, nameMap);
1296
+ }
1297
+
1298
+ function match (
1299
+ raw,
1300
+ currentRoute,
1301
+ redirectedFrom
1302
+ ) {
1303
+ var location = normalizeLocation(raw, currentRoute, false, router);
1304
+ var name = location.name;
1305
+
1306
+ if (name) {
1307
+ var record = nameMap[name];
1308
+ if (process.env.NODE_ENV !== 'production') {
1309
+ warn(record, ("Route with name '" + name + "' does not exist"));
1310
+ }
1311
+ if (!record) { return _createRoute(null, location) }
1312
+ var paramNames = record.regex.keys
1313
+ .filter(function (key) { return !key.optional; })
1314
+ .map(function (key) { return key.name; });
1315
+
1316
+ if (typeof location.params !== 'object') {
1317
+ location.params = {};
1318
+ }
1319
+
1320
+ if (currentRoute && typeof currentRoute.params === 'object') {
1321
+ for (var key in currentRoute.params) {
1322
+ if (!(key in location.params) && paramNames.indexOf(key) > -1) {
1323
+ location.params[key] = currentRoute.params[key];
1324
+ }
1325
+ }
1326
+ }
1327
+
1328
+ if (record) {
1329
+ location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
1330
+ return _createRoute(record, location, redirectedFrom)
1331
+ }
1332
+ } else if (location.path) {
1333
+ location.params = {};
1334
+ for (var i = 0; i < pathList.length; i++) {
1335
+ var path = pathList[i];
1336
+ var record$1 = pathMap[path];
1337
+ if (matchRoute(record$1.regex, location.path, location.params)) {
1338
+ return _createRoute(record$1, location, redirectedFrom)
1339
+ }
1340
+ }
1341
+ }
1342
+ // no match
1343
+ return _createRoute(null, location)
1344
+ }
1345
+
1346
+ function redirect (
1347
+ record,
1348
+ location
1349
+ ) {
1350
+ var originalRedirect = record.redirect;
1351
+ var redirect = typeof originalRedirect === 'function'
1352
+ ? originalRedirect(createRoute(record, location, null, router))
1353
+ : originalRedirect;
1354
+
1355
+ if (typeof redirect === 'string') {
1356
+ redirect = { path: redirect };
1357
+ }
1358
+
1359
+ if (!redirect || typeof redirect !== 'object') {
1360
+ if (process.env.NODE_ENV !== 'production') {
1361
+ warn(
1362
+ false, ("invalid redirect option: " + (JSON.stringify(redirect)))
1363
+ );
1364
+ }
1365
+ return _createRoute(null, location)
1366
+ }
1367
+
1368
+ var re = redirect;
1369
+ var name = re.name;
1370
+ var path = re.path;
1371
+ var query = location.query;
1372
+ var hash = location.hash;
1373
+ var params = location.params;
1374
+ query = re.hasOwnProperty('query') ? re.query : query;
1375
+ hash = re.hasOwnProperty('hash') ? re.hash : hash;
1376
+ params = re.hasOwnProperty('params') ? re.params : params;
1377
+
1378
+ if (name) {
1379
+ // resolved named direct
1380
+ var targetRecord = nameMap[name];
1381
+ if (process.env.NODE_ENV !== 'production') {
1382
+ assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
1383
+ }
1384
+ return match({
1385
+ _normalized: true,
1386
+ name: name,
1387
+ query: query,
1388
+ hash: hash,
1389
+ params: params
1390
+ }, undefined, location)
1391
+ } else if (path) {
1392
+ // 1. resolve relative redirect
1393
+ var rawPath = resolveRecordPath(path, record);
1394
+ // 2. resolve params
1395
+ var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\""));
1396
+ // 3. rematch with existing query and hash
1397
+ return match({
1398
+ _normalized: true,
1399
+ path: resolvedPath,
1400
+ query: query,
1401
+ hash: hash
1402
+ }, undefined, location)
1403
+ } else {
1404
+ if (process.env.NODE_ENV !== 'production') {
1405
+ warn(false, ("invalid redirect option: " + (JSON.stringify(redirect))));
1406
+ }
1407
+ return _createRoute(null, location)
1408
+ }
1409
+ }
1410
+
1411
+ function alias (
1412
+ record,
1413
+ location,
1414
+ matchAs
1415
+ ) {
1416
+ var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
1417
+ var aliasedMatch = match({
1418
+ _normalized: true,
1419
+ path: aliasedPath
1420
+ });
1421
+ if (aliasedMatch) {
1422
+ var matched = aliasedMatch.matched;
1423
+ var aliasedRecord = matched[matched.length - 1];
1424
+ location.params = aliasedMatch.params;
1425
+ return _createRoute(aliasedRecord, location)
1426
+ }
1427
+ return _createRoute(null, location)
1428
+ }
1429
+
1430
+ function _createRoute (
1431
+ record,
1432
+ location,
1433
+ redirectedFrom
1434
+ ) {
1435
+ if (record && record.redirect) {
1436
+ return redirect(record, redirectedFrom || location)
1437
+ }
1438
+ if (record && record.matchAs) {
1439
+ return alias(record, location, record.matchAs)
1440
+ }
1441
+ return createRoute(record, location, redirectedFrom, router)
1442
+ }
1443
+
1444
+ return {
1445
+ match: match,
1446
+ addRoutes: addRoutes
1447
+ }
1448
+ }
1449
+
1450
+ function matchRoute (
1451
+ regex,
1452
+ path,
1453
+ params
1454
+ ) {
1455
+ var m = path.match(regex);
1456
+
1457
+ if (!m) {
1458
+ return false
1459
+ } else if (!params) {
1460
+ return true
1461
+ }
1462
+
1463
+ for (var i = 1, len = m.length; i < len; ++i) {
1464
+ var key = regex.keys[i - 1];
1465
+ var val = typeof m[i] === 'string' ? decodeURIComponent(m[i]) : m[i];
1466
+ if (key) {
1467
+ params[key.name] = val;
1468
+ }
1469
+ }
1470
+
1471
+ return true
1472
+ }
1473
+
1474
+ function resolveRecordPath (path, record) {
1475
+ return resolvePath(path, record.parent ? record.parent.path : '/', true)
1476
+ }
1477
+
1478
+ /* */
1479
+
1480
+
1481
+ var positionStore = Object.create(null);
1482
+
1483
+ function setupScroll () {
1484
+ window.addEventListener('popstate', function (e) {
1485
+ saveScrollPosition();
1486
+ if (e.state && e.state.key) {
1487
+ setStateKey(e.state.key);
1488
+ }
1489
+ });
1490
+ }
1491
+
1492
+ function handleScroll (
1493
+ router,
1494
+ to,
1495
+ from,
1496
+ isPop
1497
+ ) {
1498
+ if (!router.app) {
1499
+ return
1500
+ }
1501
+
1502
+ var behavior = router.options.scrollBehavior;
1503
+ if (!behavior) {
1504
+ return
1505
+ }
1506
+
1507
+ if (process.env.NODE_ENV !== 'production') {
1508
+ assert(typeof behavior === 'function', "scrollBehavior must be a function");
1509
+ }
1510
+
1511
+ // wait until re-render finishes before scrolling
1512
+ router.app.$nextTick(function () {
1513
+ var position = getScrollPosition();
1514
+ var shouldScroll = behavior(to, from, isPop ? position : null);
1515
+ if (!shouldScroll) {
1516
+ return
1517
+ }
1518
+ var isObject = typeof shouldScroll === 'object';
1519
+ if (isObject && typeof shouldScroll.selector === 'string') {
1520
+ var el = document.querySelector(shouldScroll.selector);
1521
+ if (el) {
1522
+ var offset = shouldScroll.offset && typeof shouldScroll.offset === 'object' ? shouldScroll.offset : {};
1523
+ offset = normalizeOffset(offset);
1524
+ position = getElementPosition(el, offset);
1525
+ } else if (isValidPosition(shouldScroll)) {
1526
+ position = normalizePosition(shouldScroll);
1527
+ }
1528
+ } else if (isObject && isValidPosition(shouldScroll)) {
1529
+ position = normalizePosition(shouldScroll);
1530
+ }
1531
+
1532
+ if (position) {
1533
+ window.scrollTo(position.x, position.y);
1534
+ }
1535
+ });
1536
+ }
1537
+
1538
+ function saveScrollPosition () {
1539
+ var key = getStateKey();
1540
+ if (key) {
1541
+ positionStore[key] = {
1542
+ x: window.pageXOffset,
1543
+ y: window.pageYOffset
1544
+ };
1545
+ }
1546
+ }
1547
+
1548
+ function getScrollPosition () {
1549
+ var key = getStateKey();
1550
+ if (key) {
1551
+ return positionStore[key]
1552
+ }
1553
+ }
1554
+
1555
+ function getElementPosition (el, offset) {
1556
+ var docEl = document.documentElement;
1557
+ var docRect = docEl.getBoundingClientRect();
1558
+ var elRect = el.getBoundingClientRect();
1559
+ return {
1560
+ x: elRect.left - docRect.left - offset.x,
1561
+ y: elRect.top - docRect.top - offset.y
1562
+ }
1563
+ }
1564
+
1565
+ function isValidPosition (obj) {
1566
+ return isNumber(obj.x) || isNumber(obj.y)
1567
+ }
1568
+
1569
+ function normalizePosition (obj) {
1570
+ return {
1571
+ x: isNumber(obj.x) ? obj.x : window.pageXOffset,
1572
+ y: isNumber(obj.y) ? obj.y : window.pageYOffset
1573
+ }
1574
+ }
1575
+
1576
+ function normalizeOffset (obj) {
1577
+ return {
1578
+ x: isNumber(obj.x) ? obj.x : 0,
1579
+ y: isNumber(obj.y) ? obj.y : 0
1580
+ }
1581
+ }
1582
+
1583
+ function isNumber (v) {
1584
+ return typeof v === 'number'
1585
+ }
1586
+
1587
+ /* */
1588
+
1589
+ var supportsPushState = inBrowser && (function () {
1590
+ var ua = window.navigator.userAgent;
1591
+
1592
+ if (
1593
+ (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
1594
+ ua.indexOf('Mobile Safari') !== -1 &&
1595
+ ua.indexOf('Chrome') === -1 &&
1596
+ ua.indexOf('Windows Phone') === -1
1597
+ ) {
1598
+ return false
1599
+ }
1600
+
1601
+ return window.history && 'pushState' in window.history
1602
+ })();
1603
+
1604
+ // use User Timing api (if present) for more accurate key precision
1605
+ var Time = inBrowser && window.performance && window.performance.now
1606
+ ? window.performance
1607
+ : Date;
1608
+
1609
+ var _key = genKey();
1610
+
1611
+ function genKey () {
1612
+ return Time.now().toFixed(3)
1613
+ }
1614
+
1615
+ function getStateKey () {
1616
+ return _key
1617
+ }
1618
+
1619
+ function setStateKey (key) {
1620
+ _key = key;
1621
+ }
1622
+
1623
+ function pushState (url, replace) {
1624
+ saveScrollPosition();
1625
+ // try...catch the pushState call to get around Safari
1626
+ // DOM Exception 18 where it limits to 100 pushState calls
1627
+ var history = window.history;
1628
+ try {
1629
+ if (replace) {
1630
+ history.replaceState({ key: _key }, '', url);
1631
+ } else {
1632
+ _key = genKey();
1633
+ history.pushState({ key: _key }, '', url);
1634
+ }
1635
+ } catch (e) {
1636
+ window.location[replace ? 'replace' : 'assign'](url);
1637
+ }
1638
+ }
1639
+
1640
+ function replaceState (url) {
1641
+ pushState(url, true);
1642
+ }
1643
+
1644
+ /* */
1645
+
1646
+ function runQueue (queue, fn, cb) {
1647
+ var step = function (index) {
1648
+ if (index >= queue.length) {
1649
+ cb();
1650
+ } else {
1651
+ if (queue[index]) {
1652
+ fn(queue[index], function () {
1653
+ step(index + 1);
1654
+ });
1655
+ } else {
1656
+ step(index + 1);
1657
+ }
1658
+ }
1659
+ };
1660
+ step(0);
1661
+ }
1662
+
1663
+ /* */
1664
+
1665
+ function resolveAsyncComponents (matched) {
1666
+ return function (to, from, next) {
1667
+ var hasAsync = false;
1668
+ var pending = 0;
1669
+ var error = null;
1670
+
1671
+ flatMapComponents(matched, function (def, _, match, key) {
1672
+ // if it's a function and doesn't have cid attached,
1673
+ // assume it's an async component resolve function.
1674
+ // we are not using Kdu's default async resolving mechanism because
1675
+ // we want to halt the navigation until the incoming component has been
1676
+ // resolved.
1677
+ if (typeof def === 'function' && def.cid === undefined) {
1678
+ hasAsync = true;
1679
+ pending++;
1680
+
1681
+ var resolve = once(function (resolvedDef) {
1682
+ if (resolvedDef.__esModule && resolvedDef.default) {
1683
+ resolvedDef = resolvedDef.default;
1684
+ }
1685
+ // save resolved on async factory in case it's used elsewhere
1686
+ def.resolved = typeof resolvedDef === 'function'
1687
+ ? resolvedDef
1688
+ : _Kdu.extend(resolvedDef);
1689
+ match.components[key] = resolvedDef;
1690
+ pending--;
1691
+ if (pending <= 0) {
1692
+ next();
1693
+ }
1694
+ });
1695
+
1696
+ var reject = once(function (reason) {
1697
+ var msg = "Failed to resolve async component " + key + ": " + reason;
1698
+ process.env.NODE_ENV !== 'production' && warn(false, msg);
1699
+ if (!error) {
1700
+ error = isError(reason)
1701
+ ? reason
1702
+ : new Error(msg);
1703
+ next(error);
1704
+ }
1705
+ });
1706
+
1707
+ var res;
1708
+ try {
1709
+ res = def(resolve, reject);
1710
+ } catch (e) {
1711
+ reject(e);
1712
+ }
1713
+ if (res) {
1714
+ if (typeof res.then === 'function') {
1715
+ res.then(resolve, reject);
1716
+ } else {
1717
+ // new syntax in Kdu
1718
+ var comp = res.component;
1719
+ if (comp && typeof comp.then === 'function') {
1720
+ comp.then(resolve, reject);
1721
+ }
1722
+ }
1723
+ }
1724
+ }
1725
+ });
1726
+
1727
+ if (!hasAsync) { next(); }
1728
+ }
1729
+ }
1730
+
1731
+ function flatMapComponents (
1732
+ matched,
1733
+ fn
1734
+ ) {
1735
+ return flatten(matched.map(function (m) {
1736
+ return Object.keys(m.components).map(function (key) { return fn(
1737
+ m.components[key],
1738
+ m.instances[key],
1739
+ m, key
1740
+ ); })
1741
+ }))
1742
+ }
1743
+
1744
+ function flatten (arr) {
1745
+ return Array.prototype.concat.apply([], arr)
1746
+ }
1747
+
1748
+ // in Webpack 2, require.ensure now also returns a Promise
1749
+ // so the resolve/reject functions may get called an extra time
1750
+ // if the user uses an arrow function shorthand that happens to
1751
+ // return that Promise.
1752
+ function once (fn) {
1753
+ var called = false;
1754
+ return function () {
1755
+ var args = [], len = arguments.length;
1756
+ while ( len-- ) args[ len ] = arguments[ len ];
1757
+
1758
+ if (called) { return }
1759
+ called = true;
1760
+ return fn.apply(this, args)
1761
+ }
1762
+ }
1763
+
1764
+ /* */
1765
+
1766
+ var History = function History (router, base) {
1767
+ this.router = router;
1768
+ this.base = normalizeBase(base);
1769
+ // start with a route object that stands for "nowhere"
1770
+ this.current = START;
1771
+ this.pending = null;
1772
+ this.ready = false;
1773
+ this.readyCbs = [];
1774
+ this.readyErrorCbs = [];
1775
+ this.errorCbs = [];
1776
+ };
1777
+
1778
+ History.prototype.listen = function listen (cb) {
1779
+ this.cb = cb;
1780
+ };
1781
+
1782
+ History.prototype.onReady = function onReady (cb, errorCb) {
1783
+ if (this.ready) {
1784
+ cb();
1785
+ } else {
1786
+ this.readyCbs.push(cb);
1787
+ if (errorCb) {
1788
+ this.readyErrorCbs.push(errorCb);
1789
+ }
1790
+ }
1791
+ };
1792
+
1793
+ History.prototype.onError = function onError (errorCb) {
1794
+ this.errorCbs.push(errorCb);
1795
+ };
1796
+
1797
+ History.prototype.transitionTo = function transitionTo (location, onComplete, onAbort) {
1798
+ var this$1 = this;
1799
+
1800
+ var route = this.router.match(location, this.current);
1801
+ this.confirmTransition(route, function () {
1802
+ this$1.updateRoute(route);
1803
+ onComplete && onComplete(route);
1804
+ this$1.ensureURL();
1805
+
1806
+ // fire ready cbs once
1807
+ if (!this$1.ready) {
1808
+ this$1.ready = true;
1809
+ this$1.readyCbs.forEach(function (cb) { cb(route); });
1810
+ }
1811
+ }, function (err) {
1812
+ if (onAbort) {
1813
+ onAbort(err);
1814
+ }
1815
+ if (err && !this$1.ready) {
1816
+ this$1.ready = true;
1817
+ this$1.readyErrorCbs.forEach(function (cb) { cb(err); });
1818
+ }
1819
+ });
1820
+ };
1821
+
1822
+ History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) {
1823
+ var this$1 = this;
1824
+
1825
+ var current = this.current;
1826
+ var abort = function (err) {
1827
+ if (isError(err)) {
1828
+ if (this$1.errorCbs.length) {
1829
+ this$1.errorCbs.forEach(function (cb) { cb(err); });
1830
+ } else {
1831
+ warn(false, 'uncaught error during route navigation:');
1832
+ console.error(err);
1833
+ }
1834
+ }
1835
+ onAbort && onAbort(err);
1836
+ };
1837
+ if (
1838
+ isSameRoute(route, current) &&
1839
+ // in the case the route map has been dynamically appended to
1840
+ route.matched.length === current.matched.length
1841
+ ) {
1842
+ this.ensureURL();
1843
+ return abort()
1844
+ }
1845
+
1846
+ var ref = resolveQueue(this.current.matched, route.matched);
1847
+ var updated = ref.updated;
1848
+ var deactivated = ref.deactivated;
1849
+ var activated = ref.activated;
1850
+
1851
+ var queue = [].concat(
1852
+ // in-component leave guards
1853
+ extractLeaveGuards(deactivated),
1854
+ // global before hooks
1855
+ this.router.beforeHooks,
1856
+ // in-component update hooks
1857
+ extractUpdateHooks(updated),
1858
+ // in-config enter guards
1859
+ activated.map(function (m) { return m.beforeEnter; }),
1860
+ // async components
1861
+ resolveAsyncComponents(activated)
1862
+ );
1863
+
1864
+ this.pending = route;
1865
+ var iterator = function (hook, next) {
1866
+ if (this$1.pending !== route) {
1867
+ return abort()
1868
+ }
1869
+ try {
1870
+ hook(route, current, function (to) {
1871
+ if (to === false || isError(to)) {
1872
+ // next(false) -> abort navigation, ensure current URL
1873
+ this$1.ensureURL(true);
1874
+ abort(to);
1875
+ } else if (
1876
+ typeof to === 'string' ||
1877
+ (typeof to === 'object' && (
1878
+ typeof to.path === 'string' ||
1879
+ typeof to.name === 'string'
1880
+ ))
1881
+ ) {
1882
+ // next('/') or next({ path: '/' }) -> redirect
1883
+ abort();
1884
+ if (typeof to === 'object' && to.replace) {
1885
+ this$1.replace(to);
1886
+ } else {
1887
+ this$1.push(to);
1888
+ }
1889
+ } else {
1890
+ // confirm transition and pass on the value
1891
+ next(to);
1892
+ }
1893
+ });
1894
+ } catch (e) {
1895
+ abort(e);
1896
+ }
1897
+ };
1898
+
1899
+ runQueue(queue, iterator, function () {
1900
+ var postEnterCbs = [];
1901
+ var isValid = function () { return this$1.current === route; };
1902
+ // wait until async components are resolved before
1903
+ // extracting in-component enter guards
1904
+ var enterGuards = extractEnterGuards(activated, postEnterCbs, isValid);
1905
+ var queue = enterGuards.concat(this$1.router.resolveHooks);
1906
+ runQueue(queue, iterator, function () {
1907
+ if (this$1.pending !== route) {
1908
+ return abort()
1909
+ }
1910
+ this$1.pending = null;
1911
+ onComplete(route);
1912
+ if (this$1.router.app) {
1913
+ this$1.router.app.$nextTick(function () {
1914
+ postEnterCbs.forEach(function (cb) { cb(); });
1915
+ });
1916
+ }
1917
+ });
1918
+ });
1919
+ };
1920
+
1921
+ History.prototype.updateRoute = function updateRoute (route) {
1922
+ var prev = this.current;
1923
+ this.current = route;
1924
+ this.cb && this.cb(route);
1925
+ this.router.afterHooks.forEach(function (hook) {
1926
+ hook && hook(route, prev);
1927
+ });
1928
+ };
1929
+
1930
+ function normalizeBase (base) {
1931
+ if (!base) {
1932
+ if (inBrowser) {
1933
+ // respect <base> tag
1934
+ var baseEl = document.querySelector('base');
1935
+ base = (baseEl && baseEl.getAttribute('href')) || '/';
1936
+ // strip full URL origin
1937
+ base = base.replace(/^https?:\/\/[^\/]+/, '');
1938
+ } else {
1939
+ base = '/';
1940
+ }
1941
+ }
1942
+ // make sure there's the starting slash
1943
+ if (base.charAt(0) !== '/') {
1944
+ base = '/' + base;
1945
+ }
1946
+ // remove trailing slash
1947
+ return base.replace(/\/$/, '')
1948
+ }
1949
+
1950
+ function resolveQueue (
1951
+ current,
1952
+ next
1953
+ ) {
1954
+ var i;
1955
+ var max = Math.max(current.length, next.length);
1956
+ for (i = 0; i < max; i++) {
1957
+ if (current[i] !== next[i]) {
1958
+ break
1959
+ }
1960
+ }
1961
+ return {
1962
+ updated: next.slice(0, i),
1963
+ activated: next.slice(i),
1964
+ deactivated: current.slice(i)
1965
+ }
1966
+ }
1967
+
1968
+ function extractGuards (
1969
+ records,
1970
+ name,
1971
+ bind,
1972
+ reverse
1973
+ ) {
1974
+ var guards = flatMapComponents(records, function (def, instance, match, key) {
1975
+ var guard = extractGuard(def, name);
1976
+ if (guard) {
1977
+ return Array.isArray(guard)
1978
+ ? guard.map(function (guard) { return bind(guard, instance, match, key); })
1979
+ : bind(guard, instance, match, key)
1980
+ }
1981
+ });
1982
+ return flatten(reverse ? guards.reverse() : guards)
1983
+ }
1984
+
1985
+ function extractGuard (
1986
+ def,
1987
+ key
1988
+ ) {
1989
+ if (typeof def !== 'function') {
1990
+ // extend now so that global mixins are applied.
1991
+ def = _Kdu.extend(def);
1992
+ }
1993
+ return def.options[key]
1994
+ }
1995
+
1996
+ function extractLeaveGuards (deactivated) {
1997
+ return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
1998
+ }
1999
+
2000
+ function extractUpdateHooks (updated) {
2001
+ return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
2002
+ }
2003
+
2004
+ function bindGuard (guard, instance) {
2005
+ if (instance) {
2006
+ return function boundRouteGuard () {
2007
+ return guard.apply(instance, arguments)
2008
+ }
2009
+ }
2010
+ }
2011
+
2012
+ function extractEnterGuards (
2013
+ activated,
2014
+ cbs,
2015
+ isValid
2016
+ ) {
2017
+ return extractGuards(activated, 'beforeRouteEnter', function (guard, _, match, key) {
2018
+ return bindEnterGuard(guard, match, key, cbs, isValid)
2019
+ })
2020
+ }
2021
+
2022
+ function bindEnterGuard (
2023
+ guard,
2024
+ match,
2025
+ key,
2026
+ cbs,
2027
+ isValid
2028
+ ) {
2029
+ return function routeEnterGuard (to, from, next) {
2030
+ return guard(to, from, function (cb) {
2031
+ next(cb);
2032
+ if (typeof cb === 'function') {
2033
+ cbs.push(function () {
2034
+ // #750
2035
+ // if a router-view is wrapped with an out-in transition,
2036
+ // the instance may not have been registered at this time.
2037
+ // we will need to poll for registration until current route
2038
+ // is no longer valid.
2039
+ poll(cb, match.instances, key, isValid);
2040
+ });
2041
+ }
2042
+ })
2043
+ }
2044
+ }
2045
+
2046
+ function poll (
2047
+ cb, // somehow flow cannot infer this is a function
2048
+ instances,
2049
+ key,
2050
+ isValid
2051
+ ) {
2052
+ if (instances[key]) {
2053
+ cb(instances[key]);
2054
+ } else if (isValid()) {
2055
+ setTimeout(function () {
2056
+ poll(cb, instances, key, isValid);
2057
+ }, 16);
2058
+ }
2059
+ }
2060
+
2061
+ /* */
2062
+
2063
+
2064
+ var HTML5History = (function (History$$1) {
2065
+ function HTML5History (router, base) {
2066
+ var this$1 = this;
2067
+
2068
+ History$$1.call(this, router, base);
2069
+
2070
+ var expectScroll = router.options.scrollBehavior;
2071
+
2072
+ if (expectScroll) {
2073
+ setupScroll();
2074
+ }
2075
+
2076
+ window.addEventListener('popstate', function (e) {
2077
+ var current = this$1.current;
2078
+ this$1.transitionTo(getLocation(this$1.base), function (route) {
2079
+ if (expectScroll) {
2080
+ handleScroll(router, route, current, true);
2081
+ }
2082
+ });
2083
+ });
2084
+ }
2085
+
2086
+ if ( History$$1 ) HTML5History.__proto__ = History$$1;
2087
+ HTML5History.prototype = Object.create( History$$1 && History$$1.prototype );
2088
+ HTML5History.prototype.constructor = HTML5History;
2089
+
2090
+ HTML5History.prototype.go = function go (n) {
2091
+ window.history.go(n);
2092
+ };
2093
+
2094
+ HTML5History.prototype.push = function push (location, onComplete, onAbort) {
2095
+ var this$1 = this;
2096
+
2097
+ var ref = this;
2098
+ var fromRoute = ref.current;
2099
+ this.transitionTo(location, function (route) {
2100
+ pushState(cleanPath(this$1.base + route.fullPath));
2101
+ handleScroll(this$1.router, route, fromRoute, false);
2102
+ onComplete && onComplete(route);
2103
+ }, onAbort);
2104
+ };
2105
+
2106
+ HTML5History.prototype.replace = function replace (location, onComplete, onAbort) {
2107
+ var this$1 = this;
2108
+
2109
+ var ref = this;
2110
+ var fromRoute = ref.current;
2111
+ this.transitionTo(location, function (route) {
2112
+ replaceState(cleanPath(this$1.base + route.fullPath));
2113
+ handleScroll(this$1.router, route, fromRoute, false);
2114
+ onComplete && onComplete(route);
2115
+ }, onAbort);
2116
+ };
2117
+
2118
+ HTML5History.prototype.ensureURL = function ensureURL (push) {
2119
+ if (getLocation(this.base) !== this.current.fullPath) {
2120
+ var current = cleanPath(this.base + this.current.fullPath);
2121
+ push ? pushState(current) : replaceState(current);
2122
+ }
2123
+ };
2124
+
2125
+ HTML5History.prototype.getCurrentLocation = function getCurrentLocation () {
2126
+ return getLocation(this.base)
2127
+ };
2128
+
2129
+ return HTML5History;
2130
+ }(History));
2131
+
2132
+ function getLocation (base) {
2133
+ var path = window.location.pathname;
2134
+ if (base && path.indexOf(base) === 0) {
2135
+ path = path.slice(base.length);
2136
+ }
2137
+ return (path || '/') + window.location.search + window.location.hash
2138
+ }
2139
+
2140
+ /* */
2141
+
2142
+
2143
+ var HashHistory = (function (History$$1) {
2144
+ function HashHistory (router, base, fallback) {
2145
+ History$$1.call(this, router, base);
2146
+ // check history fallback deeplinking
2147
+ if (fallback && checkFallback(this.base)) {
2148
+ return
2149
+ }
2150
+ ensureSlash();
2151
+ }
2152
+
2153
+ if ( History$$1 ) HashHistory.__proto__ = History$$1;
2154
+ HashHistory.prototype = Object.create( History$$1 && History$$1.prototype );
2155
+ HashHistory.prototype.constructor = HashHistory;
2156
+
2157
+ // this is delayed until the app mounts
2158
+ // to avoid the hashchange listener being fired too early
2159
+ HashHistory.prototype.setupListeners = function setupListeners () {
2160
+ var this$1 = this;
2161
+
2162
+ window.addEventListener('hashchange', function () {
2163
+ if (!ensureSlash()) {
2164
+ return
2165
+ }
2166
+ this$1.transitionTo(getHash(), function (route) {
2167
+ replaceHash(route.fullPath);
2168
+ });
2169
+ });
2170
+ };
2171
+
2172
+ HashHistory.prototype.push = function push (location, onComplete, onAbort) {
2173
+ this.transitionTo(location, function (route) {
2174
+ pushHash(route.fullPath);
2175
+ onComplete && onComplete(route);
2176
+ }, onAbort);
2177
+ };
2178
+
2179
+ HashHistory.prototype.replace = function replace (location, onComplete, onAbort) {
2180
+ this.transitionTo(location, function (route) {
2181
+ replaceHash(route.fullPath);
2182
+ onComplete && onComplete(route);
2183
+ }, onAbort);
2184
+ };
2185
+
2186
+ HashHistory.prototype.go = function go (n) {
2187
+ window.history.go(n);
2188
+ };
2189
+
2190
+ HashHistory.prototype.ensureURL = function ensureURL (push) {
2191
+ var current = this.current.fullPath;
2192
+ if (getHash() !== current) {
2193
+ push ? pushHash(current) : replaceHash(current);
2194
+ }
2195
+ };
2196
+
2197
+ HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
2198
+ return getHash()
2199
+ };
2200
+
2201
+ return HashHistory;
2202
+ }(History));
2203
+
2204
+ function checkFallback (base) {
2205
+ var location = getLocation(base);
2206
+ if (!/^\/#/.test(location)) {
2207
+ window.location.replace(
2208
+ cleanPath(base + '/#' + location)
2209
+ );
2210
+ return true
2211
+ }
2212
+ }
2213
+
2214
+ function ensureSlash () {
2215
+ var path = getHash();
2216
+ if (path.charAt(0) === '/') {
2217
+ return true
2218
+ }
2219
+ replaceHash('/' + path);
2220
+ return false
2221
+ }
2222
+
2223
+ function getHash () {
2224
+ // We can't use window.location.hash here because it's not
2225
+ // consistent across browsers - Firefox will pre-decode it!
2226
+ var href = window.location.href;
2227
+ var index = href.indexOf('#');
2228
+ return index === -1 ? '' : href.slice(index + 1)
2229
+ }
2230
+
2231
+ function pushHash (path) {
2232
+ window.location.hash = path;
2233
+ }
2234
+
2235
+ function replaceHash (path) {
2236
+ var href = window.location.href;
2237
+ var i = href.indexOf('#');
2238
+ var base = i >= 0 ? href.slice(0, i) : href;
2239
+ window.location.replace((base + "#" + path));
2240
+ }
2241
+
2242
+ /* */
2243
+
2244
+
2245
+ var AbstractHistory = (function (History$$1) {
2246
+ function AbstractHistory (router, base) {
2247
+ History$$1.call(this, router, base);
2248
+ this.stack = [];
2249
+ this.index = -1;
2250
+ }
2251
+
2252
+ if ( History$$1 ) AbstractHistory.__proto__ = History$$1;
2253
+ AbstractHistory.prototype = Object.create( History$$1 && History$$1.prototype );
2254
+ AbstractHistory.prototype.constructor = AbstractHistory;
2255
+
2256
+ AbstractHistory.prototype.push = function push (location, onComplete, onAbort) {
2257
+ var this$1 = this;
2258
+
2259
+ this.transitionTo(location, function (route) {
2260
+ this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route);
2261
+ this$1.index++;
2262
+ onComplete && onComplete(route);
2263
+ }, onAbort);
2264
+ };
2265
+
2266
+ AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) {
2267
+ var this$1 = this;
2268
+
2269
+ this.transitionTo(location, function (route) {
2270
+ this$1.stack = this$1.stack.slice(0, this$1.index).concat(route);
2271
+ onComplete && onComplete(route);
2272
+ }, onAbort);
2273
+ };
2274
+
2275
+ AbstractHistory.prototype.go = function go (n) {
2276
+ var this$1 = this;
2277
+
2278
+ var targetIndex = this.index + n;
2279
+ if (targetIndex < 0 || targetIndex >= this.stack.length) {
2280
+ return
2281
+ }
2282
+ var route = this.stack[targetIndex];
2283
+ this.confirmTransition(route, function () {
2284
+ this$1.index = targetIndex;
2285
+ this$1.updateRoute(route);
2286
+ });
2287
+ };
2288
+
2289
+ AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () {
2290
+ var current = this.stack[this.stack.length - 1];
2291
+ return current ? current.fullPath : '/'
2292
+ };
2293
+
2294
+ AbstractHistory.prototype.ensureURL = function ensureURL () {
2295
+ // noop
2296
+ };
2297
+
2298
+ return AbstractHistory;
2299
+ }(History));
2300
+
2301
+ /* */
2302
+
2303
+ var KduRouter = function KduRouter (options) {
2304
+ if ( options === void 0 ) options = {};
2305
+
2306
+ this.app = null;
2307
+ this.apps = [];
2308
+ this.options = options;
2309
+ this.beforeHooks = [];
2310
+ this.resolveHooks = [];
2311
+ this.afterHooks = [];
2312
+ this.matcher = createMatcher(options.routes || [], this);
2313
+
2314
+ var mode = options.mode || 'hash';
2315
+ this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false;
2316
+ if (this.fallback) {
2317
+ mode = 'hash';
2318
+ }
2319
+ if (!inBrowser) {
2320
+ mode = 'abstract';
2321
+ }
2322
+ this.mode = mode;
2323
+
2324
+ switch (mode) {
2325
+ case 'history':
2326
+ this.history = new HTML5History(this, options.base);
2327
+ break
2328
+ case 'hash':
2329
+ this.history = new HashHistory(this, options.base, this.fallback);
2330
+ break
2331
+ case 'abstract':
2332
+ this.history = new AbstractHistory(this, options.base);
2333
+ break
2334
+ default:
2335
+ if (process.env.NODE_ENV !== 'production') {
2336
+ assert(false, ("invalid mode: " + mode));
2337
+ }
2338
+ }
2339
+ };
2340
+
2341
+ var prototypeAccessors = { currentRoute: {} };
2342
+
2343
+ KduRouter.prototype.match = function match (
2344
+ raw,
2345
+ current,
2346
+ redirectedFrom
2347
+ ) {
2348
+ return this.matcher.match(raw, current, redirectedFrom)
2349
+ };
2350
+
2351
+ prototypeAccessors.currentRoute.get = function () {
2352
+ return this.history && this.history.current
2353
+ };
2354
+
2355
+ KduRouter.prototype.init = function init (app /* Kdu component instance */) {
2356
+ var this$1 = this;
2357
+
2358
+ process.env.NODE_ENV !== 'production' && assert(
2359
+ install.installed,
2360
+ "not installed. Make sure to call `Kdu.use(KduRouter)` " +
2361
+ "before creating root instance."
2362
+ );
2363
+
2364
+ this.apps.push(app);
2365
+
2366
+ // main app already initialized.
2367
+ if (this.app) {
2368
+ return
2369
+ }
2370
+
2371
+ this.app = app;
2372
+
2373
+ var history = this.history;
2374
+
2375
+ if (history instanceof HTML5History) {
2376
+ history.transitionTo(history.getCurrentLocation());
2377
+ } else if (history instanceof HashHistory) {
2378
+ var setupHashListener = function () {
2379
+ history.setupListeners();
2380
+ };
2381
+ history.transitionTo(
2382
+ history.getCurrentLocation(),
2383
+ setupHashListener,
2384
+ setupHashListener
2385
+ );
2386
+ }
2387
+
2388
+ history.listen(function (route) {
2389
+ this$1.apps.forEach(function (app) {
2390
+ app._route = route;
2391
+ });
2392
+ });
2393
+ };
2394
+
2395
+ KduRouter.prototype.beforeEach = function beforeEach (fn) {
2396
+ return registerHook(this.beforeHooks, fn)
2397
+ };
2398
+
2399
+ KduRouter.prototype.beforeResolve = function beforeResolve (fn) {
2400
+ return registerHook(this.resolveHooks, fn)
2401
+ };
2402
+
2403
+ KduRouter.prototype.afterEach = function afterEach (fn) {
2404
+ return registerHook(this.afterHooks, fn)
2405
+ };
2406
+
2407
+ KduRouter.prototype.onReady = function onReady (cb, errorCb) {
2408
+ this.history.onReady(cb, errorCb);
2409
+ };
2410
+
2411
+ KduRouter.prototype.onError = function onError (errorCb) {
2412
+ this.history.onError(errorCb);
2413
+ };
2414
+
2415
+ KduRouter.prototype.push = function push (location, onComplete, onAbort) {
2416
+ this.history.push(location, onComplete, onAbort);
2417
+ };
2418
+
2419
+ KduRouter.prototype.replace = function replace (location, onComplete, onAbort) {
2420
+ this.history.replace(location, onComplete, onAbort);
2421
+ };
2422
+
2423
+ KduRouter.prototype.go = function go (n) {
2424
+ this.history.go(n);
2425
+ };
2426
+
2427
+ KduRouter.prototype.back = function back () {
2428
+ this.go(-1);
2429
+ };
2430
+
2431
+ KduRouter.prototype.forward = function forward () {
2432
+ this.go(1);
2433
+ };
2434
+
2435
+ KduRouter.prototype.getMatchedComponents = function getMatchedComponents (to) {
2436
+ var route = to
2437
+ ? to.matched
2438
+ ? to
2439
+ : this.resolve(to).route
2440
+ : this.currentRoute;
2441
+ if (!route) {
2442
+ return []
2443
+ }
2444
+ return [].concat.apply([], route.matched.map(function (m) {
2445
+ return Object.keys(m.components).map(function (key) {
2446
+ return m.components[key]
2447
+ })
2448
+ }))
2449
+ };
2450
+
2451
+ KduRouter.prototype.resolve = function resolve (
2452
+ to,
2453
+ current,
2454
+ append
2455
+ ) {
2456
+ var location = normalizeLocation(
2457
+ to,
2458
+ current || this.history.current,
2459
+ append,
2460
+ this
2461
+ );
2462
+ var route = this.match(location, current);
2463
+ var fullPath = route.redirectedFrom || route.fullPath;
2464
+ var base = this.history.base;
2465
+ var href = createHref(base, fullPath, this.mode);
2466
+ return {
2467
+ location: location,
2468
+ route: route,
2469
+ href: href,
2470
+ // for backwards compat
2471
+ normalizedTo: location,
2472
+ resolved: route
2473
+ }
2474
+ };
2475
+
2476
+ KduRouter.prototype.addRoutes = function addRoutes (routes) {
2477
+ this.matcher.addRoutes(routes);
2478
+ if (this.history.current !== START) {
2479
+ this.history.transitionTo(this.history.getCurrentLocation());
2480
+ }
2481
+ };
2482
+
2483
+ Object.defineProperties( KduRouter.prototype, prototypeAccessors );
2484
+
2485
+ function registerHook (list, fn) {
2486
+ list.push(fn);
2487
+ return function () {
2488
+ var i = list.indexOf(fn);
2489
+ if (i > -1) { list.splice(i, 1); }
2490
+ }
2491
+ }
2492
+
2493
+ function createHref (base, fullPath, mode) {
2494
+ var path = mode === 'hash' ? '#' + fullPath : fullPath;
2495
+ return base ? cleanPath(base + '/' + path) : path
2496
+ }
2497
+
2498
+ KduRouter.install = install;
2499
+ KduRouter.version = '2.7.0';
2500
+
2501
+ if (inBrowser && window.Kdu) {
2502
+ window.Kdu.use(KduRouter);
2503
+ }
2504
+
2505
+ export default KduRouter;