kdu-router 3.5.4 → 4.0.16

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.
Files changed (45) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +10 -4
  3. package/dist/kdu-router.cjs.js +3484 -0
  4. package/dist/kdu-router.cjs.prod.js +2759 -0
  5. package/dist/kdu-router.d.ts +1349 -0
  6. package/dist/kdu-router.esm-browser.js +3460 -0
  7. package/dist/kdu-router.esm-bundler.js +3478 -0
  8. package/dist/kdu-router.global.js +3625 -0
  9. package/dist/kdu-router.global.prod.js +6 -0
  10. package/ketur/attributes.json +8 -14
  11. package/ketur/tags.json +2 -12
  12. package/package.json +77 -71
  13. package/dist/kdu-router.common.js +0 -3147
  14. package/dist/kdu-router.esm.browser.js +0 -3113
  15. package/dist/kdu-router.esm.browser.min.js +0 -11
  16. package/dist/kdu-router.esm.js +0 -3145
  17. package/dist/kdu-router.js +0 -3152
  18. package/dist/kdu-router.min.js +0 -11
  19. package/src/components/link.js +0 -224
  20. package/src/components/view.js +0 -155
  21. package/src/create-matcher.js +0 -226
  22. package/src/create-route-map.js +0 -220
  23. package/src/history/abstract.js +0 -72
  24. package/src/history/base.js +0 -379
  25. package/src/history/hash.js +0 -152
  26. package/src/history/html5.js +0 -99
  27. package/src/index.js +0 -293
  28. package/src/install.js +0 -52
  29. package/src/util/async.js +0 -18
  30. package/src/util/dom.js +0 -3
  31. package/src/util/errors.js +0 -86
  32. package/src/util/location.js +0 -69
  33. package/src/util/misc.js +0 -6
  34. package/src/util/params.js +0 -37
  35. package/src/util/path.js +0 -74
  36. package/src/util/push-state.js +0 -46
  37. package/src/util/query.js +0 -113
  38. package/src/util/resolve-components.js +0 -109
  39. package/src/util/route.js +0 -151
  40. package/src/util/scroll.js +0 -175
  41. package/src/util/state-key.js +0 -22
  42. package/src/util/warn.js +0 -14
  43. package/types/index.d.ts +0 -21
  44. package/types/kdu.d.ts +0 -22
  45. package/types/router.d.ts +0 -211
