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