@@ -1,3152 +0,0 @@
1
- /*!
2
- * kdu-router v3.5.4
3
- * (c) 2022 NKDuy
4
- * @license MIT
5
- */
6
- (function (global, factory) {
7
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
8
- typeof define === 'function' && define.amd ? define(factory) :
9
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.KduRouter = factory());
10
- }(this, (function () { 'use strict';
11
-
12
- /* */
13
-
14
- function assert (condition, message) {
15
- if (!condition) {
16
- throw new Error(("[kdu-router] " + message))
17
- }
18
- }
19
-
20
- function warn (condition, message) {
21
- if (!condition) {
22
- typeof console !== 'undefined' && console.warn(("[kdu-router] " + message));
23
- }
24
- }
25
-
26
- function extend (a, b) {
27
- for (var key in b) {
28
- a[key] = b[key];
29
- }
30
- return a
31
- }
32
-
33
- /* */
34
-
35
- var encodeReserveRE = /[!'()*]/g;
36
- var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); };
37
- var commaRE = /%2C/g;
38
-
39
- // fixed encodeURIComponent which is more conformant to RFC3986:
40
- // - escapes [!'()*]
41
- // - preserve commas
42
- var encode = function (str) { return encodeURIComponent(str)
43
- .replace(encodeReserveRE, encodeReserveReplacer)
44
- .replace(commaRE, ','); };
45
-
46
- function decode (str) {
47
- try {
48
- return decodeURIComponent(str)
49
- } catch (err) {
50
- {
51
- warn(false, ("Error decoding \"" + str + "\". Leaving it intact."));
52
- }
53
- }
54
- return str
55
- }
56
-
57
- function resolveQuery (
58
- query,
59
- extraQuery,
60
- _parseQuery
61
- ) {
62
- if ( extraQuery === void 0 ) extraQuery = {};
63
-
64
- var parse = _parseQuery || parseQuery;
65
- var parsedQuery;
66
- try {
67
- parsedQuery = parse(query || '');
68
- } catch (e) {
69
- warn(false, e.message);
70
- parsedQuery = {};
71
- }
72
- for (var key in extraQuery) {
73
- var value = extraQuery[key];
74
- parsedQuery[key] = Array.isArray(value)
75
- ? value.map(castQueryParamValue)
76
- : castQueryParamValue(value);
77
- }
78
- return parsedQuery
79
- }
80
-
81
- var castQueryParamValue = function (value) { return (value == null || typeof value === 'object' ? value : String(value)); };
82
-
83
- function parseQuery (query) {
84
- var res = {};
85
-
86
- query = query.trim().replace(/^(\?|#|&)/, '');
87
-
88
- if (!query) {
89
- return res
90
- }
91
-
92
- query.split('&').forEach(function (param) {
93
- var parts = param.replace(/\+/g, ' ').split('=');
94
- var key = decode(parts.shift());
95
- var val = parts.length > 0 ? decode(parts.join('=')) : null;
96
-
97
- if (res[key] === undefined) {
98
- res[key] = val;
99
- } else if (Array.isArray(res[key])) {
100
- res[key].push(val);
101
- } else {
102
- res[key] = [res[key], val];
103
- }
104
- });
105
-
106
- return res
107
- }
108
-
109
- function stringifyQuery (obj) {
110
- var res = obj
111
- ? Object.keys(obj)
112
- .map(function (key) {
113
- var val = obj[key];
114
-
115
- if (val === undefined) {
116
- return ''
117
- }
118
-
119
- if (val === null) {
120
- return encode(key)
121
- }
122
-
123
- if (Array.isArray(val)) {
124
- var result = [];
125
- val.forEach(function (val2) {
126
- if (val2 === undefined) {
127
- return
128
- }
129
- if (val2 === null) {
130
- result.push(encode(key));
131
- } else {
132
- result.push(encode(key) + '=' + encode(val2));
133
- }
134
- });
135
- return result.join('&')
136
- }
137
-
138
- return encode(key) + '=' + encode(val)
139
- })
140
- .filter(function (x) { return x.length > 0; })
141
- .join('&')
142
- : null;
143
- return res ? ("?" + res) : ''
144
- }
145
-
146
- /* */
147
-
148
- var trailingSlashRE = /\/?$/;
149
-
150
- function createRoute (
151
- record,
152
- location,
153
- redirectedFrom,
154
- router
155
- ) {
156
- var stringifyQuery = router && router.options.stringifyQuery;
157
-
158
- var query = location.query || {};
159
- try {
160
- query = clone(query);
161
- } catch (e) {}
162
-
163
- var route = {
164
- name: location.name || (record && record.name),
165
- meta: (record && record.meta) || {},
166
- path: location.path || '/',
167
- hash: location.hash || '',
168
- query: query,
169
- params: location.params || {},
170
- fullPath: getFullPath(location, stringifyQuery),
171
- matched: record ? formatMatch(record) : []
172
- };
173
- if (redirectedFrom) {
174
- route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery);
175
- }
176
- return Object.freeze(route)
177
- }
178
-
179
- function clone (value) {
180
- if (Array.isArray(value)) {
181
- return value.map(clone)
182
- } else if (value && typeof value === 'object') {
183
- var res = {};
184
- for (var key in value) {
185
- res[key] = clone(value[key]);
186
- }
187
- return res
188
- } else {
189
- return value
190
- }
191
- }
192
-
193
- // the starting route that represents the initial state
194
- var START = createRoute(null, {
195
- path: '/'
196
- });
197
-
198
- function formatMatch (record) {
199
- var res = [];
200
- while (record) {
201
- res.unshift(record);
202
- record = record.parent;
203
- }
204
- return res
205
- }
206
-
207
- function getFullPath (
208
- ref,
209
- _stringifyQuery
210
- ) {
211
- var path = ref.path;
212
- var query = ref.query; if ( query === void 0 ) query = {};
213
- var hash = ref.hash; if ( hash === void 0 ) hash = '';
214
-
215
- var stringify = _stringifyQuery || stringifyQuery;
216
- return (path || '/') + stringify(query) + hash
217
- }
218
-
219
- function isSameRoute (a, b, onlyPath) {
220
- if (b === START) {
221
- return a === b
222
- } else if (!b) {
223
- return false
224
- } else if (a.path && b.path) {
225
- return a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && (onlyPath ||
226
- a.hash === b.hash &&
227
- isObjectEqual(a.query, b.query))
228
- } else if (a.name && b.name) {
229
- return (
230
- a.name === b.name &&
231
- (onlyPath || (
232
- a.hash === b.hash &&
233
- isObjectEqual(a.query, b.query) &&
234
- isObjectEqual(a.params, b.params))
235
- )
236
- )
237
- } else {
238
- return false
239
- }
240
- }
241
-
242
- function isObjectEqual (a, b) {
243
- if ( a === void 0 ) a = {};
244
- if ( b === void 0 ) b = {};
245
-
246
- // handle null value #1566
247
- if (!a || !b) { return a === b }
248
- var aKeys = Object.keys(a).sort();
249
- var bKeys = Object.keys(b).sort();
250
- if (aKeys.length !== bKeys.length) {
251
- return false
252
- }
253
- return aKeys.every(function (key, i) {
254
- var aVal = a[key];
255
- var bKey = bKeys[i];
256
- if (bKey !== key) { return false }
257
- var bVal = b[key];
258
- // query values can be null and undefined
259
- if (aVal == null || bVal == null) { return aVal === bVal }
260
- // check nested equality
261
- if (typeof aVal === 'object' && typeof bVal === 'object') {
262
- return isObjectEqual(aVal, bVal)
263
- }
264
- return String(aVal) === String(bVal)
265
- })
266
- }
267
-
268
- function isIncludedRoute (current, target) {
269
- return (
270
- current.path.replace(trailingSlashRE, '/').indexOf(
271
- target.path.replace(trailingSlashRE, '/')
272
- ) === 0 &&
273
- (!target.hash || current.hash === target.hash) &&
274
- queryIncludes(current.query, target.query)
275
- )
276
- }
277
-
278
- function queryIncludes (current, target) {
279
- for (var key in target) {
280
- if (!(key in current)) {
281
- return false
282
- }
283
- }
284
- return true
285
- }
286
-
287
- function handleRouteEntered (route) {
288
- for (var i = 0; i < route.matched.length; i++) {
289
- var record = route.matched[i];
290
- for (var name in record.instances) {
291
- var instance = record.instances[name];
292
- var cbs = record.enteredCbs[name];
293
- if (!instance || !cbs) { continue }
294
- delete record.enteredCbs[name];
295
- for (var i$1 = 0; i$1 < cbs.length; i$1++) {
296
- if (!instance._isBeingDestroyed) { cbs[i$1](instance); }
297
- }
298
- }
299
- }
300
- }
301
-
302
- var View = {
303
- name: 'RouterView',
304
- functional: true,
305
- props: {
306
- name: {
307
- type: String,
308
- default: 'default'
309
- }
310
- },
311
- render: function render (_, ref) {
312
- var props = ref.props;
313
- var children = ref.children;
314
- var parent = ref.parent;
315
- var data = ref.data;
316
-
317
- // used by devtools to display a router-view badge
318
- data.routerView = true;
319
-
320
- // directly use parent context's createElement() function
321
- // so that components rendered by router-view can resolve named slots
322
- var h = parent.$createElement;
323
- var name = props.name;
324
- var route = parent.$route;
325
- var cache = parent._routerViewCache || (parent._routerViewCache = {});
326
-
327
- // determine current view depth, also check to see if the tree
328
- // has been toggled inactive but kept-alive.
329
- var depth = 0;
330
- var inactive = false;
331
- while (parent && parent._routerRoot !== parent) {
332
- var knodeData = parent.$knode ? parent.$knode.data : {};
333
- if (knodeData.routerView) {
334
- depth++;
335
- }
336
- if (knodeData.keepAlive && parent._directInactive && parent._inactive) {
337
- inactive = true;
338
- }
339
- parent = parent.$parent;
340
- }
341
- data.routerViewDepth = depth;
342
-
343
- // render previous view if the tree is inactive and kept-alive
344
- if (inactive) {
345
- var cachedData = cache[name];
346
- var cachedComponent = cachedData && cachedData.component;
347
- if (cachedComponent) {
348
- // #2301
349
- // pass props
350
- if (cachedData.configProps) {
351
- fillPropsinData(cachedComponent, data, cachedData.route, cachedData.configProps);
352
- }
353
- return h(cachedComponent, data, children)
354
- } else {
355
- // render previous empty view
356
- return h()
357
- }
358
- }
359
-
360
- var matched = route.matched[depth];
361
- var component = matched && matched.components[name];
362
-
363
- // render empty node if no matched route or no config component
364
- if (!matched || !component) {
365
- cache[name] = null;
366
- return h()
367
- }
368
-
369
- // cache component
370
- cache[name] = { component: component };
371
-
372
- // attach instance registration hook
373
- // this will be called in the instance's injected lifecycle hooks
374
- data.registerRouteInstance = function (vm, val) {
375
- // val could be undefined for unregistration
376
- var current = matched.instances[name];
377
- if (
378
- (val && current !== vm) ||
379
- (!val && current === vm)
380
- ) {
381
- matched.instances[name] = val;
382
- }
383
- }
384
-
385
- // also register instance in prepatch hook
386
- // in case the same component instance is reused across different routes
387
- ;(data.hook || (data.hook = {})).prepatch = function (_, knode) {
388
- matched.instances[name] = knode.componentInstance;
389
- };
390
-
391
- // register instance in init hook
392
- // in case kept-alive component be actived when routes changed
393
- data.hook.init = function (knode) {
394
- if (knode.data.keepAlive &&
395
- knode.componentInstance &&
396
- knode.componentInstance !== matched.instances[name]
397
- ) {
398
- matched.instances[name] = knode.componentInstance;
399
- }
400
-
401
- // if the route transition has already been confirmed then we weren't
402
- // able to call the cbs during confirmation as the component was not
403
- // registered yet, so we call it here.
404
- handleRouteEntered(route);
405
- };
406
-
407
- var configProps = matched.props && matched.props[name];
408
- // save route and configProps in cache
409
- if (configProps) {
410
- extend(cache[name], {
411
- route: route,
412
- configProps: configProps
413
- });
414
- fillPropsinData(component, data, route, configProps);
415
- }
416
-
417
- return h(component, data, children)
418
- }
419
- };
420
-
421
- function fillPropsinData (component, data, route, configProps) {
422
- // resolve props
423
- var propsToPass = data.props = resolveProps(route, configProps);
424
- if (propsToPass) {
425
- // clone to prevent mutation
426
- propsToPass = data.props = extend({}, propsToPass);
427
- // pass non-declared props as attrs
428
- var attrs = data.attrs = data.attrs || {};
429
- for (var key in propsToPass) {
430
- if (!component.props || !(key in component.props)) {
431
- attrs[key] = propsToPass[key];
432
- delete propsToPass[key];
433
- }
434
- }
435
- }
436
- }
437
-
438
- function resolveProps (route, config) {
439
- switch (typeof config) {
440
- case 'undefined':
441
- return
442
- case 'object':
443
- return config
444
- case 'function':
445
- return config(route)
446
- case 'boolean':
447
- return config ? route.params : undefined
448
- default:
449
- {
450
- warn(
451
- false,
452
- "props in \"" + (route.path) + "\" is a " + (typeof config) + ", " +
453
- "expecting an object, function or boolean."
454
- );
455
- }
456
- }
457
- }
458
-
459
- /* */
460
-
461
- function resolvePath (
462
- relative,
463
- base,
464
- append
465
- ) {
466
- var firstChar = relative.charAt(0);
467
- if (firstChar === '/') {
468
- return relative
469
- }
470
-
471
- if (firstChar === '?' || firstChar === '#') {
472
- return base + relative
473
- }
474
-
475
- var stack = base.split('/');
476
-
477
- // remove trailing segment if:
478
- // - not appending
479
- // - appending to trailing slash (last segment is empty)
480
- if (!append || !stack[stack.length - 1]) {
481
- stack.pop();
482
- }
483
-
484
- // resolve relative path
485
- var segments = relative.replace(/^\//, '').split('/');
486
- for (var i = 0; i < segments.length; i++) {
487
- var segment = segments[i];
488
- if (segment === '..') {
489
- stack.pop();
490
- } else if (segment !== '.') {
491
- stack.push(segment);
492
- }
493
- }
494
-
495
- // ensure leading slash
496
- if (stack[0] !== '') {
497
- stack.unshift('');
498
- }
499
-
500
- return stack.join('/')
501
- }
502
-
503
- function parsePath (path) {
504
- var hash = '';
505
- var query = '';
506
-
507
- var hashIndex = path.indexOf('#');
508
- if (hashIndex >= 0) {
509
- hash = path.slice(hashIndex);
510
- path = path.slice(0, hashIndex);
511
- }
512
-
513
- var queryIndex = path.indexOf('?');
514
- if (queryIndex >= 0) {
515
- query = path.slice(queryIndex + 1);
516
- path = path.slice(0, queryIndex);
517
- }
518
-
519
- return {
520
- path: path,
521
- query: query,
522
- hash: hash
523
- }
524
- }
525
-
526
- function cleanPath (path) {
527
- return path.replace(/\/(?:\s*\/)+/g, '/')
528
- }
529
-
530
- var isarray = Array.isArray || function (arr) {
531
- return Object.prototype.toString.call(arr) == '[object Array]';
532
- };
533
-
534
- /**
535
- * Expose `pathToRegexp`.
536
- */
537
- var pathToRegexp_1 = pathToRegexp;
538
- var parse_1 = parse;
539
- var compile_1 = compile;
540
- var tokensToFunction_1 = tokensToFunction;
541
- var tokensToRegExp_1 = tokensToRegExp;
542
-
543
- /**
544
- * The main path matching regexp utility.
545
- *
546
- * @type {RegExp}
547
- */
548
- var PATH_REGEXP = new RegExp([
549
- // Match escaped characters that would otherwise appear in future matches.
550
- // This allows the user to escape special characters that won't transform.
551
- '(\\\\.)',
552
- // Match Express-style parameters and un-named parameters with a prefix
553
- // and optional suffixes. Matches appear as:
554
- //
555
- // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
556
- // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
557
- // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
558
- '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
559
- ].join('|'), 'g');
560
-
561
- /**
562
- * Parse a string for the raw tokens.
563
- *
564
- * @param {string} str
565
- * @param {Object=} options
566
- * @return {!Array}
567
- */
568
- function parse (str, options) {
569
- var tokens = [];
570
- var key = 0;
571
- var index = 0;
572
- var path = '';
573
- var defaultDelimiter = options && options.delimiter || '/';
574
- var res;
575
-
576
- while ((res = PATH_REGEXP.exec(str)) != null) {
577
- var m = res[0];
578
- var escaped = res[1];
579
- var offset = res.index;
580
- path += str.slice(index, offset);
581
- index = offset + m.length;
582
-
583
- // Ignore already escaped sequences.
584
- if (escaped) {
585
- path += escaped[1];
586
- continue
587
- }
588
-
589
- var next = str[index];
590
- var prefix = res[2];
591
- var name = res[3];
592
- var capture = res[4];
593
- var group = res[5];
594
- var modifier = res[6];
595
- var asterisk = res[7];
596
-
597
- // Push the current path onto the tokens.
598
- if (path) {
599
- tokens.push(path);
600
- path = '';
601
- }
602
-
603
- var partial = prefix != null && next != null && next !== prefix;
604
- var repeat = modifier === '+' || modifier === '*';
605
- var optional = modifier === '?' || modifier === '*';
606
- var delimiter = res[2] || defaultDelimiter;
607
- var pattern = capture || group;
608
-
609
- tokens.push({
610
- name: name || key++,
611
- prefix: prefix || '',
612
- delimiter: delimiter,
613
- optional: optional,
614
- repeat: repeat,
615
- partial: partial,
616
- asterisk: !!asterisk,
617
- pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
618
- });
619
- }
620
-
621
- // Match any characters still remaining.
622
- if (index < str.length) {
623
- path += str.substr(index);
624
- }
625
-
626
- // If the path exists, push it onto the end.
627
- if (path) {
628
- tokens.push(path);
629
- }
630
-
631
- return tokens
632
- }
633
-
634
- /**
635
- * Compile a string to a template function for the path.
636
- *
637
- * @param {string} str
638
- * @param {Object=} options
639
- * @return {!function(Object=, Object=)}
640
- */
641
- function compile (str, options) {
642
- return tokensToFunction(parse(str, options), options)
643
- }
644
-
645
- /**
646
- * Prettier encoding of URI path segments.
647
- *
648
- * @param {string}
649
- * @return {string}
650
- */
651
- function encodeURIComponentPretty (str) {
652
- return encodeURI(str).replace(/[\/?#]/g, function (c) {
653
- return '%' + c.charCodeAt(0).toString(16).toUpperCase()
654
- })
655
- }
656
-
657
- /**
658
- * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
659
- *
660
- * @param {string}
661
- * @return {string}
662
- */
663
- function encodeAsterisk (str) {
664
- return encodeURI(str).replace(/[?#]/g, function (c) {
665
- return '%' + c.charCodeAt(0).toString(16).toUpperCase()
666
- })
667
- }
668
-
669
- /**
670
- * Expose a method for transforming tokens into the path function.
671
- */
672
- function tokensToFunction (tokens, options) {
673
- // Compile all the tokens into regexps.
674
- var matches = new Array(tokens.length);
675
-
676
- // Compile all the patterns before compilation.
677
- for (var i = 0; i < tokens.length; i++) {
678
- if (typeof tokens[i] === 'object') {
679
- matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options));
680
- }
681
- }
682
-
683
- return function (obj, opts) {
684
- var path = '';
685
- var data = obj || {};
686
- var options = opts || {};
687
- var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
688
-
689
- for (var i = 0; i < tokens.length; i++) {
690
- var token = tokens[i];
691
-
692
- if (typeof token === 'string') {
693
- path += token;
694
-
695
- continue
696
- }
697
-
698
- var value = data[token.name];
699
- var segment;
700
-
701
- if (value == null) {
702
- if (token.optional) {
703
- // Prepend partial segment prefixes.
704
- if (token.partial) {
705
- path += token.prefix;
706
- }
707
-
708
- continue
709
- } else {
710
- throw new TypeError('Expected "' + token.name + '" to be defined')
711
- }
712
- }
713
-
714
- if (isarray(value)) {
715
- if (!token.repeat) {
716
- throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
717
- }
718
-
719
- if (value.length === 0) {
720
- if (token.optional) {
721
- continue
722
- } else {
723
- throw new TypeError('Expected "' + token.name + '" to not be empty')
724
- }
725
- }
726
-
727
- for (var j = 0; j < value.length; j++) {
728
- segment = encode(value[j]);
729
-
730
- if (!matches[i].test(segment)) {
731
- throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
732
- }
733
-
734
- path += (j === 0 ? token.prefix : token.delimiter) + segment;
735
- }
736
-
737
- continue
738
- }
739
-
740
- segment = token.asterisk ? encodeAsterisk(value) : encode(value);
741
-
742
- if (!matches[i].test(segment)) {
743
- throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
744
- }
745
-
746
- path += token.prefix + segment;
747
- }
748
-
749
- return path
750
- }
751
- }
752
-
753
- /**
754
- * Escape a regular expression string.
755
- *
756
- * @param {string} str
757
- * @return {string}
758
- */
759
- function escapeString (str) {
760
- return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
761
- }
762
-
763
- /**
764
- * Escape the capturing group by escaping special characters and meaning.
765
- *
766
- * @param {string} group
767
- * @return {string}
768
- */
769
- function escapeGroup (group) {
770
- return group.replace(/([=!:$\/()])/g, '\\$1')
771
- }
772
-
773
- /**
774
- * Attach the keys as a property of the regexp.
775
- *
776
- * @param {!RegExp} re
777
- * @param {Array} keys
778
- * @return {!RegExp}
779
- */
780
- function attachKeys (re, keys) {
781
- re.keys = keys;
782
- return re
783
- }
784
-
785
- /**
786
- * Get the flags for a regexp from the options.
787
- *
788
- * @param {Object} options
789
- * @return {string}
790
- */
791
- function flags (options) {
792
- return options && options.sensitive ? '' : 'i'
793
- }
794
-
795
- /**
796
- * Pull out keys from a regexp.
797
- *
798
- * @param {!RegExp} path
799
- * @param {!Array} keys
800
- * @return {!RegExp}
801
- */
802
- function regexpToRegexp (path, keys) {
803
- // Use a negative lookahead to match only capturing groups.
804
- var groups = path.source.match(/\((?!\?)/g);
805
-
806
- if (groups) {
807
- for (var i = 0; i < groups.length; i++) {
808
- keys.push({
809
- name: i,
810
- prefix: null,
811
- delimiter: null,
812
- optional: false,
813
- repeat: false,
814
- partial: false,
815
- asterisk: false,
816
- pattern: null
817
- });
818
- }
819
- }
820
-
821
- return attachKeys(path, keys)
822
- }
823
-
824
- /**
825
- * Transform an array into a regexp.
826
- *
827
- * @param {!Array} path
828
- * @param {Array} keys
829
- * @param {!Object} options
830
- * @return {!RegExp}
831
- */
832
- function arrayToRegexp (path, keys, options) {
833
- var parts = [];
834
-
835
- for (var i = 0; i < path.length; i++) {
836
- parts.push(pathToRegexp(path[i], keys, options).source);
837
- }
838
-
839
- var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
840
-
841
- return attachKeys(regexp, keys)
842
- }
843
-
844
- /**
845
- * Create a path regexp from string input.
846
- *
847
- * @param {string} path
848
- * @param {!Array} keys
849
- * @param {!Object} options
850
- * @return {!RegExp}
851
- */
852
- function stringToRegexp (path, keys, options) {
853
- return tokensToRegExp(parse(path, options), keys, options)
854
- }
855
-
856
- /**
857
- * Expose a function for taking tokens and returning a RegExp.
858
- *
859
- * @param {!Array} tokens
860
- * @param {(Array|Object)=} keys
861
- * @param {Object=} options
862
- * @return {!RegExp}
863
- */
864
- function tokensToRegExp (tokens, keys, options) {
865
- if (!isarray(keys)) {
866
- options = /** @type {!Object} */ (keys || options);
867
- keys = [];
868
- }
869
-
870
- options = options || {};
871
-
872
- var strict = options.strict;
873
- var end = options.end !== false;
874
- var route = '';
875
-
876
- // Iterate over the tokens and create our regexp string.
877
- for (var i = 0; i < tokens.length; i++) {
878
- var token = tokens[i];
879
-
880
- if (typeof token === 'string') {
881
- route += escapeString(token);
882
- } else {
883
- var prefix = escapeString(token.prefix);
884
- var capture = '(?:' + token.pattern + ')';
885
-
886
- keys.push(token);
887
-
888
- if (token.repeat) {
889
- capture += '(?:' + prefix + capture + ')*';
890
- }
891
-
892
- if (token.optional) {
893
- if (!token.partial) {
894
- capture = '(?:' + prefix + '(' + capture + '))?';
895
- } else {
896
- capture = prefix + '(' + capture + ')?';
897
- }
898
- } else {
899
- capture = prefix + '(' + capture + ')';
900
- }
901
-
902
- route += capture;
903
- }
904
- }
905
-
906
- var delimiter = escapeString(options.delimiter || '/');
907
- var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
908
-
909
- // In non-strict mode we allow a slash at the end of match. If the path to
910
- // match already ends with a slash, we remove it for consistency. The slash
911
- // is valid at the end of a path match, not in the middle. This is important
912
- // in non-ending mode, where "/test/" shouldn't match "/test//route".
913
- if (!strict) {
914
- route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
915
- }
916
-
917
- if (end) {
918
- route += '$';
919
- } else {
920
- // In non-ending mode, we need the capturing groups to match as much as
921
- // possible by using a positive lookahead to the end or next path segment.
922
- route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
923
- }
924
-
925
- return attachKeys(new RegExp('^' + route, flags(options)), keys)
926
- }
927
-
928
- /**
929
- * Normalize the given path string, returning a regular expression.
930
- *
931
- * An empty array can be passed in for the keys, which will hold the
932
- * placeholder key descriptions. For example, using `/user/:id`, `keys` will
933
- * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
934
- *
935
- * @param {(string|RegExp|Array)} path
936
- * @param {(Array|Object)=} keys
937
- * @param {Object=} options
938
- * @return {!RegExp}
939
- */
940
- function pathToRegexp (path, keys, options) {
941
- if (!isarray(keys)) {
942
- options = /** @type {!Object} */ (keys || options);
943
- keys = [];
944
- }
945
-
946
- options = options || {};
947
-
948
- if (path instanceof RegExp) {
949
- return regexpToRegexp(path, /** @type {!Array} */ (keys))
950
- }
951
-
952
- if (isarray(path)) {
953
- return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
954
- }
955
-
956
- return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
957
- }
958
- pathToRegexp_1.parse = parse_1;
959
- pathToRegexp_1.compile = compile_1;
960
- pathToRegexp_1.tokensToFunction = tokensToFunction_1;
961
- pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
962
-
963
- /* */
964
-
965
- // $flow-disable-line
966
- var regexpCompileCache = Object.create(null);
967
-
968
- function fillParams (
969
- path,
970
- params,
971
- routeMsg
972
- ) {
973
- params = params || {};
974
- try {
975
- var filler =
976
- regexpCompileCache[path] ||
977
- (regexpCompileCache[path] = pathToRegexp_1.compile(path));
978
-
979
- // Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }}
980
- // and fix #3106 so that you can work with location descriptor object having params.pathMatch equal to empty string
981
- if (typeof params.pathMatch === 'string') { params[0] = params.pathMatch; }
982
-
983
- return filler(params, { pretty: true })
984
- } catch (e) {
985
- {
986
- // Fix #3072 no warn if `pathMatch` is string
987
- warn(typeof params.pathMatch === 'string', ("missing param for " + routeMsg + ": " + (e.message)));
988
- }
989
- return ''
990
- } finally {
991
- // delete the 0 if it was added
992
- delete params[0];
993
- }
994
- }
995
-
996
- /* */
997
-
998
- function normalizeLocation (
999
- raw,
1000
- current,
1001
- append,
1002
- router
1003
- ) {
1004
- var next = typeof raw === 'string' ? { path: raw } : raw;
1005
- // named target
1006
- if (next._normalized) {
1007
- return next
1008
- } else if (next.name) {
1009
- next = extend({}, raw);
1010
- var params = next.params;
1011
- if (params && typeof params === 'object') {
1012
- next.params = extend({}, params);
1013
- }
1014
- return next
1015
- }
1016
-
1017
- // relative params
1018
- if (!next.path && next.params && current) {
1019
- next = extend({}, next);
1020
- next._normalized = true;
1021
- var params$1 = extend(extend({}, current.params), next.params);
1022
- if (current.name) {
1023
- next.name = current.name;
1024
- next.params = params$1;
1025
- } else if (current.matched.length) {
1026
- var rawPath = current.matched[current.matched.length - 1].path;
1027
- next.path = fillParams(rawPath, params$1, ("path " + (current.path)));
1028
- } else {
1029
- warn(false, "relative params navigation requires a current route.");
1030
- }
1031
- return next
1032
- }
1033
-
1034
- var parsedPath = parsePath(next.path || '');
1035
- var basePath = (current && current.path) || '/';
1036
- var path = parsedPath.path
1037
- ? resolvePath(parsedPath.path, basePath, append || next.append)
1038
- : basePath;
1039
-
1040
- var query = resolveQuery(
1041
- parsedPath.query,
1042
- next.query,
1043
- router && router.options.parseQuery
1044
- );
1045
-
1046
- var hash = next.hash || parsedPath.hash;
1047
- if (hash && hash.charAt(0) !== '#') {
1048
- hash = "#" + hash;
1049
- }
1050
-
1051
- return {
1052
- _normalized: true,
1053
- path: path,
1054
- query: query,
1055
- hash: hash
1056
- }
1057
- }
1058
-
1059
- /* */
1060
-
1061
- // work around weird flow bug
1062
- var toTypes = [String, Object];
1063
- var eventTypes = [String, Array];
1064
-
1065
- var noop = function () {};
1066
-
1067
- var warnedCustomSlot;
1068
- var warnedTagProp;
1069
- var warnedEventProp;
1070
-
1071
- var Link = {
1072
- name: 'RouterLink',
1073
- props: {
1074
- to: {
1075
- type: toTypes,
1076
- required: true
1077
- },
1078
- tag: {
1079
- type: String,
1080
- default: 'a'
1081
- },
1082
- custom: Boolean,
1083
- exact: Boolean,
1084
- exactPath: Boolean,
1085
- append: Boolean,
1086
- replace: Boolean,
1087
- activeClass: String,
1088
- exactActiveClass: String,
1089
- ariaCurrentValue: {
1090
- type: String,
1091
- default: 'page'
1092
- },
1093
- event: {
1094
- type: eventTypes,
1095
- default: 'click'
1096
- }
1097
- },
1098
- render: function render (h) {
1099
- var this$1 = this;
1100
-
1101
- var router = this.$router;
1102
- var current = this.$route;
1103
- var ref = router.resolve(
1104
- this.to,
1105
- current,
1106
- this.append
1107
- );
1108
- var location = ref.location;
1109
- var route = ref.route;
1110
- var href = ref.href;
1111
-
1112
- var classes = {};
1113
- var globalActiveClass = router.options.linkActiveClass;
1114
- var globalExactActiveClass = router.options.linkExactActiveClass;
1115
- // Support global empty active class
1116
- var activeClassFallback =
1117
- globalActiveClass == null ? 'router-link-active' : globalActiveClass;
1118
- var exactActiveClassFallback =
1119
- globalExactActiveClass == null
1120
- ? 'router-link-exact-active'
1121
- : globalExactActiveClass;
1122
- var activeClass =
1123
- this.activeClass == null ? activeClassFallback : this.activeClass;
1124
- var exactActiveClass =
1125
- this.exactActiveClass == null
1126
- ? exactActiveClassFallback
1127
- : this.exactActiveClass;
1128
-
1129
- var compareTarget = route.redirectedFrom
1130
- ? createRoute(null, normalizeLocation(route.redirectedFrom), null, router)
1131
- : route;
1132
-
1133
- classes[exactActiveClass] = isSameRoute(current, compareTarget, this.exactPath);
1134
- classes[activeClass] = this.exact || this.exactPath
1135
- ? classes[exactActiveClass]
1136
- : isIncludedRoute(current, compareTarget);
1137
-
1138
- var ariaCurrentValue = classes[exactActiveClass] ? this.ariaCurrentValue : null;
1139
-
1140
- var handler = function (e) {
1141
- if (guardEvent(e)) {
1142
- if (this$1.replace) {
1143
- router.replace(location, noop);
1144
- } else {
1145
- router.push(location, noop);
1146
- }
1147
- }
1148
- };
1149
-
1150
- var on = { click: guardEvent };
1151
- if (Array.isArray(this.event)) {
1152
- this.event.forEach(function (e) {
1153
- on[e] = handler;
1154
- });
1155
- } else {
1156
- on[this.event] = handler;
1157
- }
1158
-
1159
- var data = { class: classes };
1160
-
1161
- var scopedSlot =
1162
- !this.$scopedSlots.$hasNormal &&
1163
- this.$scopedSlots.default &&
1164
- this.$scopedSlots.default({
1165
- href: href,
1166
- route: route,
1167
- navigate: handler,
1168
- isActive: classes[activeClass],
1169
- isExactActive: classes[exactActiveClass]
1170
- });
1171
-
1172
- if (scopedSlot) {
1173
- if (!this.custom) {
1174
- !warnedCustomSlot && warn(false, 'In Kdu Router 4, the k-slot API will by default wrap its content with an <a> element. Use the custom prop to remove this warning:\n<router-link k-slot="{ navigate, href }" custom></router-link>\n');
1175
- warnedCustomSlot = true;
1176
- }
1177
- if (scopedSlot.length === 1) {
1178
- return scopedSlot[0]
1179
- } else if (scopedSlot.length > 1 || !scopedSlot.length) {
1180
- {
1181
- warn(
1182
- false,
1183
- ("<router-link> with to=\"" + (this.to) + "\" is trying to use a scoped slot but it didn't provide exactly one child. Wrapping the content with a span element.")
1184
- );
1185
- }
1186
- return scopedSlot.length === 0 ? h() : h('span', {}, scopedSlot)
1187
- }
1188
- }
1189
-
1190
- {
1191
- if ('tag' in this.$options.propsData && !warnedTagProp) {
1192
- warn(
1193
- false,
1194
- "<router-link>'s tag prop is deprecated and has been removed in Kdu Router 4. Use the k-slot API to remove this warning: https://kdujs-router.web.app/guide/migration/#removal-of-event-and-tag-props-in-router-link."
1195
- );
1196
- warnedTagProp = true;
1197
- }
1198
- if ('event' in this.$options.propsData && !warnedEventProp) {
1199
- warn(
1200
- false,
1201
- "<router-link>'s event prop is deprecated and has been removed in Kdu Router 4. Use the k-slot API to remove this warning: https://kdujs-router.web.app/guide/migration/#removal-of-event-and-tag-props-in-router-link."
1202
- );
1203
- warnedEventProp = true;
1204
- }
1205
- }
1206
-
1207
- if (this.tag === 'a') {
1208
- data.on = on;
1209
- data.attrs = { href: href, 'aria-current': ariaCurrentValue };
1210
- } else {
1211
- // find the first <a> child and apply listener and href
1212
- var a = findAnchor(this.$slots.default);
1213
- if (a) {
1214
- // in case the <a> is a static node
1215
- a.isStatic = false;
1216
- var aData = (a.data = extend({}, a.data));
1217
- aData.on = aData.on || {};
1218
- // transform existing events in both objects into arrays so we can push later
1219
- for (var event in aData.on) {
1220
- var handler$1 = aData.on[event];
1221
- if (event in on) {
1222
- aData.on[event] = Array.isArray(handler$1) ? handler$1 : [handler$1];
1223
- }
1224
- }
1225
- // append new listeners for router-link
1226
- for (var event$1 in on) {
1227
- if (event$1 in aData.on) {
1228
- // on[event] is always a function
1229
- aData.on[event$1].push(on[event$1]);
1230
- } else {
1231
- aData.on[event$1] = handler;
1232
- }
1233
- }
1234
-
1235
- var aAttrs = (a.data.attrs = extend({}, a.data.attrs));
1236
- aAttrs.href = href;
1237
- aAttrs['aria-current'] = ariaCurrentValue;
1238
- } else {
1239
- // doesn't have <a> child, apply listener to self
1240
- data.on = on;
1241
- }
1242
- }
1243
-
1244
- return h(this.tag, data, this.$slots.default)
1245
- }
1246
- };
1247
-
1248
- function guardEvent (e) {
1249
- // don't redirect with control keys
1250
- if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return }
1251
- // don't redirect when preventDefault called
1252
- if (e.defaultPrevented) { return }
1253
- // don't redirect on right click
1254
- if (e.button !== undefined && e.button !== 0) { return }
1255
- // don't redirect if `target="_blank"`
1256
- if (e.currentTarget && e.currentTarget.getAttribute) {
1257
- var target = e.currentTarget.getAttribute('target');
1258
- if (/\b_blank\b/i.test(target)) { return }
1259
- }
1260
- // this may be a Weex event which doesn't have this method
1261
- if (e.preventDefault) {
1262
- e.preventDefault();
1263
- }
1264
- return true
1265
- }
1266
-
1267
- function findAnchor (children) {
1268
- if (children) {
1269
- var child;
1270
- for (var i = 0; i < children.length; i++) {
1271
- child = children[i];
1272
- if (child.tag === 'a') {
1273
- return child
1274
- }
1275
- if (child.children && (child = findAnchor(child.children))) {
1276
- return child
1277
- }
1278
- }
1279
- }
1280
- }
1281
-
1282
- var _Kdu;
1283
-
1284
- function install (Kdu) {
1285
- if (install.installed && _Kdu === Kdu) { return }
1286
- install.installed = true;
1287
-
1288
- _Kdu = Kdu;
1289
-
1290
- var isDef = function (v) { return v !== undefined; };
1291
-
1292
- var registerInstance = function (vm, callVal) {
1293
- var i = vm.$options._parentKnode;
1294
- if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
1295
- i(vm, callVal);
1296
- }
1297
- };
1298
-
1299
- Kdu.mixin({
1300
- beforeCreate: function beforeCreate () {
1301
- if (isDef(this.$options.router)) {
1302
- this._routerRoot = this;
1303
- this._router = this.$options.router;
1304
- this._router.init(this);
1305
- Kdu.util.defineReactive(this, '_route', this._router.history.current);
1306
- } else {
1307
- this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
1308
- }
1309
- registerInstance(this, this);
1310
- },
1311
- destroyed: function destroyed () {
1312
- registerInstance(this);
1313
- }
1314
- });
1315
-
1316
- Object.defineProperty(Kdu.prototype, '$router', {
1317
- get: function get () { return this._routerRoot._router }
1318
- });
1319
-
1320
- Object.defineProperty(Kdu.prototype, '$route', {
1321
- get: function get () { return this._routerRoot._route }
1322
- });
1323
-
1324
- Kdu.component('RouterView', View);
1325
- Kdu.component('RouterLink', Link);
1326
-
1327
- var strats = Kdu.config.optionMergeStrategies;
1328
- // use the same hook merging strategy for route hooks
1329
- strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
1330
- }
1331
-
1332
- /* */
1333
-
1334
- var inBrowser = typeof window !== 'undefined';
1335
-
1336
- /* */
1337
-
1338
- function createRouteMap (
1339
- routes,
1340
- oldPathList,
1341
- oldPathMap,
1342
- oldNameMap,
1343
- parentRoute
1344
- ) {
1345
- // the path list is used to control path matching priority
1346
- var pathList = oldPathList || [];
1347
- // $flow-disable-line
1348
- var pathMap = oldPathMap || Object.create(null);
1349
- // $flow-disable-line
1350
- var nameMap = oldNameMap || Object.create(null);
1351
-
1352
- routes.forEach(function (route) {
1353
- addRouteRecord(pathList, pathMap, nameMap, route, parentRoute);
1354
- });
1355
-
1356
- // ensure wildcard routes are always at the end
1357
- for (var i = 0, l = pathList.length; i < l; i++) {
1358
- if (pathList[i] === '*') {
1359
- pathList.push(pathList.splice(i, 1)[0]);
1360
- l--;
1361
- i--;
1362
- }
1363
- }
1364
-
1365
- {
1366
- // warn if routes do not include leading slashes
1367
- var found = pathList
1368
- // check for missing leading slash
1369
- .filter(function (path) { return path && path.charAt(0) !== '*' && path.charAt(0) !== '/'; });
1370
-
1371
- if (found.length > 0) {
1372
- var pathNames = found.map(function (path) { return ("- " + path); }).join('\n');
1373
- warn(false, ("Non-nested routes must include a leading slash character. Fix the following routes: \n" + pathNames));
1374
- }
1375
- }
1376
-
1377
- return {
1378
- pathList: pathList,
1379
- pathMap: pathMap,
1380
- nameMap: nameMap
1381
- }
1382
- }
1383
-
1384
- function addRouteRecord (
1385
- pathList,
1386
- pathMap,
1387
- nameMap,
1388
- route,
1389
- parent,
1390
- matchAs
1391
- ) {
1392
- var path = route.path;
1393
- var name = route.name;
1394
- {
1395
- assert(path != null, "\"path\" is required in a route configuration.");
1396
- assert(
1397
- typeof route.component !== 'string',
1398
- "route config \"component\" for path: " + (String(
1399
- path || name
1400
- )) + " cannot be a " + "string id. Use an actual component instead."
1401
- );
1402
-
1403
- warn(
1404
- // eslint-disable-next-line no-control-regex
1405
- !/[^\u0000-\u007F]+/.test(path),
1406
- "Route with path \"" + path + "\" contains unencoded characters, make sure " +
1407
- "your path is correctly encoded before passing it to the router. Use " +
1408
- "encodeURI to encode static segments of your path."
1409
- );
1410
- }
1411
-
1412
- var pathToRegexpOptions =
1413
- route.pathToRegexpOptions || {};
1414
- var normalizedPath = normalizePath(path, parent, pathToRegexpOptions.strict);
1415
-
1416
- if (typeof route.caseSensitive === 'boolean') {
1417
- pathToRegexpOptions.sensitive = route.caseSensitive;
1418
- }
1419
-
1420
- var record = {
1421
- path: normalizedPath,
1422
- regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
1423
- components: route.components || { default: route.component },
1424
- alias: route.alias
1425
- ? typeof route.alias === 'string'
1426
- ? [route.alias]
1427
- : route.alias
1428
- : [],
1429
- instances: {},
1430
- enteredCbs: {},
1431
- name: name,
1432
- parent: parent,
1433
- matchAs: matchAs,
1434
- redirect: route.redirect,
1435
- beforeEnter: route.beforeEnter,
1436
- meta: route.meta || {},
1437
- props:
1438
- route.props == null
1439
- ? {}
1440
- : route.components
1441
- ? route.props
1442
- : { default: route.props }
1443
- };
1444
-
1445
- if (route.children) {
1446
- // Warn if route is named, does not redirect and has a default child route.
1447
- // If users navigate to this route by name, the default child will
1448
- // not be rendered (GH Issue #629)
1449
- {
1450
- if (
1451
- route.name &&
1452
- !route.redirect &&
1453
- route.children.some(function (child) { return /^\/?$/.test(child.path); })
1454
- ) {
1455
- warn(
1456
- false,
1457
- "Named Route '" + (route.name) + "' has a default child route. " +
1458
- "When navigating to this named route (:to=\"{name: '" + (route.name) + "'}\"), " +
1459
- "the default child route will not be rendered. Remove the name from " +
1460
- "this route and use the name of the default child route for named " +
1461
- "links instead."
1462
- );
1463
- }
1464
- }
1465
- route.children.forEach(function (child) {
1466
- var childMatchAs = matchAs
1467
- ? cleanPath((matchAs + "/" + (child.path)))
1468
- : undefined;
1469
- addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
1470
- });
1471
- }
1472
-
1473
- if (!pathMap[record.path]) {
1474
- pathList.push(record.path);
1475
- pathMap[record.path] = record;
1476
- }
1477
-
1478
- if (route.alias !== undefined) {
1479
- var aliases = Array.isArray(route.alias) ? route.alias : [route.alias];
1480
- for (var i = 0; i < aliases.length; ++i) {
1481
- var alias = aliases[i];
1482
- if (alias === path) {
1483
- warn(
1484
- false,
1485
- ("Found an alias with the same value as the path: \"" + path + "\". You have to remove that alias. It will be ignored in development.")
1486
- );
1487
- // skip in dev to make it work
1488
- continue
1489
- }
1490
-
1491
- var aliasRoute = {
1492
- path: alias,
1493
- children: route.children
1494
- };
1495
- addRouteRecord(
1496
- pathList,
1497
- pathMap,
1498
- nameMap,
1499
- aliasRoute,
1500
- parent,
1501
- record.path || '/' // matchAs
1502
- );
1503
- }
1504
- }
1505
-
1506
- if (name) {
1507
- if (!nameMap[name]) {
1508
- nameMap[name] = record;
1509
- } else if (!matchAs) {
1510
- warn(
1511
- false,
1512
- "Duplicate named routes definition: " +
1513
- "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
1514
- );
1515
- }
1516
- }
1517
- }
1518
-
1519
- function compileRouteRegex (
1520
- path,
1521
- pathToRegexpOptions
1522
- ) {
1523
- var regex = pathToRegexp_1(path, [], pathToRegexpOptions);
1524
- {
1525
- var keys = Object.create(null);
1526
- regex.keys.forEach(function (key) {
1527
- warn(
1528
- !keys[key.name],
1529
- ("Duplicate param keys in route with path: \"" + path + "\"")
1530
- );
1531
- keys[key.name] = true;
1532
- });
1533
- }
1534
- return regex
1535
- }
1536
-
1537
- function normalizePath (
1538
- path,
1539
- parent,
1540
- strict
1541
- ) {
1542
- if (!strict) { path = path.replace(/\/$/, ''); }
1543
- if (path[0] === '/') { return path }
1544
- if (parent == null) { return path }
1545
- return cleanPath(((parent.path) + "/" + path))
1546
- }
1547
-
1548
- /* */
1549
-
1550
-
1551
-
1552
- function createMatcher (
1553
- routes,
1554
- router
1555
- ) {
1556
- var ref = createRouteMap(routes);
1557
- var pathList = ref.pathList;
1558
- var pathMap = ref.pathMap;
1559
- var nameMap = ref.nameMap;
1560
-
1561
- function addRoutes (routes) {
1562
- createRouteMap(routes, pathList, pathMap, nameMap);
1563
- }
1564
-
1565
- function addRoute (parentOrRoute, route) {
1566
- var parent = (typeof parentOrRoute !== 'object') ? nameMap[parentOrRoute] : undefined;
1567
- // $flow-disable-line
1568
- createRouteMap([route || parentOrRoute], pathList, pathMap, nameMap, parent);
1569
-
1570
- // add aliases of parent
1571
- if (parent && parent.alias.length) {
1572
- createRouteMap(
1573
- // $flow-disable-line route is defined if parent is
1574
- parent.alias.map(function (alias) { return ({ path: alias, children: [route] }); }),
1575
- pathList,
1576
- pathMap,
1577
- nameMap,
1578
- parent
1579
- );
1580
- }
1581
- }
1582
-
1583
- function getRoutes () {
1584
- return pathList.map(function (path) { return pathMap[path]; })
1585
- }
1586
-
1587
- function match (
1588
- raw,
1589
- currentRoute,
1590
- redirectedFrom
1591
- ) {
1592
- var location = normalizeLocation(raw, currentRoute, false, router);
1593
- var name = location.name;
1594
-
1595
- if (name) {
1596
- var record = nameMap[name];
1597
- {
1598
- warn(record, ("Route with name '" + name + "' does not exist"));
1599
- }
1600
- if (!record) { return _createRoute(null, location) }
1601
- var paramNames = record.regex.keys
1602
- .filter(function (key) { return !key.optional; })
1603
- .map(function (key) { return key.name; });
1604
-
1605
- if (typeof location.params !== 'object') {
1606
- location.params = {};
1607
- }
1608
-
1609
- if (currentRoute && typeof currentRoute.params === 'object') {
1610
- for (var key in currentRoute.params) {
1611
- if (!(key in location.params) && paramNames.indexOf(key) > -1) {
1612
- location.params[key] = currentRoute.params[key];
1613
- }
1614
- }
1615
- }
1616
-
1617
- location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
1618
- return _createRoute(record, location, redirectedFrom)
1619
- } else if (location.path) {
1620
- location.params = {};
1621
- for (var i = 0; i < pathList.length; i++) {
1622
- var path = pathList[i];
1623
- var record$1 = pathMap[path];
1624
- if (matchRoute(record$1.regex, location.path, location.params)) {
1625
- return _createRoute(record$1, location, redirectedFrom)
1626
- }
1627
- }
1628
- }
1629
- // no match
1630
- return _createRoute(null, location)
1631
- }
1632
-
1633
- function redirect (
1634
- record,
1635
- location
1636
- ) {
1637
- var originalRedirect = record.redirect;
1638
- var redirect = typeof originalRedirect === 'function'
1639
- ? originalRedirect(createRoute(record, location, null, router))
1640
- : originalRedirect;
1641
-
1642
- if (typeof redirect === 'string') {
1643
- redirect = { path: redirect };
1644
- }
1645
-
1646
- if (!redirect || typeof redirect !== 'object') {
1647
- {
1648
- warn(
1649
- false, ("invalid redirect option: " + (JSON.stringify(redirect)))
1650
- );
1651
- }
1652
- return _createRoute(null, location)
1653
- }
1654
-
1655
- var re = redirect;
1656
- var name = re.name;
1657
- var path = re.path;
1658
- var query = location.query;
1659
- var hash = location.hash;
1660
- var params = location.params;
1661
- query = re.hasOwnProperty('query') ? re.query : query;
1662
- hash = re.hasOwnProperty('hash') ? re.hash : hash;
1663
- params = re.hasOwnProperty('params') ? re.params : params;
1664
-
1665
- if (name) {
1666
- // resolved named direct
1667
- var targetRecord = nameMap[name];
1668
- {
1669
- assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
1670
- }
1671
- return match({
1672
- _normalized: true,
1673
- name: name,
1674
- query: query,
1675
- hash: hash,
1676
- params: params
1677
- }, undefined, location)
1678
- } else if (path) {
1679
- // 1. resolve relative redirect
1680
- var rawPath = resolveRecordPath(path, record);
1681
- // 2. resolve params
1682
- var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\""));
1683
- // 3. rematch with existing query and hash
1684
- return match({
1685
- _normalized: true,
1686
- path: resolvedPath,
1687
- query: query,
1688
- hash: hash
1689
- }, undefined, location)
1690
- } else {
1691
- {
1692
- warn(false, ("invalid redirect option: " + (JSON.stringify(redirect))));
1693
- }
1694
- return _createRoute(null, location)
1695
- }
1696
- }
1697
-
1698
- function alias (
1699
- record,
1700
- location,
1701
- matchAs
1702
- ) {
1703
- var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
1704
- var aliasedMatch = match({
1705
- _normalized: true,
1706
- path: aliasedPath
1707
- });
1708
- if (aliasedMatch) {
1709
- var matched = aliasedMatch.matched;
1710
- var aliasedRecord = matched[matched.length - 1];
1711
- location.params = aliasedMatch.params;
1712
- return _createRoute(aliasedRecord, location)
1713
- }
1714
- return _createRoute(null, location)
1715
- }
1716
-
1717
- function _createRoute (
1718
- record,
1719
- location,
1720
- redirectedFrom
1721
- ) {
1722
- if (record && record.redirect) {
1723
- return redirect(record, redirectedFrom || location)
1724
- }
1725
- if (record && record.matchAs) {
1726
- return alias(record, location, record.matchAs)
1727
- }
1728
- return createRoute(record, location, redirectedFrom, router)
1729
- }
1730
-
1731
- return {
1732
- match: match,
1733
- addRoute: addRoute,
1734
- getRoutes: getRoutes,
1735
- addRoutes: addRoutes
1736
- }
1737
- }
1738
-
1739
- function matchRoute (
1740
- regex,
1741
- path,
1742
- params
1743
- ) {
1744
- var m = path.match(regex);
1745
-
1746
- if (!m) {
1747
- return false
1748
- } else if (!params) {
1749
- return true
1750
- }
1751
-
1752
- for (var i = 1, len = m.length; i < len; ++i) {
1753
- var key = regex.keys[i - 1];
1754
- if (key) {
1755
- // Fix #1994: using * with props: true generates a param named 0
1756
- params[key.name || 'pathMatch'] = typeof m[i] === 'string' ? decode(m[i]) : m[i];
1757
- }
1758
- }
1759
-
1760
- return true
1761
- }
1762
-
1763
- function resolveRecordPath (path, record) {
1764
- return resolvePath(path, record.parent ? record.parent.path : '/', true)
1765
- }
1766
-
1767
- /* */
1768
-
1769
- // use User Timing api (if present) for more accurate key precision
1770
- var Time =
1771
- inBrowser && window.performance && window.performance.now
1772
- ? window.performance
1773
- : Date;
1774
-
1775
- function genStateKey () {
1776
- return Time.now().toFixed(3)
1777
- }
1778
-
1779
- var _key = genStateKey();
1780
-
1781
- function getStateKey () {
1782
- return _key
1783
- }
1784
-
1785
- function setStateKey (key) {
1786
- return (_key = key)
1787
- }
1788
-
1789
- /* */
1790
-
1791
- var positionStore = Object.create(null);
1792
-
1793
- function setupScroll () {
1794
- // Prevent browser scroll behavior on History popstate
1795
- if ('scrollRestoration' in window.history) {
1796
- window.history.scrollRestoration = 'manual';
1797
- }
1798
- // Fix for #1585 for Firefox
1799
- // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
1800
- // Fix for #2774 Support for apps loaded from Windows file shares not mapped to network drives: replaced location.origin with
1801
- // window.location.protocol + '//' + window.location.host
1802
- // location.host contains the port and location.hostname doesn't
1803
- var protocolAndPath = window.location.protocol + '//' + window.location.host;
1804
- var absolutePath = window.location.href.replace(protocolAndPath, '');
1805
- // preserve existing history state as it could be overriden by the user
1806
- var stateCopy = extend({}, window.history.state);
1807
- stateCopy.key = getStateKey();
1808
- window.history.replaceState(stateCopy, '', absolutePath);
1809
- window.addEventListener('popstate', handlePopState);
1810
- return function () {
1811
- window.removeEventListener('popstate', handlePopState);
1812
- }
1813
- }
1814
-
1815
- function handleScroll (
1816
- router,
1817
- to,
1818
- from,
1819
- isPop
1820
- ) {
1821
- if (!router.app) {
1822
- return
1823
- }
1824
-
1825
- var behavior = router.options.scrollBehavior;
1826
- if (!behavior) {
1827
- return
1828
- }
1829
-
1830
- {
1831
- assert(typeof behavior === 'function', "scrollBehavior must be a function");
1832
- }
1833
-
1834
- // wait until re-render finishes before scrolling
1835
- router.app.$nextTick(function () {
1836
- var position = getScrollPosition();
1837
- var shouldScroll = behavior.call(
1838
- router,
1839
- to,
1840
- from,
1841
- isPop ? position : null
1842
- );
1843
-
1844
- if (!shouldScroll) {
1845
- return
1846
- }
1847
-
1848
- if (typeof shouldScroll.then === 'function') {
1849
- shouldScroll
1850
- .then(function (shouldScroll) {
1851
- scrollToPosition((shouldScroll), position);
1852
- })
1853
- .catch(function (err) {
1854
- {
1855
- assert(false, err.toString());
1856
- }
1857
- });
1858
- } else {
1859
- scrollToPosition(shouldScroll, position);
1860
- }
1861
- });
1862
- }
1863
-
1864
- function saveScrollPosition () {
1865
- var key = getStateKey();
1866
- if (key) {
1867
- positionStore[key] = {
1868
- x: window.pageXOffset,
1869
- y: window.pageYOffset
1870
- };
1871
- }
1872
- }
1873
-
1874
- function handlePopState (e) {
1875
- saveScrollPosition();
1876
- if (e.state && e.state.key) {
1877
- setStateKey(e.state.key);
1878
- }
1879
- }
1880
-
1881
- function getScrollPosition () {
1882
- var key = getStateKey();
1883
- if (key) {
1884
- return positionStore[key]
1885
- }
1886
- }
1887
-
1888
- function getElementPosition (el, offset) {
1889
- var docEl = document.documentElement;
1890
- var docRect = docEl.getBoundingClientRect();
1891
- var elRect = el.getBoundingClientRect();
1892
- return {
1893
- x: elRect.left - docRect.left - offset.x,
1894
- y: elRect.top - docRect.top - offset.y
1895
- }
1896
- }
1897
-
1898
- function isValidPosition (obj) {
1899
- return isNumber(obj.x) || isNumber(obj.y)
1900
- }
1901
-
1902
- function normalizePosition (obj) {
1903
- return {
1904
- x: isNumber(obj.x) ? obj.x : window.pageXOffset,
1905
- y: isNumber(obj.y) ? obj.y : window.pageYOffset
1906
- }
1907
- }
1908
-
1909
- function normalizeOffset (obj) {
1910
- return {
1911
- x: isNumber(obj.x) ? obj.x : 0,
1912
- y: isNumber(obj.y) ? obj.y : 0
1913
- }
1914
- }
1915
-
1916
- function isNumber (v) {
1917
- return typeof v === 'number'
1918
- }
1919
-
1920
- var hashStartsWithNumberRE = /^#\d/;
1921
-
1922
- function scrollToPosition (shouldScroll, position) {
1923
- var isObject = typeof shouldScroll === 'object';
1924
- if (isObject && typeof shouldScroll.selector === 'string') {
1925
- // getElementById would still fail if the selector contains a more complicated query like #main[data-attr]
1926
- // but at the same time, it doesn't make much sense to select an element with an id and an extra selector
1927
- var el = hashStartsWithNumberRE.test(shouldScroll.selector) // $flow-disable-line
1928
- ? document.getElementById(shouldScroll.selector.slice(1)) // $flow-disable-line
1929
- : document.querySelector(shouldScroll.selector);
1930
-
1931
- if (el) {
1932
- var offset =
1933
- shouldScroll.offset && typeof shouldScroll.offset === 'object'
1934
- ? shouldScroll.offset
1935
- : {};
1936
- offset = normalizeOffset(offset);
1937
- position = getElementPosition(el, offset);
1938
- } else if (isValidPosition(shouldScroll)) {
1939
- position = normalizePosition(shouldScroll);
1940
- }
1941
- } else if (isObject && isValidPosition(shouldScroll)) {
1942
- position = normalizePosition(shouldScroll);
1943
- }
1944
-
1945
- if (position) {
1946
- // $flow-disable-line
1947
- if ('scrollBehavior' in document.documentElement.style) {
1948
- window.scrollTo({
1949
- left: position.x,
1950
- top: position.y,
1951
- // $flow-disable-line
1952
- behavior: shouldScroll.behavior
1953
- });
1954
- } else {
1955
- window.scrollTo(position.x, position.y);
1956
- }
1957
- }
1958
- }
1959
-
1960
- /* */
1961
-
1962
- var supportsPushState =
1963
- inBrowser &&
1964
- (function () {
1965
- var ua = window.navigator.userAgent;
1966
-
1967
- if (
1968
- (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
1969
- ua.indexOf('Mobile Safari') !== -1 &&
1970
- ua.indexOf('Chrome') === -1 &&
1971
- ua.indexOf('Windows Phone') === -1
1972
- ) {
1973
- return false
1974
- }
1975
-
1976
- return window.history && typeof window.history.pushState === 'function'
1977
- })();
1978
-
1979
- function pushState (url, replace) {
1980
- saveScrollPosition();
1981
- // try...catch the pushState call to get around Safari
1982
- // DOM Exception 18 where it limits to 100 pushState calls
1983
- var history = window.history;
1984
- try {
1985
- if (replace) {
1986
- // preserve existing history state as it could be overriden by the user
1987
- var stateCopy = extend({}, history.state);
1988
- stateCopy.key = getStateKey();
1989
- history.replaceState(stateCopy, '', url);
1990
- } else {
1991
- history.pushState({ key: setStateKey(genStateKey()) }, '', url);
1992
- }
1993
- } catch (e) {
1994
- window.location[replace ? 'replace' : 'assign'](url);
1995
- }
1996
- }
1997
-
1998
- function replaceState (url) {
1999
- pushState(url, true);
2000
- }
2001
-
2002
- /* */
2003
-
2004
- function runQueue (queue, fn, cb) {
2005
- var step = function (index) {
2006
- if (index >= queue.length) {
2007
- cb();
2008
- } else {
2009
- if (queue[index]) {
2010
- fn(queue[index], function () {
2011
- step(index + 1);
2012
- });
2013
- } else {
2014
- step(index + 1);
2015
- }
2016
- }
2017
- };
2018
- step(0);
2019
- }
2020
-
2021
- // When changing thing, also edit router.d.ts
2022
- var NavigationFailureType = {
2023
- redirected: 2,
2024
- aborted: 4,
2025
- cancelled: 8,
2026
- duplicated: 16
2027
- };
2028
-
2029
- function createNavigationRedirectedError (from, to) {
2030
- return createRouterError(
2031
- from,
2032
- to,
2033
- NavigationFailureType.redirected,
2034
- ("Redirected when going from \"" + (from.fullPath) + "\" to \"" + (stringifyRoute(
2035
- to
2036
- )) + "\" via a navigation guard.")
2037
- )
2038
- }
2039
-
2040
- function createNavigationDuplicatedError (from, to) {
2041
- var error = createRouterError(
2042
- from,
2043
- to,
2044
- NavigationFailureType.duplicated,
2045
- ("Avoided redundant navigation to current location: \"" + (from.fullPath) + "\".")
2046
- );
2047
- // backwards compatible with the first introduction of Errors
2048
- error.name = 'NavigationDuplicated';
2049
- return error
2050
- }
2051
-
2052
- function createNavigationCancelledError (from, to) {
2053
- return createRouterError(
2054
- from,
2055
- to,
2056
- NavigationFailureType.cancelled,
2057
- ("Navigation cancelled from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" with a new navigation.")
2058
- )
2059
- }
2060
-
2061
- function createNavigationAbortedError (from, to) {
2062
- return createRouterError(
2063
- from,
2064
- to,
2065
- NavigationFailureType.aborted,
2066
- ("Navigation aborted from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" via a navigation guard.")
2067
- )
2068
- }
2069
-
2070
- function createRouterError (from, to, type, message) {
2071
- var error = new Error(message);
2072
- error._isRouter = true;
2073
- error.from = from;
2074
- error.to = to;
2075
- error.type = type;
2076
-
2077
- return error
2078
- }
2079
-
2080
- var propertiesToLog = ['params', 'query', 'hash'];
2081
-
2082
- function stringifyRoute (to) {
2083
- if (typeof to === 'string') { return to }
2084
- if ('path' in to) { return to.path }
2085
- var location = {};
2086
- propertiesToLog.forEach(function (key) {
2087
- if (key in to) { location[key] = to[key]; }
2088
- });
2089
- return JSON.stringify(location, null, 2)
2090
- }
2091
-
2092
- function isError (err) {
2093
- return Object.prototype.toString.call(err).indexOf('Error') > -1
2094
- }
2095
-
2096
- function isNavigationFailure (err, errorType) {
2097
- return (
2098
- isError(err) &&
2099
- err._isRouter &&
2100
- (errorType == null || err.type === errorType)
2101
- )
2102
- }
2103
-
2104
- /* */
2105
-
2106
- function resolveAsyncComponents (matched) {
2107
- return function (to, from, next) {
2108
- var hasAsync = false;
2109
- var pending = 0;
2110
- var error = null;
2111
-
2112
- flatMapComponents(matched, function (def, _, match, key) {
2113
- // if it's a function and doesn't have cid attached,
2114
- // assume it's an async component resolve function.
2115
- // we are not using Kdu's default async resolving mechanism because
2116
- // we want to halt the navigation until the incoming component has been
2117
- // resolved.
2118
- if (typeof def === 'function' && def.cid === undefined) {
2119
- hasAsync = true;
2120
- pending++;
2121
-
2122
- var resolve = once(function (resolvedDef) {
2123
- if (isESModule(resolvedDef)) {
2124
- resolvedDef = resolvedDef.default;
2125
- }
2126
- // save resolved on async factory in case it's used elsewhere
2127
- def.resolved = typeof resolvedDef === 'function'
2128
- ? resolvedDef
2129
- : _Kdu.extend(resolvedDef);
2130
- match.components[key] = resolvedDef;
2131
- pending--;
2132
- if (pending <= 0) {
2133
- next();
2134
- }
2135
- });
2136
-
2137
- var reject = once(function (reason) {
2138
- var msg = "Failed to resolve async component " + key + ": " + reason;
2139
- warn(false, msg);
2140
- if (!error) {
2141
- error = isError(reason)
2142
- ? reason
2143
- : new Error(msg);
2144
- next(error);
2145
- }
2146
- });
2147
-
2148
- var res;
2149
- try {
2150
- res = def(resolve, reject);
2151
- } catch (e) {
2152
- reject(e);
2153
- }
2154
- if (res) {
2155
- if (typeof res.then === 'function') {
2156
- res.then(resolve, reject);
2157
- } else {
2158
- // new syntax in Kdu 2.3
2159
- var comp = res.component;
2160
- if (comp && typeof comp.then === 'function') {
2161
- comp.then(resolve, reject);
2162
- }
2163
- }
2164
- }
2165
- }
2166
- });
2167
-
2168
- if (!hasAsync) { next(); }
2169
- }
2170
- }
2171
-
2172
- function flatMapComponents (
2173
- matched,
2174
- fn
2175
- ) {
2176
- return flatten(matched.map(function (m) {
2177
- return Object.keys(m.components).map(function (key) { return fn(
2178
- m.components[key],
2179
- m.instances[key],
2180
- m, key
2181
- ); })
2182
- }))
2183
- }
2184
-
2185
- function flatten (arr) {
2186
- return Array.prototype.concat.apply([], arr)
2187
- }
2188
-
2189
- var hasSymbol =
2190
- typeof Symbol === 'function' &&
2191
- typeof Symbol.toStringTag === 'symbol';
2192
-
2193
- function isESModule (obj) {
2194
- return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
2195
- }
2196
-
2197
- // in Webpack 2, require.ensure now also returns a Promise
2198
- // so the resolve/reject functions may get called an extra time
2199
- // if the user uses an arrow function shorthand that happens to
2200
- // return that Promise.
2201
- function once (fn) {
2202
- var called = false;
2203
- return function () {
2204
- var args = [], len = arguments.length;
2205
- while ( len-- ) args[ len ] = arguments[ len ];
2206
-
2207
- if (called) { return }
2208
- called = true;
2209
- return fn.apply(this, args)
2210
- }
2211
- }
2212
-
2213
- /* */
2214
-
2215
- var History = function History (router, base) {
2216
- this.router = router;
2217
- this.base = normalizeBase(base);
2218
- // start with a route object that stands for "nowhere"
2219
- this.current = START;
2220
- this.pending = null;
2221
- this.ready = false;
2222
- this.readyCbs = [];
2223
- this.readyErrorCbs = [];
2224
- this.errorCbs = [];
2225
- this.listeners = [];
2226
- };
2227
-
2228
- History.prototype.listen = function listen (cb) {
2229
- this.cb = cb;
2230
- };
2231
-
2232
- History.prototype.onReady = function onReady (cb, errorCb) {
2233
- if (this.ready) {
2234
- cb();
2235
- } else {
2236
- this.readyCbs.push(cb);
2237
- if (errorCb) {
2238
- this.readyErrorCbs.push(errorCb);
2239
- }
2240
- }
2241
- };
2242
-
2243
- History.prototype.onError = function onError (errorCb) {
2244
- this.errorCbs.push(errorCb);
2245
- };
2246
-
2247
- History.prototype.transitionTo = function transitionTo (
2248
- location,
2249
- onComplete,
2250
- onAbort
2251
- ) {
2252
- var this$1 = this;
2253
-
2254
- var route;
2255
- // catch redirect option
2256
- try {
2257
- route = this.router.match(location, this.current);
2258
- } catch (e) {
2259
- this.errorCbs.forEach(function (cb) {
2260
- cb(e);
2261
- });
2262
- // Exception should still be thrown
2263
- throw e
2264
- }
2265
- var prev = this.current;
2266
- this.confirmTransition(
2267
- route,
2268
- function () {
2269
- this$1.updateRoute(route);
2270
- onComplete && onComplete(route);
2271
- this$1.ensureURL();
2272
- this$1.router.afterHooks.forEach(function (hook) {
2273
- hook && hook(route, prev);
2274
- });
2275
-
2276
- // fire ready cbs once
2277
- if (!this$1.ready) {
2278
- this$1.ready = true;
2279
- this$1.readyCbs.forEach(function (cb) {
2280
- cb(route);
2281
- });
2282
- }
2283
- },
2284
- function (err) {
2285
- if (onAbort) {
2286
- onAbort(err);
2287
- }
2288
- if (err && !this$1.ready) {
2289
- // Initial redirection should not mark the history as ready yet
2290
- // because it's triggered by the redirection instead
2291
- if (!isNavigationFailure(err, NavigationFailureType.redirected) || prev !== START) {
2292
- this$1.ready = true;
2293
- this$1.readyErrorCbs.forEach(function (cb) {
2294
- cb(err);
2295
- });
2296
- }
2297
- }
2298
- }
2299
- );
2300
- };
2301
-
2302
- History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) {
2303
- var this$1 = this;
2304
-
2305
- var current = this.current;
2306
- this.pending = route;
2307
- var abort = function (err) {
2308
- // changed after adding errors
2309
- // before that change, redirect and aborted navigation would produce an err == null
2310
- if (!isNavigationFailure(err) && isError(err)) {
2311
- if (this$1.errorCbs.length) {
2312
- this$1.errorCbs.forEach(function (cb) {
2313
- cb(err);
2314
- });
2315
- } else {
2316
- {
2317
- warn(false, 'uncaught error during route navigation:');
2318
- }
2319
- console.error(err);
2320
- }
2321
- }
2322
- onAbort && onAbort(err);
2323
- };
2324
- var lastRouteIndex = route.matched.length - 1;
2325
- var lastCurrentIndex = current.matched.length - 1;
2326
- if (
2327
- isSameRoute(route, current) &&
2328
- // in the case the route map has been dynamically appended to
2329
- lastRouteIndex === lastCurrentIndex &&
2330
- route.matched[lastRouteIndex] === current.matched[lastCurrentIndex]
2331
- ) {
2332
- this.ensureURL();
2333
- if (route.hash) {
2334
- handleScroll(this.router, current, route, false);
2335
- }
2336
- return abort(createNavigationDuplicatedError(current, route))
2337
- }
2338
-
2339
- var ref = resolveQueue(
2340
- this.current.matched,
2341
- route.matched
2342
- );
2343
- var updated = ref.updated;
2344
- var deactivated = ref.deactivated;
2345
- var activated = ref.activated;
2346
-
2347
- var queue = [].concat(
2348
- // in-component leave guards
2349
- extractLeaveGuards(deactivated),
2350
- // global before hooks
2351
- this.router.beforeHooks,
2352
- // in-component update hooks
2353
- extractUpdateHooks(updated),
2354
- // in-config enter guards
2355
- activated.map(function (m) { return m.beforeEnter; }),
2356
- // async components
2357
- resolveAsyncComponents(activated)
2358
- );
2359
-
2360
- var iterator = function (hook, next) {
2361
- if (this$1.pending !== route) {
2362
- return abort(createNavigationCancelledError(current, route))
2363
- }
2364
- try {
2365
- hook(route, current, function (to) {
2366
- if (to === false) {
2367
- // next(false) -> abort navigation, ensure current URL
2368
- this$1.ensureURL(true);
2369
- abort(createNavigationAbortedError(current, route));
2370
- } else if (isError(to)) {
2371
- this$1.ensureURL(true);
2372
- abort(to);
2373
- } else if (
2374
- typeof to === 'string' ||
2375
- (typeof to === 'object' &&
2376
- (typeof to.path === 'string' || typeof to.name === 'string'))
2377
- ) {
2378
- // next('/') or next({ path: '/' }) -> redirect
2379
- abort(createNavigationRedirectedError(current, route));
2380
- if (typeof to === 'object' && to.replace) {
2381
- this$1.replace(to);
2382
- } else {
2383
- this$1.push(to);
2384
- }
2385
- } else {
2386
- // confirm transition and pass on the value
2387
- next(to);
2388
- }
2389
- });
2390
- } catch (e) {
2391
- abort(e);
2392
- }
2393
- };
2394
-
2395
- runQueue(queue, iterator, function () {
2396
- // wait until async components are resolved before
2397
- // extracting in-component enter guards
2398
- var enterGuards = extractEnterGuards(activated);
2399
- var queue = enterGuards.concat(this$1.router.resolveHooks);
2400
- runQueue(queue, iterator, function () {
2401
- if (this$1.pending !== route) {
2402
- return abort(createNavigationCancelledError(current, route))
2403
- }
2404
- this$1.pending = null;
2405
- onComplete(route);
2406
- if (this$1.router.app) {
2407
- this$1.router.app.$nextTick(function () {
2408
- handleRouteEntered(route);
2409
- });
2410
- }
2411
- });
2412
- });
2413
- };
2414
-
2415
- History.prototype.updateRoute = function updateRoute (route) {
2416
- this.current = route;
2417
- this.cb && this.cb(route);
2418
- };
2419
-
2420
- History.prototype.setupListeners = function setupListeners () {
2421
- // Default implementation is empty
2422
- };
2423
-
2424
- History.prototype.teardown = function teardown () {
2425
- // clean up event listeners
2426
- this.listeners.forEach(function (cleanupListener) {
2427
- cleanupListener();
2428
- });
2429
- this.listeners = [];
2430
-
2431
- // reset current history route
2432
- this.current = START;
2433
- this.pending = null;
2434
- };
2435
-
2436
- function normalizeBase (base) {
2437
- if (!base) {
2438
- if (inBrowser) {
2439
- // respect <base> tag
2440
- var baseEl = document.querySelector('base');
2441
- base = (baseEl && baseEl.getAttribute('href')) || '/';
2442
- // strip full URL origin
2443
- base = base.replace(/^https?:\/\/[^\/]+/, '');
2444
- } else {
2445
- base = '/';
2446
- }
2447
- }
2448
- // make sure there's the starting slash
2449
- if (base.charAt(0) !== '/') {
2450
- base = '/' + base;
2451
- }
2452
- // remove trailing slash
2453
- return base.replace(/\/$/, '')
2454
- }
2455
-
2456
- function resolveQueue (
2457
- current,
2458
- next
2459
- ) {
2460
- var i;
2461
- var max = Math.max(current.length, next.length);
2462
- for (i = 0; i < max; i++) {
2463
- if (current[i] !== next[i]) {
2464
- break
2465
- }
2466
- }
2467
- return {
2468
- updated: next.slice(0, i),
2469
- activated: next.slice(i),
2470
- deactivated: current.slice(i)
2471
- }
2472
- }
2473
-
2474
- function extractGuards (
2475
- records,
2476
- name,
2477
- bind,
2478
- reverse
2479
- ) {
2480
- var guards = flatMapComponents(records, function (def, instance, match, key) {
2481
- var guard = extractGuard(def, name);
2482
- if (guard) {
2483
- return Array.isArray(guard)
2484
- ? guard.map(function (guard) { return bind(guard, instance, match, key); })
2485
- : bind(guard, instance, match, key)
2486
- }
2487
- });
2488
- return flatten(reverse ? guards.reverse() : guards)
2489
- }
2490
-
2491
- function extractGuard (
2492
- def,
2493
- key
2494
- ) {
2495
- if (typeof def !== 'function') {
2496
- // extend now so that global mixins are applied.
2497
- def = _Kdu.extend(def);
2498
- }
2499
- return def.options[key]
2500
- }
2501
-
2502
- function extractLeaveGuards (deactivated) {
2503
- return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
2504
- }
2505
-
2506
- function extractUpdateHooks (updated) {
2507
- return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
2508
- }
2509
-
2510
- function bindGuard (guard, instance) {
2511
- if (instance) {
2512
- return function boundRouteGuard () {
2513
- return guard.apply(instance, arguments)
2514
- }
2515
- }
2516
- }
2517
-
2518
- function extractEnterGuards (
2519
- activated
2520
- ) {
2521
- return extractGuards(
2522
- activated,
2523
- 'beforeRouteEnter',
2524
- function (guard, _, match, key) {
2525
- return bindEnterGuard(guard, match, key)
2526
- }
2527
- )
2528
- }
2529
-
2530
- function bindEnterGuard (
2531
- guard,
2532
- match,
2533
- key
2534
- ) {
2535
- return function routeEnterGuard (to, from, next) {
2536
- return guard(to, from, function (cb) {
2537
- if (typeof cb === 'function') {
2538
- if (!match.enteredCbs[key]) {
2539
- match.enteredCbs[key] = [];
2540
- }
2541
- match.enteredCbs[key].push(cb);
2542
- }
2543
- next(cb);
2544
- })
2545
- }
2546
- }
2547
-
2548
- /* */
2549
-
2550
- var HTML5History = /*@__PURE__*/(function (History) {
2551
- function HTML5History (router, base) {
2552
- History.call(this, router, base);
2553
-
2554
- this._startLocation = getLocation(this.base);
2555
- }
2556
-
2557
- if ( History ) HTML5History.__proto__ = History;
2558
- HTML5History.prototype = Object.create( History && History.prototype );
2559
- HTML5History.prototype.constructor = HTML5History;
2560
-
2561
- HTML5History.prototype.setupListeners = function setupListeners () {
2562
- var this$1 = this;
2563
-
2564
- if (this.listeners.length > 0) {
2565
- return
2566
- }
2567
-
2568
- var router = this.router;
2569
- var expectScroll = router.options.scrollBehavior;
2570
- var supportsScroll = supportsPushState && expectScroll;
2571
-
2572
- if (supportsScroll) {
2573
- this.listeners.push(setupScroll());
2574
- }
2575
-
2576
- var handleRoutingEvent = function () {
2577
- var current = this$1.current;
2578
-
2579
- // Avoiding first `popstate` event dispatched in some browsers but first
2580
- // history route not updated since async guard at the same time.
2581
- var location = getLocation(this$1.base);
2582
- if (this$1.current === START && location === this$1._startLocation) {
2583
- return
2584
- }
2585
-
2586
- this$1.transitionTo(location, function (route) {
2587
- if (supportsScroll) {
2588
- handleScroll(router, route, current, true);
2589
- }
2590
- });
2591
- };
2592
- window.addEventListener('popstate', handleRoutingEvent);
2593
- this.listeners.push(function () {
2594
- window.removeEventListener('popstate', handleRoutingEvent);
2595
- });
2596
- };
2597
-
2598
- HTML5History.prototype.go = function go (n) {
2599
- window.history.go(n);
2600
- };
2601
-
2602
- HTML5History.prototype.push = function push (location, onComplete, onAbort) {
2603
- var this$1 = this;
2604
-
2605
- var ref = this;
2606
- var fromRoute = ref.current;
2607
- this.transitionTo(location, function (route) {
2608
- pushState(cleanPath(this$1.base + route.fullPath));
2609
- handleScroll(this$1.router, route, fromRoute, false);
2610
- onComplete && onComplete(route);
2611
- }, onAbort);
2612
- };
2613
-
2614
- HTML5History.prototype.replace = function replace (location, onComplete, onAbort) {
2615
- var this$1 = this;
2616
-
2617
- var ref = this;
2618
- var fromRoute = ref.current;
2619
- this.transitionTo(location, function (route) {
2620
- replaceState(cleanPath(this$1.base + route.fullPath));
2621
- handleScroll(this$1.router, route, fromRoute, false);
2622
- onComplete && onComplete(route);
2623
- }, onAbort);
2624
- };
2625
-
2626
- HTML5History.prototype.ensureURL = function ensureURL (push) {
2627
- if (getLocation(this.base) !== this.current.fullPath) {
2628
- var current = cleanPath(this.base + this.current.fullPath);
2629
- push ? pushState(current) : replaceState(current);
2630
- }
2631
- };
2632
-
2633
- HTML5History.prototype.getCurrentLocation = function getCurrentLocation () {
2634
- return getLocation(this.base)
2635
- };
2636
-
2637
- return HTML5History;
2638
- }(History));
2639
-
2640
- function getLocation (base) {
2641
- var path = window.location.pathname;
2642
- var pathLowerCase = path.toLowerCase();
2643
- var baseLowerCase = base.toLowerCase();
2644
- // base="/a" shouldn't turn path="/app" into "/a/pp"
2645
- // so we ensure the trailing slash in the base
2646
- if (base && ((pathLowerCase === baseLowerCase) ||
2647
- (pathLowerCase.indexOf(cleanPath(baseLowerCase + '/')) === 0))) {
2648
- path = path.slice(base.length);
2649
- }
2650
- return (path || '/') + window.location.search + window.location.hash
2651
- }
2652
-
2653
- /* */
2654
-
2655
- var HashHistory = /*@__PURE__*/(function (History) {
2656
- function HashHistory (router, base, fallback) {
2657
- History.call(this, router, base);
2658
- // check history fallback deeplinking
2659
- if (fallback && checkFallback(this.base)) {
2660
- return
2661
- }
2662
- ensureSlash();
2663
- }
2664
-
2665
- if ( History ) HashHistory.__proto__ = History;
2666
- HashHistory.prototype = Object.create( History && History.prototype );
2667
- HashHistory.prototype.constructor = HashHistory;
2668
-
2669
- // this is delayed until the app mounts
2670
- // to avoid the hashchange listener being fired too early
2671
- HashHistory.prototype.setupListeners = function setupListeners () {
2672
- var this$1 = this;
2673
-
2674
- if (this.listeners.length > 0) {
2675
- return
2676
- }
2677
-
2678
- var router = this.router;
2679
- var expectScroll = router.options.scrollBehavior;
2680
- var supportsScroll = supportsPushState && expectScroll;
2681
-
2682
- if (supportsScroll) {
2683
- this.listeners.push(setupScroll());
2684
- }
2685
-
2686
- var handleRoutingEvent = function () {
2687
- var current = this$1.current;
2688
- if (!ensureSlash()) {
2689
- return
2690
- }
2691
- this$1.transitionTo(getHash(), function (route) {
2692
- if (supportsScroll) {
2693
- handleScroll(this$1.router, route, current, true);
2694
- }
2695
- if (!supportsPushState) {
2696
- replaceHash(route.fullPath);
2697
- }
2698
- });
2699
- };
2700
- var eventType = supportsPushState ? 'popstate' : 'hashchange';
2701
- window.addEventListener(
2702
- eventType,
2703
- handleRoutingEvent
2704
- );
2705
- this.listeners.push(function () {
2706
- window.removeEventListener(eventType, handleRoutingEvent);
2707
- });
2708
- };
2709
-
2710
- HashHistory.prototype.push = function push (location, onComplete, onAbort) {
2711
- var this$1 = this;
2712
-
2713
- var ref = this;
2714
- var fromRoute = ref.current;
2715
- this.transitionTo(
2716
- location,
2717
- function (route) {
2718
- pushHash(route.fullPath);
2719
- handleScroll(this$1.router, route, fromRoute, false);
2720
- onComplete && onComplete(route);
2721
- },
2722
- onAbort
2723
- );
2724
- };
2725
-
2726
- HashHistory.prototype.replace = function replace (location, onComplete, onAbort) {
2727
- var this$1 = this;
2728
-
2729
- var ref = this;
2730
- var fromRoute = ref.current;
2731
- this.transitionTo(
2732
- location,
2733
- function (route) {
2734
- replaceHash(route.fullPath);
2735
- handleScroll(this$1.router, route, fromRoute, false);
2736
- onComplete && onComplete(route);
2737
- },
2738
- onAbort
2739
- );
2740
- };
2741
-
2742
- HashHistory.prototype.go = function go (n) {
2743
- window.history.go(n);
2744
- };
2745
-
2746
- HashHistory.prototype.ensureURL = function ensureURL (push) {
2747
- var current = this.current.fullPath;
2748
- if (getHash() !== current) {
2749
- push ? pushHash(current) : replaceHash(current);
2750
- }
2751
- };
2752
-
2753
- HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
2754
- return getHash()
2755
- };
2756
-
2757
- return HashHistory;
2758
- }(History));
2759
-
2760
- function checkFallback (base) {
2761
- var location = getLocation(base);
2762
- if (!/^\/#/.test(location)) {
2763
- window.location.replace(cleanPath(base + '/#' + location));
2764
- return true
2765
- }
2766
- }
2767
-
2768
- function ensureSlash () {
2769
- var path = getHash();
2770
- if (path.charAt(0) === '/') {
2771
- return true
2772
- }
2773
- replaceHash('/' + path);
2774
- return false
2775
- }
2776
-
2777
- function getHash () {
2778
- // We can't use window.location.hash here because it's not
2779
- // consistent across browsers - Firefox will pre-decode it!
2780
- var href = window.location.href;
2781
- var index = href.indexOf('#');
2782
- // empty path
2783
- if (index < 0) { return '' }
2784
-
2785
- href = href.slice(index + 1);
2786
-
2787
- return href
2788
- }
2789
-
2790
- function getUrl (path) {
2791
- var href = window.location.href;
2792
- var i = href.indexOf('#');
2793
- var base = i >= 0 ? href.slice(0, i) : href;
2794
- return (base + "#" + path)
2795
- }
2796
-
2797
- function pushHash (path) {
2798
- if (supportsPushState) {
2799
- pushState(getUrl(path));
2800
- } else {
2801
- window.location.hash = path;
2802
- }
2803
- }
2804
-
2805
- function replaceHash (path) {
2806
- if (supportsPushState) {
2807
- replaceState(getUrl(path));
2808
- } else {
2809
- window.location.replace(getUrl(path));
2810
- }
2811
- }
2812
-
2813
- /* */
2814
-
2815
- var AbstractHistory = /*@__PURE__*/(function (History) {
2816
- function AbstractHistory (router, base) {
2817
- History.call(this, router, base);
2818
- this.stack = [];
2819
- this.index = -1;
2820
- }
2821
-
2822
- if ( History ) AbstractHistory.__proto__ = History;
2823
- AbstractHistory.prototype = Object.create( History && History.prototype );
2824
- AbstractHistory.prototype.constructor = AbstractHistory;
2825
-
2826
- AbstractHistory.prototype.push = function push (location, onComplete, onAbort) {
2827
- var this$1 = this;
2828
-
2829
- this.transitionTo(
2830
- location,
2831
- function (route) {
2832
- this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route);
2833
- this$1.index++;
2834
- onComplete && onComplete(route);
2835
- },
2836
- onAbort
2837
- );
2838
- };
2839
-
2840
- AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) {
2841
- var this$1 = this;
2842
-
2843
- this.transitionTo(
2844
- location,
2845
- function (route) {
2846
- this$1.stack = this$1.stack.slice(0, this$1.index).concat(route);
2847
- onComplete && onComplete(route);
2848
- },
2849
- onAbort
2850
- );
2851
- };
2852
-
2853
- AbstractHistory.prototype.go = function go (n) {
2854
- var this$1 = this;
2855
-
2856
- var targetIndex = this.index + n;
2857
- if (targetIndex < 0 || targetIndex >= this.stack.length) {
2858
- return
2859
- }
2860
- var route = this.stack[targetIndex];
2861
- this.confirmTransition(
2862
- route,
2863
- function () {
2864
- var prev = this$1.current;
2865
- this$1.index = targetIndex;
2866
- this$1.updateRoute(route);
2867
- this$1.router.afterHooks.forEach(function (hook) {
2868
- hook && hook(route, prev);
2869
- });
2870
- },
2871
- function (err) {
2872
- if (isNavigationFailure(err, NavigationFailureType.duplicated)) {
2873
- this$1.index = targetIndex;
2874
- }
2875
- }
2876
- );
2877
- };
2878
-
2879
- AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () {
2880
- var current = this.stack[this.stack.length - 1];
2881
- return current ? current.fullPath : '/'
2882
- };
2883
-
2884
- AbstractHistory.prototype.ensureURL = function ensureURL () {
2885
- // noop
2886
- };
2887
-
2888
- return AbstractHistory;
2889
- }(History));
2890
-
2891
- /* */
2892
-
2893
- var KduRouter = function KduRouter (options) {
2894
- if ( options === void 0 ) options = {};
2895
-
2896
- {
2897
- warn(this instanceof KduRouter, "Router must be called with the new operator.");
2898
- }
2899
- this.app = null;
2900
- this.apps = [];
2901
- this.options = options;
2902
- this.beforeHooks = [];
2903
- this.resolveHooks = [];
2904
- this.afterHooks = [];
2905
- this.matcher = createMatcher(options.routes || [], this);
2906
-
2907
- var mode = options.mode || 'hash';
2908
- this.fallback =
2909
- mode === 'history' && !supportsPushState && options.fallback !== false;
2910
- if (this.fallback) {
2911
- mode = 'hash';
2912
- }
2913
- if (!inBrowser) {
2914
- mode = 'abstract';
2915
- }
2916
- this.mode = mode;
2917
-
2918
- switch (mode) {
2919
- case 'history':
2920
- this.history = new HTML5History(this, options.base);
2921
- break
2922
- case 'hash':
2923
- this.history = new HashHistory(this, options.base, this.fallback);
2924
- break
2925
- case 'abstract':
2926
- this.history = new AbstractHistory(this, options.base);
2927
- break
2928
- default:
2929
- {
2930
- assert(false, ("invalid mode: " + mode));
2931
- }
2932
- }
2933
- };
2934
-
2935
- var prototypeAccessors = { currentRoute: { configurable: true } };
2936
-
2937
- KduRouter.prototype.match = function match (raw, current, redirectedFrom) {
2938
- return this.matcher.match(raw, current, redirectedFrom)
2939
- };
2940
-
2941
- prototypeAccessors.currentRoute.get = function () {
2942
- return this.history && this.history.current
2943
- };
2944
-
2945
- KduRouter.prototype.init = function init (app /* Kdu component instance */) {
2946
- var this$1 = this;
2947
-
2948
- assert(
2949
- install.installed,
2950
- "not installed. Make sure to call `Kdu.use(KduRouter)` " +
2951
- "before creating root instance."
2952
- );
2953
-
2954
- this.apps.push(app);
2955
-
2956
- // set up app destroyed handler
2957
- app.$once('hook:destroyed', function () {
2958
- // clean out app from this.apps array once destroyed
2959
- var index = this$1.apps.indexOf(app);
2960
- if (index > -1) { this$1.apps.splice(index, 1); }
2961
- // ensure we still have a main app or null if no apps
2962
- // we do not release the router so it can be reused
2963
- if (this$1.app === app) { this$1.app = this$1.apps[0] || null; }
2964
-
2965
- if (!this$1.app) { this$1.history.teardown(); }
2966
- });
2967
-
2968
- // main app previously initialized
2969
- // return as we don't need to set up new history listener
2970
- if (this.app) {
2971
- return
2972
- }
2973
-
2974
- this.app = app;
2975
-
2976
- var history = this.history;
2977
-
2978
- if (history instanceof HTML5History || history instanceof HashHistory) {
2979
- var handleInitialScroll = function (routeOrError) {
2980
- var from = history.current;
2981
- var expectScroll = this$1.options.scrollBehavior;
2982
- var supportsScroll = supportsPushState && expectScroll;
2983
-
2984
- if (supportsScroll && 'fullPath' in routeOrError) {
2985
- handleScroll(this$1, routeOrError, from, false);
2986
- }
2987
- };
2988
- var setupListeners = function (routeOrError) {
2989
- history.setupListeners();
2990
- handleInitialScroll(routeOrError);
2991
- };
2992
- history.transitionTo(
2993
- history.getCurrentLocation(),
2994
- setupListeners,
2995
- setupListeners
2996
- );
2997
- }
2998
-
2999
- history.listen(function (route) {
3000
- this$1.apps.forEach(function (app) {
3001
- app._route = route;
3002
- });
3003
- });
3004
- };
3005
-
3006
- KduRouter.prototype.beforeEach = function beforeEach (fn) {
3007
- return registerHook(this.beforeHooks, fn)
3008
- };
3009
-
3010
- KduRouter.prototype.beforeResolve = function beforeResolve (fn) {
3011
- return registerHook(this.resolveHooks, fn)
3012
- };
3013
-
3014
- KduRouter.prototype.afterEach = function afterEach (fn) {
3015
- return registerHook(this.afterHooks, fn)
3016
- };
3017
-
3018
- KduRouter.prototype.onReady = function onReady (cb, errorCb) {
3019
- this.history.onReady(cb, errorCb);
3020
- };
3021
-
3022
- KduRouter.prototype.onError = function onError (errorCb) {
3023
- this.history.onError(errorCb);
3024
- };
3025
-
3026
- KduRouter.prototype.push = function push (location, onComplete, onAbort) {
3027
- var this$1 = this;
3028
-
3029
- // $flow-disable-line
3030
- if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
3031
- return new Promise(function (resolve, reject) {
3032
- this$1.history.push(location, resolve, reject);
3033
- })
3034
- } else {
3035
- this.history.push(location, onComplete, onAbort);
3036
- }
3037
- };
3038
-
3039
- KduRouter.prototype.replace = function replace (location, onComplete, onAbort) {
3040
- var this$1 = this;
3041
-
3042
- // $flow-disable-line
3043
- if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
3044
- return new Promise(function (resolve, reject) {
3045
- this$1.history.replace(location, resolve, reject);
3046
- })
3047
- } else {
3048
- this.history.replace(location, onComplete, onAbort);
3049
- }
3050
- };
3051
-
3052
- KduRouter.prototype.go = function go (n) {
3053
- this.history.go(n);
3054
- };
3055
-
3056
- KduRouter.prototype.back = function back () {
3057
- this.go(-1);
3058
- };
3059
-
3060
- KduRouter.prototype.forward = function forward () {
3061
- this.go(1);
3062
- };
3063
-
3064
- KduRouter.prototype.getMatchedComponents = function getMatchedComponents (to) {
3065
- var route = to
3066
- ? to.matched
3067
- ? to
3068
- : this.resolve(to).route
3069
- : this.currentRoute;
3070
- if (!route) {
3071
- return []
3072
- }
3073
- return [].concat.apply(
3074
- [],
3075
- route.matched.map(function (m) {
3076
- return Object.keys(m.components).map(function (key) {
3077
- return m.components[key]
3078
- })
3079
- })
3080
- )
3081
- };
3082
-
3083
- KduRouter.prototype.resolve = function resolve (
3084
- to,
3085
- current,
3086
- append
3087
- ) {
3088
- current = current || this.history.current;
3089
- var location = normalizeLocation(to, current, append, this);
3090
- var route = this.match(location, current);
3091
- var fullPath = route.redirectedFrom || route.fullPath;
3092
- var base = this.history.base;
3093
- var href = createHref(base, fullPath, this.mode);
3094
- return {
3095
- location: location,
3096
- route: route,
3097
- href: href,
3098
- // for backwards compat
3099
- normalizedTo: location,
3100
- resolved: route
3101
- }
3102
- };
3103
-
3104
- KduRouter.prototype.getRoutes = function getRoutes () {
3105
- return this.matcher.getRoutes()
3106
- };
3107
-
3108
- KduRouter.prototype.addRoute = function addRoute (parentOrRoute, route) {
3109
- this.matcher.addRoute(parentOrRoute, route);
3110
- if (this.history.current !== START) {
3111
- this.history.transitionTo(this.history.getCurrentLocation());
3112
- }
3113
- };
3114
-
3115
- KduRouter.prototype.addRoutes = function addRoutes (routes) {
3116
- {
3117
- warn(false, 'router.addRoutes() is deprecated and has been removed in Kdu Router 4. Use router.addRoute() instead.');
3118
- }
3119
- this.matcher.addRoutes(routes);
3120
- if (this.history.current !== START) {
3121
- this.history.transitionTo(this.history.getCurrentLocation());
3122
- }
3123
- };
3124
-
3125
- Object.defineProperties( KduRouter.prototype, prototypeAccessors );
3126
-
3127
- function registerHook (list, fn) {
3128
- list.push(fn);
3129
- return function () {
3130
- var i = list.indexOf(fn);
3131
- if (i > -1) { list.splice(i, 1); }
3132
- }
3133
- }
3134
-
3135
- function createHref (base, fullPath, mode) {
3136
- var path = mode === 'hash' ? '#' + fullPath : fullPath;
3137
- return base ? cleanPath(base + '/' + path) : path
3138
- }
3139
-
3140
- KduRouter.install = install;
3141
- KduRouter.version = '3.5.4';
3142
- KduRouter.isNavigationFailure = isNavigationFailure;
3143
- KduRouter.NavigationFailureType = NavigationFailureType;
3144
- KduRouter.START_LOCATION = START;
3145
-
3146
- if (inBrowser && window.Kdu) {
3147
- window.Kdu.use(KduRouter);
3148
- }
3149
-
3150
- return KduRouter;
3151
-
3152
- })));