PageRenderTime 30ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/js/ui/vue/router/src/router.js

https://gitlab.com/alexprowars/bitrix
JavaScript | 1947 lines | 1456 code | 247 blank | 244 comment | 344 complexity | 725c8689ecb43546f5619d36cdd95a94 MD5 | raw file
  1. /*!
  2. * vue-router v3.5.3
  3. * (c) 2021 Evan You
  4. * @license MIT
  5. *
  6. * @source: https://unpkg.com/vue-router@3.5.3/dist/vue-router.esm.browser.js
  7. */
  8. /**
  9. * Modify list for integration with Bitrix Framework:
  10. * - replaced usages window.Vue to local value of Vue;
  11. * - add method VueRouter.create
  12. */
  13. import {VueVendor as Vue} from "ui.vue";
  14. // origin-start
  15. function assert (condition, message) {
  16. if (!condition) {
  17. throw new Error(`[vue-router] ${message}`)
  18. }
  19. }
  20. function warn (condition, message) {
  21. if (!condition) {
  22. typeof console !== 'undefined' && console.warn(`[vue-router] ${message}`);
  23. }
  24. }
  25. function extend (a, b) {
  26. for (const key in b) {
  27. a[key] = b[key];
  28. }
  29. return a
  30. }
  31. /* */
  32. const encodeReserveRE = /[!'()*]/g;
  33. const encodeReserveReplacer = c => '%' + c.charCodeAt(0).toString(16);
  34. const commaRE = /%2C/g;
  35. // fixed encodeURIComponent which is more conformant to RFC3986:
  36. // - escapes [!'()*]
  37. // - preserve commas
  38. const encode = str =>
  39. encodeURIComponent(str)
  40. .replace(encodeReserveRE, encodeReserveReplacer)
  41. .replace(commaRE, ',');
  42. function decode (str) {
  43. try {
  44. return decodeURIComponent(str)
  45. } catch (err) {
  46. {
  47. warn(false, `Error decoding "${str}". Leaving it intact.`);
  48. }
  49. }
  50. return str
  51. }
  52. function resolveQuery (
  53. query,
  54. extraQuery = {},
  55. _parseQuery
  56. ) {
  57. const parse = _parseQuery || parseQuery;
  58. let parsedQuery;
  59. try {
  60. parsedQuery = parse(query || '');
  61. } catch (e) {
  62. warn(false, e.message);
  63. parsedQuery = {};
  64. }
  65. for (const key in extraQuery) {
  66. const value = extraQuery[key];
  67. parsedQuery[key] = Array.isArray(value)
  68. ? value.map(castQueryParamValue)
  69. : castQueryParamValue(value);
  70. }
  71. return parsedQuery
  72. }
  73. const castQueryParamValue = value => (value == null || typeof value === 'object' ? value : String(value));
  74. function parseQuery (query) {
  75. const res = {};
  76. query = query.trim().replace(/^(\?|#|&)/, '');
  77. if (!query) {
  78. return res
  79. }
  80. query.split('&').forEach(param => {
  81. const parts = param.replace(/\+/g, ' ').split('=');
  82. const key = decode(parts.shift());
  83. const val = parts.length > 0 ? decode(parts.join('=')) : null;
  84. if (res[key] === undefined) {
  85. res[key] = val;
  86. } else if (Array.isArray(res[key])) {
  87. res[key].push(val);
  88. } else {
  89. res[key] = [res[key], val];
  90. }
  91. });
  92. return res
  93. }
  94. function stringifyQuery (obj) {
  95. const res = obj
  96. ? Object.keys(obj)
  97. .map(key => {
  98. const val = obj[key];
  99. if (val === undefined) {
  100. return ''
  101. }
  102. if (val === null) {
  103. return encode(key)
  104. }
  105. if (Array.isArray(val)) {
  106. const result = [];
  107. val.forEach(val2 => {
  108. if (val2 === undefined) {
  109. return
  110. }
  111. if (val2 === null) {
  112. result.push(encode(key));
  113. } else {
  114. result.push(encode(key) + '=' + encode(val2));
  115. }
  116. });
  117. return result.join('&')
  118. }
  119. return encode(key) + '=' + encode(val)
  120. })
  121. .filter(x => x.length > 0)
  122. .join('&')
  123. : null;
  124. return res ? `?${res}` : ''
  125. }
  126. /* */
  127. const trailingSlashRE = /\/?$/;
  128. function createRoute (
  129. record,
  130. location,
  131. redirectedFrom,
  132. router
  133. ) {
  134. const stringifyQuery = router && router.options.stringifyQuery;
  135. let query = location.query || {};
  136. try {
  137. query = clone(query);
  138. } catch (e) {}
  139. const route = {
  140. name: location.name || (record && record.name),
  141. meta: (record && record.meta) || {},
  142. path: location.path || '/',
  143. hash: location.hash || '',
  144. query,
  145. params: location.params || {},
  146. fullPath: getFullPath(location, stringifyQuery),
  147. matched: record ? formatMatch(record) : []
  148. };
  149. if (redirectedFrom) {
  150. route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery);
  151. }
  152. return Object.freeze(route)
  153. }
  154. function clone (value) {
  155. if (Array.isArray(value)) {
  156. return value.map(clone)
  157. } else if (value && typeof value === 'object') {
  158. const res = {};
  159. for (const key in value) {
  160. res[key] = clone(value[key]);
  161. }
  162. return res
  163. } else {
  164. return value
  165. }
  166. }
  167. // the starting route that represents the initial state
  168. const START = createRoute(null, {
  169. path: '/'
  170. });
  171. function formatMatch (record) {
  172. const res = [];
  173. while (record) {
  174. res.unshift(record);
  175. record = record.parent;
  176. }
  177. return res
  178. }
  179. function getFullPath (
  180. { path, query = {}, hash = '' },
  181. _stringifyQuery
  182. ) {
  183. const stringify = _stringifyQuery || stringifyQuery;
  184. return (path || '/') + stringify(query) + hash
  185. }
  186. function isSameRoute (a, b, onlyPath) {
  187. if (b === START) {
  188. return a === b
  189. } else if (!b) {
  190. return false
  191. } else if (a.path && b.path) {
  192. return a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && (onlyPath ||
  193. a.hash === b.hash &&
  194. isObjectEqual(a.query, b.query))
  195. } else if (a.name && b.name) {
  196. return (
  197. a.name === b.name &&
  198. (onlyPath || (
  199. a.hash === b.hash &&
  200. isObjectEqual(a.query, b.query) &&
  201. isObjectEqual(a.params, b.params))
  202. )
  203. )
  204. } else {
  205. return false
  206. }
  207. }
  208. function isObjectEqual (a = {}, b = {}) {
  209. // handle null value #1566
  210. if (!a || !b) return a === b
  211. const aKeys = Object.keys(a).sort();
  212. const bKeys = Object.keys(b).sort();
  213. if (aKeys.length !== bKeys.length) {
  214. return false
  215. }
  216. return aKeys.every((key, i) => {
  217. const aVal = a[key];
  218. const bKey = bKeys[i];
  219. if (bKey !== key) return false
  220. const bVal = b[key];
  221. // query values can be null and undefined
  222. if (aVal == null || bVal == null) return aVal === bVal
  223. // check nested equality
  224. if (typeof aVal === 'object' && typeof bVal === 'object') {
  225. return isObjectEqual(aVal, bVal)
  226. }
  227. return String(aVal) === String(bVal)
  228. })
  229. }
  230. function isIncludedRoute (current, target) {
  231. return (
  232. current.path.replace(trailingSlashRE, '/').indexOf(
  233. target.path.replace(trailingSlashRE, '/')
  234. ) === 0 &&
  235. (!target.hash || current.hash === target.hash) &&
  236. queryIncludes(current.query, target.query)
  237. )
  238. }
  239. function queryIncludes (current, target) {
  240. for (const key in target) {
  241. if (!(key in current)) {
  242. return false
  243. }
  244. }
  245. return true
  246. }
  247. function handleRouteEntered (route) {
  248. for (let i = 0; i < route.matched.length; i++) {
  249. const record = route.matched[i];
  250. for (const name in record.instances) {
  251. const instance = record.instances[name];
  252. const cbs = record.enteredCbs[name];
  253. if (!instance || !cbs) continue
  254. delete record.enteredCbs[name];
  255. for (let i = 0; i < cbs.length; i++) {
  256. if (!instance._isBeingDestroyed) cbs[i](instance);
  257. }
  258. }
  259. }
  260. }
  261. var View = {
  262. name: 'RouterView',
  263. functional: true,
  264. props: {
  265. name: {
  266. type: String,
  267. default: 'default'
  268. }
  269. },
  270. render (_, { props, children, parent, data }) {
  271. // used by devtools to display a router-view badge
  272. data.routerView = true;
  273. // directly use parent context's createElement() function
  274. // so that components rendered by router-view can resolve named slots
  275. const h = parent.$createElement;
  276. const name = props.name;
  277. const route = parent.$route;
  278. const cache = parent._routerViewCache || (parent._routerViewCache = {});
  279. // determine current view depth, also check to see if the tree
  280. // has been toggled inactive but kept-alive.
  281. let depth = 0;
  282. let inactive = false;
  283. while (parent && parent._routerRoot !== parent) {
  284. const vnodeData = parent.$vnode ? parent.$vnode.data : {};
  285. if (vnodeData.routerView) {
  286. depth++;
  287. }
  288. if (vnodeData.keepAlive && parent._directInactive && parent._inactive) {
  289. inactive = true;
  290. }
  291. parent = parent.$parent;
  292. }
  293. data.routerViewDepth = depth;
  294. // render previous view if the tree is inactive and kept-alive
  295. if (inactive) {
  296. const cachedData = cache[name];
  297. const cachedComponent = cachedData && cachedData.component;
  298. if (cachedComponent) {
  299. // #2301
  300. // pass props
  301. if (cachedData.configProps) {
  302. fillPropsinData(cachedComponent, data, cachedData.route, cachedData.configProps);
  303. }
  304. return h(cachedComponent, data, children)
  305. } else {
  306. // render previous empty view
  307. return h()
  308. }
  309. }
  310. const matched = route.matched[depth];
  311. const component = matched && matched.components[name];
  312. // render empty node if no matched route or no config component
  313. if (!matched || !component) {
  314. cache[name] = null;
  315. return h()
  316. }
  317. // cache component
  318. cache[name] = { component };
  319. // attach instance registration hook
  320. // this will be called in the instance's injected lifecycle hooks
  321. data.registerRouteInstance = (vm, val) => {
  322. // val could be undefined for unregistration
  323. const current = matched.instances[name];
  324. if (
  325. (val && current !== vm) ||
  326. (!val && current === vm)
  327. ) {
  328. matched.instances[name] = val;
  329. }
  330. }
  331. // also register instance in prepatch hook
  332. // in case the same component instance is reused across different routes
  333. ;(data.hook || (data.hook = {})).prepatch = (_, vnode) => {
  334. matched.instances[name] = vnode.componentInstance;
  335. };
  336. // register instance in init hook
  337. // in case kept-alive component be actived when routes changed
  338. data.hook.init = (vnode) => {
  339. if (vnode.data.keepAlive &&
  340. vnode.componentInstance &&
  341. vnode.componentInstance !== matched.instances[name]
  342. ) {
  343. matched.instances[name] = vnode.componentInstance;
  344. }
  345. // if the route transition has already been confirmed then we weren't
  346. // able to call the cbs during confirmation as the component was not
  347. // registered yet, so we call it here.
  348. handleRouteEntered(route);
  349. };
  350. const configProps = matched.props && matched.props[name];
  351. // save route and configProps in cache
  352. if (configProps) {
  353. extend(cache[name], {
  354. route,
  355. configProps
  356. });
  357. fillPropsinData(component, data, route, configProps);
  358. }
  359. return h(component, data, children)
  360. }
  361. };
  362. function fillPropsinData (component, data, route, configProps) {
  363. // resolve props
  364. let propsToPass = data.props = resolveProps(route, configProps);
  365. if (propsToPass) {
  366. // clone to prevent mutation
  367. propsToPass = data.props = extend({}, propsToPass);
  368. // pass non-declared props as attrs
  369. const attrs = data.attrs = data.attrs || {};
  370. for (const key in propsToPass) {
  371. if (!component.props || !(key in component.props)) {
  372. attrs[key] = propsToPass[key];
  373. delete propsToPass[key];
  374. }
  375. }
  376. }
  377. }
  378. function resolveProps (route, config) {
  379. switch (typeof config) {
  380. case 'undefined':
  381. return
  382. case 'object':
  383. return config
  384. case 'function':
  385. return config(route)
  386. case 'boolean':
  387. return config ? route.params : undefined
  388. default:
  389. {
  390. warn(
  391. false,
  392. `props in "${route.path}" is a ${typeof config}, ` +
  393. `expecting an object, function or boolean.`
  394. );
  395. }
  396. }
  397. }
  398. /* */
  399. function resolvePath (
  400. relative,
  401. base,
  402. append
  403. ) {
  404. const firstChar = relative.charAt(0);
  405. if (firstChar === '/') {
  406. return relative
  407. }
  408. if (firstChar === '?' || firstChar === '#') {
  409. return base + relative
  410. }
  411. const stack = base.split('/');
  412. // remove trailing segment if:
  413. // - not appending
  414. // - appending to trailing slash (last segment is empty)
  415. if (!append || !stack[stack.length - 1]) {
  416. stack.pop();
  417. }
  418. // resolve relative path
  419. const segments = relative.replace(/^\//, '').split('/');
  420. for (let i = 0; i < segments.length; i++) {
  421. const segment = segments[i];
  422. if (segment === '..') {
  423. stack.pop();
  424. } else if (segment !== '.') {
  425. stack.push(segment);
  426. }
  427. }
  428. // ensure leading slash
  429. if (stack[0] !== '') {
  430. stack.unshift('');
  431. }
  432. return stack.join('/')
  433. }
  434. function parsePath (path) {
  435. let hash = '';
  436. let query = '';
  437. const hashIndex = path.indexOf('#');
  438. if (hashIndex >= 0) {
  439. hash = path.slice(hashIndex);
  440. path = path.slice(0, hashIndex);
  441. }
  442. const queryIndex = path.indexOf('?');
  443. if (queryIndex >= 0) {
  444. query = path.slice(queryIndex + 1);
  445. path = path.slice(0, queryIndex);
  446. }
  447. return {
  448. path,
  449. query,
  450. hash
  451. }
  452. }
  453. function cleanPath (path) {
  454. return path.replace(/\/+/g, '/')
  455. }
  456. var isarray = Array.isArray || function (arr) {
  457. return Object.prototype.toString.call(arr) == '[object Array]';
  458. };
  459. /**
  460. * Expose `pathToRegexp`.
  461. */
  462. var pathToRegexp_1 = pathToRegexp;
  463. var parse_1 = parse;
  464. var compile_1 = compile;
  465. var tokensToFunction_1 = tokensToFunction;
  466. var tokensToRegExp_1 = tokensToRegExp;
  467. /**
  468. * The main path matching regexp utility.
  469. *
  470. * @type {RegExp}
  471. */
  472. var PATH_REGEXP = new RegExp([
  473. // Match escaped characters that would otherwise appear in future matches.
  474. // This allows the user to escape special characters that won't transform.
  475. '(\\\\.)',
  476. // Match Express-style parameters and un-named parameters with a prefix
  477. // and optional suffixes. Matches appear as:
  478. //
  479. // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
  480. // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
  481. // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
  482. '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
  483. ].join('|'), 'g');
  484. /**
  485. * Parse a string for the raw tokens.
  486. *
  487. * @param {string} str
  488. * @param {Object=} options
  489. * @return {!Array}
  490. */
  491. function parse (str, options) {
  492. var tokens = [];
  493. var key = 0;
  494. var index = 0;
  495. var path = '';
  496. var defaultDelimiter = options && options.delimiter || '/';
  497. var res;
  498. while ((res = PATH_REGEXP.exec(str)) != null) {
  499. var m = res[0];
  500. var escaped = res[1];
  501. var offset = res.index;
  502. path += str.slice(index, offset);
  503. index = offset + m.length;
  504. // Ignore already escaped sequences.
  505. if (escaped) {
  506. path += escaped[1];
  507. continue
  508. }
  509. var next = str[index];
  510. var prefix = res[2];
  511. var name = res[3];
  512. var capture = res[4];
  513. var group = res[5];
  514. var modifier = res[6];
  515. var asterisk = res[7];
  516. // Push the current path onto the tokens.
  517. if (path) {
  518. tokens.push(path);
  519. path = '';
  520. }
  521. var partial = prefix != null && next != null && next !== prefix;
  522. var repeat = modifier === '+' || modifier === '*';
  523. var optional = modifier === '?' || modifier === '*';
  524. var delimiter = res[2] || defaultDelimiter;
  525. var pattern = capture || group;
  526. tokens.push({
  527. name: name || key++,
  528. prefix: prefix || '',
  529. delimiter: delimiter,
  530. optional: optional,
  531. repeat: repeat,
  532. partial: partial,
  533. asterisk: !!asterisk,
  534. pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
  535. });
  536. }
  537. // Match any characters still remaining.
  538. if (index < str.length) {
  539. path += str.substr(index);
  540. }
  541. // If the path exists, push it onto the end.
  542. if (path) {
  543. tokens.push(path);
  544. }
  545. return tokens
  546. }
  547. /**
  548. * Compile a string to a template function for the path.
  549. *
  550. * @param {string} str
  551. * @param {Object=} options
  552. * @return {!function(Object=, Object=)}
  553. */
  554. function compile (str, options) {
  555. return tokensToFunction(parse(str, options), options)
  556. }
  557. /**
  558. * Prettier encoding of URI path segments.
  559. *
  560. * @param {string}
  561. * @return {string}
  562. */
  563. function encodeURIComponentPretty (str) {
  564. return encodeURI(str).replace(/[\/?#]/g, function (c) {
  565. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  566. })
  567. }
  568. /**
  569. * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
  570. *
  571. * @param {string}
  572. * @return {string}
  573. */
  574. function encodeAsterisk (str) {
  575. return encodeURI(str).replace(/[?#]/g, function (c) {
  576. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  577. })
  578. }
  579. /**
  580. * Expose a method for transforming tokens into the path function.
  581. */
  582. function tokensToFunction (tokens, options) {
  583. // Compile all the tokens into regexps.
  584. var matches = new Array(tokens.length);
  585. // Compile all the patterns before compilation.
  586. for (var i = 0; i < tokens.length; i++) {
  587. if (typeof tokens[i] === 'object') {
  588. matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options));
  589. }
  590. }
  591. return function (obj, opts) {
  592. var path = '';
  593. var data = obj || {};
  594. var options = opts || {};
  595. var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
  596. for (var i = 0; i < tokens.length; i++) {
  597. var token = tokens[i];
  598. if (typeof token === 'string') {
  599. path += token;
  600. continue
  601. }
  602. var value = data[token.name];
  603. var segment;
  604. if (value == null) {
  605. if (token.optional) {
  606. // Prepend partial segment prefixes.
  607. if (token.partial) {
  608. path += token.prefix;
  609. }
  610. continue
  611. } else {
  612. throw new TypeError('Expected "' + token.name + '" to be defined')
  613. }
  614. }
  615. if (isarray(value)) {
  616. if (!token.repeat) {
  617. throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
  618. }
  619. if (value.length === 0) {
  620. if (token.optional) {
  621. continue
  622. } else {
  623. throw new TypeError('Expected "' + token.name + '" to not be empty')
  624. }
  625. }
  626. for (var j = 0; j < value.length; j++) {
  627. segment = encode(value[j]);
  628. if (!matches[i].test(segment)) {
  629. throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
  630. }
  631. path += (j === 0 ? token.prefix : token.delimiter) + segment;
  632. }
  633. continue
  634. }
  635. segment = token.asterisk ? encodeAsterisk(value) : encode(value);
  636. if (!matches[i].test(segment)) {
  637. throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
  638. }
  639. path += token.prefix + segment;
  640. }
  641. return path
  642. }
  643. }
  644. /**
  645. * Escape a regular expression string.
  646. *
  647. * @param {string} str
  648. * @return {string}
  649. */
  650. function escapeString (str) {
  651. return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
  652. }
  653. /**
  654. * Escape the capturing group by escaping special characters and meaning.
  655. *
  656. * @param {string} group
  657. * @return {string}
  658. */
  659. function escapeGroup (group) {
  660. return group.replace(/([=!:$\/()])/g, '\\$1')
  661. }
  662. /**
  663. * Attach the keys as a property of the regexp.
  664. *
  665. * @param {!RegExp} re
  666. * @param {Array} keys
  667. * @return {!RegExp}
  668. */
  669. function attachKeys (re, keys) {
  670. re.keys = keys;
  671. return re
  672. }
  673. /**
  674. * Get the flags for a regexp from the options.
  675. *
  676. * @param {Object} options
  677. * @return {string}
  678. */
  679. function flags (options) {
  680. return options && options.sensitive ? '' : 'i'
  681. }
  682. /**
  683. * Pull out keys from a regexp.
  684. *
  685. * @param {!RegExp} path
  686. * @param {!Array} keys
  687. * @return {!RegExp}
  688. */
  689. function regexpToRegexp (path, keys) {
  690. // Use a negative lookahead to match only capturing groups.
  691. var groups = path.source.match(/\((?!\?)/g);
  692. if (groups) {
  693. for (var i = 0; i < groups.length; i++) {
  694. keys.push({
  695. name: i,
  696. prefix: null,
  697. delimiter: null,
  698. optional: false,
  699. repeat: false,
  700. partial: false,
  701. asterisk: false,
  702. pattern: null
  703. });
  704. }
  705. }
  706. return attachKeys(path, keys)
  707. }
  708. /**
  709. * Transform an array into a regexp.
  710. *
  711. * @param {!Array} path
  712. * @param {Array} keys
  713. * @param {!Object} options
  714. * @return {!RegExp}
  715. */
  716. function arrayToRegexp (path, keys, options) {
  717. var parts = [];
  718. for (var i = 0; i < path.length; i++) {
  719. parts.push(pathToRegexp(path[i], keys, options).source);
  720. }
  721. var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
  722. return attachKeys(regexp, keys)
  723. }
  724. /**
  725. * Create a path regexp from string input.
  726. *
  727. * @param {string} path
  728. * @param {!Array} keys
  729. * @param {!Object} options
  730. * @return {!RegExp}
  731. */
  732. function stringToRegexp (path, keys, options) {
  733. return tokensToRegExp(parse(path, options), keys, options)
  734. }
  735. /**
  736. * Expose a function for taking tokens and returning a RegExp.
  737. *
  738. * @param {!Array} tokens
  739. * @param {(Array|Object)=} keys
  740. * @param {Object=} options
  741. * @return {!RegExp}
  742. */
  743. function tokensToRegExp (tokens, keys, options) {
  744. if (!isarray(keys)) {
  745. options = /** @type {!Object} */ (keys || options);
  746. keys = [];
  747. }
  748. options = options || {};
  749. var strict = options.strict;
  750. var end = options.end !== false;
  751. var route = '';
  752. // Iterate over the tokens and create our regexp string.
  753. for (var i = 0; i < tokens.length; i++) {
  754. var token = tokens[i];
  755. if (typeof token === 'string') {
  756. route += escapeString(token);
  757. } else {
  758. var prefix = escapeString(token.prefix);
  759. var capture = '(?:' + token.pattern + ')';
  760. keys.push(token);
  761. if (token.repeat) {
  762. capture += '(?:' + prefix + capture + ')*';
  763. }
  764. if (token.optional) {
  765. if (!token.partial) {
  766. capture = '(?:' + prefix + '(' + capture + '))?';
  767. } else {
  768. capture = prefix + '(' + capture + ')?';
  769. }
  770. } else {
  771. capture = prefix + '(' + capture + ')';
  772. }
  773. route += capture;
  774. }
  775. }
  776. var delimiter = escapeString(options.delimiter || '/');
  777. var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
  778. // In non-strict mode we allow a slash at the end of match. If the path to
  779. // match already ends with a slash, we remove it for consistency. The slash
  780. // is valid at the end of a path match, not in the middle. This is important
  781. // in non-ending mode, where "/test/" shouldn't match "/test//route".
  782. if (!strict) {
  783. route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
  784. }
  785. if (end) {
  786. route += '$';
  787. } else {
  788. // In non-ending mode, we need the capturing groups to match as much as
  789. // possible by using a positive lookahead to the end or next path segment.
  790. route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
  791. }
  792. return attachKeys(new RegExp('^' + route, flags(options)), keys)
  793. }
  794. /**
  795. * Normalize the given path string, returning a regular expression.
  796. *
  797. * An empty array can be passed in for the keys, which will hold the
  798. * placeholder key descriptions. For example, using `/user/:id`, `keys` will
  799. * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
  800. *
  801. * @param {(string|RegExp|Array)} path
  802. * @param {(Array|Object)=} keys
  803. * @param {Object=} options
  804. * @return {!RegExp}
  805. */
  806. function pathToRegexp (path, keys, options) {
  807. if (!isarray(keys)) {
  808. options = /** @type {!Object} */ (keys || options);
  809. keys = [];
  810. }
  811. options = options || {};
  812. if (path instanceof RegExp) {
  813. return regexpToRegexp(path, /** @type {!Array} */ (keys))
  814. }
  815. if (isarray(path)) {
  816. return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
  817. }
  818. return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
  819. }
  820. pathToRegexp_1.parse = parse_1;
  821. pathToRegexp_1.compile = compile_1;
  822. pathToRegexp_1.tokensToFunction = tokensToFunction_1;
  823. pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
  824. /* */
  825. // $flow-disable-line
  826. const regexpCompileCache = Object.create(null);
  827. function fillParams (
  828. path,
  829. params,
  830. routeMsg
  831. ) {
  832. params = params || {};
  833. try {
  834. const filler =
  835. regexpCompileCache[path] ||
  836. (regexpCompileCache[path] = pathToRegexp_1.compile(path));
  837. // Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }}
  838. // and fix #3106 so that you can work with location descriptor object having params.pathMatch equal to empty string
  839. if (typeof params.pathMatch === 'string') params[0] = params.pathMatch;
  840. return filler(params, { pretty: true })
  841. } catch (e) {
  842. {
  843. // Fix #3072 no warn if `pathMatch` is string
  844. warn(typeof params.pathMatch === 'string', `missing param for ${routeMsg}: ${e.message}`);
  845. }
  846. return ''
  847. } finally {
  848. // delete the 0 if it was added
  849. delete params[0];
  850. }
  851. }
  852. /* */
  853. function normalizeLocation (
  854. raw,
  855. current,
  856. append,
  857. router
  858. ) {
  859. let next = typeof raw === 'string' ? { path: raw } : raw;
  860. // named target
  861. if (next._normalized) {
  862. return next
  863. } else if (next.name) {
  864. next = extend({}, raw);
  865. const params = next.params;
  866. if (params && typeof params === 'object') {
  867. next.params = extend({}, params);
  868. }
  869. return next
  870. }
  871. // relative params
  872. if (!next.path && next.params && current) {
  873. next = extend({}, next);
  874. next._normalized = true;
  875. const params = extend(extend({}, current.params), next.params);
  876. if (current.name) {
  877. next.name = current.name;
  878. next.params = params;
  879. } else if (current.matched.length) {
  880. const rawPath = current.matched[current.matched.length - 1].path;
  881. next.path = fillParams(rawPath, params, `path ${current.path}`);
  882. } else {
  883. warn(false, `relative params navigation requires a current route.`);
  884. }
  885. return next
  886. }
  887. const parsedPath = parsePath(next.path || '');
  888. const basePath = (current && current.path) || '/';
  889. const path = parsedPath.path
  890. ? resolvePath(parsedPath.path, basePath, append || next.append)
  891. : basePath;
  892. const query = resolveQuery(
  893. parsedPath.query,
  894. next.query,
  895. router && router.options.parseQuery
  896. );
  897. let hash = next.hash || parsedPath.hash;
  898. if (hash && hash.charAt(0) !== '#') {
  899. hash = `#${hash}`;
  900. }
  901. return {
  902. _normalized: true,
  903. path,
  904. query,
  905. hash
  906. }
  907. }
  908. /* */
  909. // work around weird flow bug
  910. const toTypes = [String, Object];
  911. const eventTypes = [String, Array];
  912. const noop = () => {};
  913. let warnedCustomSlot;
  914. let warnedTagProp;
  915. let warnedEventProp;
  916. var Link = {
  917. name: 'RouterLink',
  918. props: {
  919. to: {
  920. type: toTypes,
  921. required: true
  922. },
  923. tag: {
  924. type: String,
  925. default: 'a'
  926. },
  927. custom: Boolean,
  928. exact: Boolean,
  929. exactPath: Boolean,
  930. append: Boolean,
  931. replace: Boolean,
  932. activeClass: String,
  933. exactActiveClass: String,
  934. ariaCurrentValue: {
  935. type: String,
  936. default: 'page'
  937. },
  938. event: {
  939. type: eventTypes,
  940. default: 'click'
  941. }
  942. },
  943. render (h) {
  944. const router = this.$router;
  945. const current = this.$route;
  946. const { location, route, href } = router.resolve(
  947. this.to,
  948. current,
  949. this.append
  950. );
  951. const classes = {};
  952. const globalActiveClass = router.options.linkActiveClass;
  953. const globalExactActiveClass = router.options.linkExactActiveClass;
  954. // Support global empty active class
  955. const activeClassFallback =
  956. globalActiveClass == null ? 'router-link-active' : globalActiveClass;
  957. const exactActiveClassFallback =
  958. globalExactActiveClass == null
  959. ? 'router-link-exact-active'
  960. : globalExactActiveClass;
  961. const activeClass =
  962. this.activeClass == null ? activeClassFallback : this.activeClass;
  963. const exactActiveClass =
  964. this.exactActiveClass == null
  965. ? exactActiveClassFallback
  966. : this.exactActiveClass;
  967. const compareTarget = route.redirectedFrom
  968. ? createRoute(null, normalizeLocation(route.redirectedFrom), null, router)
  969. : route;
  970. classes[exactActiveClass] = isSameRoute(current, compareTarget, this.exactPath);
  971. classes[activeClass] = this.exact || this.exactPath
  972. ? classes[exactActiveClass]
  973. : isIncludedRoute(current, compareTarget);
  974. const ariaCurrentValue = classes[exactActiveClass] ? this.ariaCurrentValue : null;
  975. const handler = e => {
  976. if (guardEvent(e)) {
  977. if (this.replace) {
  978. router.replace(location, noop);
  979. } else {
  980. router.push(location, noop);
  981. }
  982. }
  983. };
  984. const on = { click: guardEvent };
  985. if (Array.isArray(this.event)) {
  986. this.event.forEach(e => {
  987. on[e] = handler;
  988. });
  989. } else {
  990. on[this.event] = handler;
  991. }
  992. const data = { class: classes };
  993. const scopedSlot =
  994. !this.$scopedSlots.$hasNormal &&
  995. this.$scopedSlots.default &&
  996. this.$scopedSlots.default({
  997. href,
  998. route,
  999. navigate: handler,
  1000. isActive: classes[activeClass],
  1001. isExactActive: classes[exactActiveClass]
  1002. });
  1003. if (scopedSlot) {
  1004. if (!this.custom) {
  1005. !warnedCustomSlot && warn(false, 'In Vue Router 4, the v-slot API will by default wrap its content with an <a> element. Use the custom prop to remove this warning:\n<router-link v-slot="{ navigate, href }" custom></router-link>\n');
  1006. warnedCustomSlot = true;
  1007. }
  1008. if (scopedSlot.length === 1) {
  1009. return scopedSlot[0]
  1010. } else if (scopedSlot.length > 1 || !scopedSlot.length) {
  1011. {
  1012. warn(
  1013. false,
  1014. `<router-link> with to="${
  1015. this.to
  1016. }" is trying to use a scoped slot but it didn't provide exactly one child. Wrapping the content with a span element.`
  1017. );
  1018. }
  1019. return scopedSlot.length === 0 ? h() : h('span', {}, scopedSlot)
  1020. }
  1021. }
  1022. {
  1023. if ('tag' in this.$options.propsData && !warnedTagProp) {
  1024. warn(
  1025. false,
  1026. `<router-link>'s tag prop is deprecated and has been removed in Vue Router 4. Use the v-slot API to remove this warning: https://next.router.vuejs.org/guide/migration/#removal-of-event-and-tag-props-in-router-link.`
  1027. );
  1028. warnedTagProp = true;
  1029. }
  1030. if ('event' in this.$options.propsData && !warnedEventProp) {
  1031. warn(
  1032. false,
  1033. `<router-link>'s event prop is deprecated and has been removed in Vue Router 4. Use the v-slot API to remove this warning: https://next.router.vuejs.org/guide/migration/#removal-of-event-and-tag-props-in-router-link.`
  1034. );
  1035. warnedEventProp = true;
  1036. }
  1037. }
  1038. if (this.tag === 'a') {
  1039. data.on = on;
  1040. data.attrs = { href, 'aria-current': ariaCurrentValue };
  1041. } else {
  1042. // find the first <a> child and apply listener and href
  1043. const a = findAnchor(this.$slots.default);
  1044. if (a) {
  1045. // in case the <a> is a static node
  1046. a.isStatic = false;
  1047. const aData = (a.data = extend({}, a.data));
  1048. aData.on = aData.on || {};
  1049. // transform existing events in both objects into arrays so we can push later
  1050. for (const event in aData.on) {
  1051. const handler = aData.on[event];
  1052. if (event in on) {
  1053. aData.on[event] = Array.isArray(handler) ? handler : [handler];
  1054. }
  1055. }
  1056. // append new listeners for router-link
  1057. for (const event in on) {
  1058. if (event in aData.on) {
  1059. // on[event] is always a function
  1060. aData.on[event].push(on[event]);
  1061. } else {
  1062. aData.on[event] = handler;
  1063. }
  1064. }
  1065. const aAttrs = (a.data.attrs = extend({}, a.data.attrs));
  1066. aAttrs.href = href;
  1067. aAttrs['aria-current'] = ariaCurrentValue;
  1068. } else {
  1069. // doesn't have <a> child, apply listener to self
  1070. data.on = on;
  1071. }
  1072. }
  1073. return h(this.tag, data, this.$slots.default)
  1074. }
  1075. };
  1076. function guardEvent (e) {
  1077. // don't redirect with control keys
  1078. if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return
  1079. // don't redirect when preventDefault called
  1080. if (e.defaultPrevented) return
  1081. // don't redirect on right click
  1082. if (e.button !== undefined && e.button !== 0) return
  1083. // don't redirect if `target="_blank"`
  1084. if (e.currentTarget && e.currentTarget.getAttribute) {
  1085. const target = e.currentTarget.getAttribute('target');
  1086. if (/\b_blank\b/i.test(target)) return
  1087. }
  1088. // this may be a Weex event which doesn't have this method
  1089. if (e.preventDefault) {
  1090. e.preventDefault();
  1091. }
  1092. return true
  1093. }
  1094. function findAnchor (children) {
  1095. if (children) {
  1096. let child;
  1097. for (let i = 0; i < children.length; i++) {
  1098. child = children[i];
  1099. if (child.tag === 'a') {
  1100. return child
  1101. }
  1102. if (child.children && (child = findAnchor(child.children))) {
  1103. return child
  1104. }
  1105. }
  1106. }
  1107. }
  1108. let _Vue;
  1109. function install (Vue) {
  1110. if (install.installed && _Vue === Vue) return
  1111. install.installed = true;
  1112. _Vue = Vue;
  1113. const isDef = v => v !== undefined;
  1114. const registerInstance = (vm, callVal) => {
  1115. let i = vm.$options._parentVnode;
  1116. if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
  1117. i(vm, callVal);
  1118. }
  1119. };
  1120. Vue.mixin({
  1121. beforeCreate () {
  1122. if (isDef(this.$options.router)) {
  1123. this._routerRoot = this;
  1124. this._router = this.$options.router;
  1125. this._router.init(this);
  1126. Vue.util.defineReactive(this, '_route', this._router.history.current);
  1127. } else {
  1128. this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
  1129. }
  1130. registerInstance(this, this);
  1131. },
  1132. destroyed () {
  1133. registerInstance(this);
  1134. }
  1135. });
  1136. Object.defineProperty(Vue.prototype, '$router', {
  1137. get () { return this._routerRoot._router }
  1138. });
  1139. Object.defineProperty(Vue.prototype, '$route', {
  1140. get () { return this._routerRoot._route }
  1141. });
  1142. Vue.component('RouterView', View);
  1143. Vue.component('RouterLink', Link);
  1144. const strats = Vue.config.optionMergeStrategies;
  1145. // use the same hook merging strategy for route hooks
  1146. strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
  1147. }
  1148. /* */
  1149. const inBrowser = typeof window !== 'undefined';
  1150. /* */
  1151. function createRouteMap (
  1152. routes,
  1153. oldPathList,
  1154. oldPathMap,
  1155. oldNameMap,
  1156. parentRoute
  1157. ) {
  1158. // the path list is used to control path matching priority
  1159. const pathList = oldPathList || [];
  1160. // $flow-disable-line
  1161. const pathMap = oldPathMap || Object.create(null);
  1162. // $flow-disable-line
  1163. const nameMap = oldNameMap || Object.create(null);
  1164. routes.forEach(route => {
  1165. addRouteRecord(pathList, pathMap, nameMap, route, parentRoute);
  1166. });
  1167. // ensure wildcard routes are always at the end
  1168. for (let i = 0, l = pathList.length; i < l; i++) {
  1169. if (pathList[i] === '*') {
  1170. pathList.push(pathList.splice(i, 1)[0]);
  1171. l--;
  1172. i--;
  1173. }
  1174. }
  1175. {
  1176. // warn if routes do not include leading slashes
  1177. const found = pathList
  1178. // check for missing leading slash
  1179. .filter(path => path && path.charAt(0) !== '*' && path.charAt(0) !== '/');
  1180. if (found.length > 0) {
  1181. const pathNames = found.map(path => `- ${path}`).join('\n');
  1182. warn(false, `Non-nested routes must include a leading slash character. Fix the following routes: \n${pathNames}`);
  1183. }
  1184. }
  1185. return {
  1186. pathList,
  1187. pathMap,
  1188. nameMap
  1189. }
  1190. }
  1191. function addRouteRecord (
  1192. pathList,
  1193. pathMap,
  1194. nameMap,
  1195. route,
  1196. parent,
  1197. matchAs
  1198. ) {
  1199. const { path, name } = route;
  1200. {
  1201. assert(path != null, `"path" is required in a route configuration.`);
  1202. assert(
  1203. typeof route.component !== 'string',
  1204. `route config "component" for path: ${String(
  1205. path || name
  1206. )} cannot be a ` + `string id. Use an actual component instead.`
  1207. );
  1208. warn(
  1209. // eslint-disable-next-line no-control-regex
  1210. !/[^\u0000-\u007F]+/.test(path),
  1211. `Route with path "${path}" contains unencoded characters, make sure ` +
  1212. `your path is correctly encoded before passing it to the router. Use ` +
  1213. `encodeURI to encode static segments of your path.`
  1214. );
  1215. }
  1216. const pathToRegexpOptions =
  1217. route.pathToRegexpOptions || {};
  1218. const normalizedPath = normalizePath(path, parent, pathToRegexpOptions.strict);
  1219. if (typeof route.caseSensitive === 'boolean') {
  1220. pathToRegexpOptions.sensitive = route.caseSensitive;
  1221. }
  1222. const record = {
  1223. path: normalizedPath,
  1224. regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
  1225. components: route.components || { default: route.component },
  1226. alias: route.alias
  1227. ? typeof route.alias === 'string'
  1228. ? [route.alias]
  1229. : route.alias
  1230. : [],
  1231. instances: {},
  1232. enteredCbs: {},
  1233. name,
  1234. parent,
  1235. matchAs,
  1236. redirect: route.redirect,
  1237. beforeEnter: route.beforeEnter,
  1238. meta: route.meta || {},
  1239. props:
  1240. route.props == null
  1241. ? {}
  1242. : route.components
  1243. ? route.props
  1244. : { default: route.props }
  1245. };
  1246. if (route.children) {
  1247. // Warn if route is named, does not redirect and has a default child route.
  1248. // If users navigate to this route by name, the default child will
  1249. // not be rendered (GH Issue #629)
  1250. {
  1251. if (
  1252. route.name &&
  1253. !route.redirect &&
  1254. route.children.some(child => /^\/?$/.test(child.path))
  1255. ) {
  1256. warn(
  1257. false,
  1258. `Named Route '${route.name}' has a default child route. ` +
  1259. `When navigating to this named route (:to="{name: '${
  1260. route.name
  1261. }'"), ` +
  1262. `the default child route will not be rendered. Remove the name from ` +
  1263. `this route and use the name of the default child route for named ` +
  1264. `links instead.`
  1265. );
  1266. }
  1267. }
  1268. route.children.forEach(child => {
  1269. const childMatchAs = matchAs
  1270. ? cleanPath(`${matchAs}/${child.path}`)
  1271. : undefined;
  1272. addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
  1273. });
  1274. }
  1275. if (!pathMap[record.path]) {
  1276. pathList.push(record.path);
  1277. pathMap[record.path] = record;
  1278. }
  1279. if (route.alias !== undefined) {
  1280. const aliases = Array.isArray(route.alias) ? route.alias : [route.alias];
  1281. for (let i = 0; i < aliases.length; ++i) {
  1282. const alias = aliases[i];
  1283. if (alias === path) {
  1284. warn(
  1285. false,
  1286. `Found an alias with the same value as the path: "${path}". You have to remove that alias. It will be ignored in development.`
  1287. );
  1288. // skip in dev to make it work
  1289. continue
  1290. }
  1291. const aliasRoute = {
  1292. path: alias,
  1293. children: route.children
  1294. };
  1295. addRouteRecord(
  1296. pathList,
  1297. pathMap,
  1298. nameMap,
  1299. aliasRoute,
  1300. parent,
  1301. record.path || '/' // matchAs
  1302. );
  1303. }
  1304. }
  1305. if (name) {
  1306. if (!nameMap[name]) {
  1307. nameMap[name] = record;
  1308. } else if (!matchAs) {
  1309. warn(
  1310. false,
  1311. `Duplicate named routes definition: ` +
  1312. `{ name: "${name}", path: "${record.path}" }`
  1313. );
  1314. }
  1315. }
  1316. }
  1317. function compileRouteRegex (
  1318. path,
  1319. pathToRegexpOptions
  1320. ) {
  1321. const regex = pathToRegexp_1(path, [], pathToRegexpOptions);
  1322. {
  1323. const keys = Object.create(null);
  1324. regex.keys.forEach(key => {
  1325. warn(
  1326. !keys[key.name],
  1327. `Duplicate param keys in route with path: "${path}"`
  1328. );
  1329. keys[key.name] = true;
  1330. });
  1331. }
  1332. return regex
  1333. }
  1334. function normalizePath (
  1335. path,
  1336. parent,
  1337. strict
  1338. ) {
  1339. if (!strict) path = path.replace(/\/$/, '');
  1340. if (path[0] === '/') return path
  1341. if (parent == null) return path
  1342. return cleanPath(`${parent.path}/${path}`)
  1343. }
  1344. /* */
  1345. function createMatcher (
  1346. routes,
  1347. router
  1348. ) {
  1349. const { pathList, pathMap, nameMap } = createRouteMap(routes);
  1350. function addRoutes (routes) {
  1351. createRouteMap(routes, pathList, pathMap, nameMap);
  1352. }
  1353. function addRoute (parentOrRoute, route) {
  1354. const parent = (typeof parentOrRoute !== 'object') ? nameMap[parentOrRoute] : undefined;
  1355. // $flow-disable-line
  1356. createRouteMap([route || parentOrRoute], pathList, pathMap, nameMap, parent);
  1357. // add aliases of parent
  1358. if (parent && parent.alias.length) {
  1359. createRouteMap(
  1360. // $flow-disable-line route is defined if parent is
  1361. parent.alias.map(alias => ({ path: alias, children: [route] })),
  1362. pathList,
  1363. pathMap,
  1364. nameMap,
  1365. parent
  1366. );
  1367. }
  1368. }
  1369. function getRoutes () {
  1370. return pathList.map(path => pathMap[path])
  1371. }
  1372. function match (
  1373. raw,
  1374. currentRoute,
  1375. redirectedFrom
  1376. ) {
  1377. const location = normalizeLocation(raw, currentRoute, false, router);
  1378. const { name } = location;
  1379. if (name) {
  1380. const record = nameMap[name];
  1381. {
  1382. warn(record, `Route with name '${name}' does not exist`);
  1383. }
  1384. if (!record) return _createRoute(null, location)
  1385. const paramNames = record.regex.keys
  1386. .filter(key => !key.optional)
  1387. .map(key => key.name);
  1388. if (typeof location.params !== 'object') {
  1389. location.params = {};
  1390. }
  1391. if (currentRoute && typeof currentRoute.params === 'object') {
  1392. for (const key in currentRoute.params) {
  1393. if (!(key in location.params) && paramNames.indexOf(key) > -1) {
  1394. location.params[key] = currentRoute.params[key];
  1395. }
  1396. }
  1397. }
  1398. location.path = fillParams(record.path, location.params, `named route "${name}"`);
  1399. return _createRoute(record, location, redirectedFrom)
  1400. } else if (location.path) {
  1401. location.params = {};
  1402. for (let i = 0; i < pathList.length; i++) {
  1403. const path = pathList[i];
  1404. const record = pathMap[path];
  1405. if (matchRoute(record.regex, location.path, location.params)) {
  1406. return _createRoute(record, location, redirectedFrom)
  1407. }
  1408. }
  1409. }
  1410. // no match
  1411. return _createRoute(null, location)
  1412. }
  1413. function redirect (
  1414. record,
  1415. location
  1416. ) {
  1417. const originalRedirect = record.redirect;
  1418. let redirect = typeof originalRedirect === 'function'
  1419. ? originalRedirect(createRoute(record, location, null, router))
  1420. : originalRedirect;
  1421. if (typeof redirect === 'string') {
  1422. redirect = { path: redirect };
  1423. }
  1424. if (!redirect || typeof redirect !== 'object') {
  1425. {
  1426. warn(
  1427. false, `invalid redirect option: ${JSON.stringify(redirect)}`
  1428. );
  1429. }
  1430. return _createRoute(null, location)
  1431. }
  1432. const re = redirect;
  1433. const { name, path } = re;
  1434. let { query, hash, params } = location;
  1435. query = re.hasOwnProperty('query') ? re.query : query;
  1436. hash = re.hasOwnProperty('hash') ? re.hash : hash;
  1437. params = re.hasOwnProperty('params') ? re.params : params;
  1438. if (name) {
  1439. // resolved named direct
  1440. const targetRecord = nameMap[name];
  1441. {
  1442. assert(targetRecord, `redirect failed: named route "${name}" not found.`);
  1443. }
  1444. return match({
  1445. _normalized: true,
  1446. name,
  1447. query,
  1448. hash,
  1449. params
  1450. }, undefined, location)
  1451. } else if (path) {
  1452. // 1. resolve relative redirect
  1453. const rawPath = resolveRecordPath(path, record);
  1454. // 2. resolve params
  1455. const resolvedPath = fillParams(rawPath, params, `redirect route with path "${rawPath}"`);
  1456. // 3. rematch with existing query and hash
  1457. return match({
  1458. _normalized: true,
  1459. path: resolvedPath,
  1460. query,
  1461. hash
  1462. }, undefined, location)
  1463. } else {
  1464. {
  1465. warn(false, `invalid redirect option: ${JSON.stringify(redirect)}`);
  1466. }
  1467. return _createRoute(null, location)
  1468. }
  1469. }
  1470. function alias (
  1471. record,
  1472. location,
  1473. matchAs
  1474. ) {
  1475. const aliasedPath = fillParams(matchAs, location.params, `aliased route with path "${matchAs}"`);
  1476. const aliasedMatch = match({
  1477. _normalized: true,
  1478. path: aliasedPath
  1479. });
  1480. if (aliasedMatch) {
  1481. const matched = aliasedMatch.matched;
  1482. const aliasedRecord = matched[matched.length - 1];
  1483. location.params = aliasedMatch.params;
  1484. return _createRoute(aliasedRecord, location)
  1485. }
  1486. return _createRoute(null, location)
  1487. }
  1488. function _createRoute (
  1489. record,
  1490. location,
  1491. redirectedFrom
  1492. ) {
  1493. if (record && record.redirect) {
  1494. return redirect(record, redirectedFrom || location)
  1495. }
  1496. if (record && record.matchAs) {
  1497. return alias(record, location, record.matchAs)
  1498. }
  1499. return createRoute(record, location, redirectedFrom, router)
  1500. }
  1501. return {
  1502. match,
  1503. addRoute,
  1504. getRoutes,
  1505. addRoutes
  1506. }
  1507. }
  1508. function matchRoute (
  1509. regex,
  1510. path,
  1511. params
  1512. ) {
  1513. const m = path.match(regex);
  1514. if (!m) {
  1515. return false
  1516. } else if (!params) {
  1517. return true
  1518. }
  1519. for (let i = 1, len = m.length; i < len; ++i) {
  1520. const key = regex.keys[i - 1];
  1521. if (key) {
  1522. // Fix #1994: using * with props: true generates a param named 0
  1523. params[key.name || 'pathMatch'] = typeof m[i] === 'string' ? decode(m[i]) : m[i];
  1524. }
  1525. }
  1526. return true
  1527. }
  1528. function resolveRecordPath (path, record) {
  1529. return resolvePath(path, record.parent ? record.parent.path : '/', true)
  1530. }
  1531. /* */
  1532. // use User Timing api (if present) for more accurate key precision
  1533. const Time =
  1534. inBrowser && window.performance && window.performance.now
  1535. ? window.performance
  1536. : Date;
  1537. function genStateKey () {
  1538. return Time.now().toFixed(3)
  1539. }
  1540. let _key = genStateKey();
  1541. function getStateKey () {
  1542. return _key
  1543. }
  1544. function setStateKey (key) {
  1545. return (_key = key)
  1546. }
  1547. /* */
  1548. const positionStore = Object.create(null);
  1549. function setupScroll () {
  1550. // Prevent browser scroll behavior on History popstate
  1551. if ('scrollRestoration' in window.history) {
  1552. window.history.scrollRestoration = 'manual';
  1553. }
  1554. // Fix for #1585 for Firefox
  1555. // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
  1556. // Fix for #2774 Support for apps loaded from Windows file shares not mapped to network drives: replaced location.origin with
  1557. // window.location.protocol + '//' + window.location.host
  1558. // location.host contains the port and location.hostname doesn't
  1559. const protocolAndPath = window.location.protocol + '//' + window.location.host;
  1560. const absolutePath = window.location.href.replace(protocolAndPath, '');
  1561. // preserve existing history state as it could be overriden by the user
  1562. const stateCopy = extend({}, window.history.state);
  1563. stateCopy.key = getStateKey();
  1564. window.history.replaceState(stateCopy, '', absolutePath);
  1565. window.addEventListener('popstate', handlePopState);
  1566. return () => {
  1567. window.removeEventListener('popstate', handlePopState);
  1568. }
  1569. }
  1570. function handleScroll (
  1571. router,
  1572. to,
  1573. from,
  1574. isPop
  1575. ) {
  1576. if (!router.app) {
  1577. return
  1578. }
  1579. const behavior = router.options.scrollBehavior;
  1580. if (!behavior) {
  1581. return
  1582. }
  1583. {
  1584. assert(typeof behavior === 'function', `scrollBehavior must be a function`);
  1585. }
  1586. // wait until re-render finishes before scrolling
  1587. router.app.$nextTick(() => {
  1588. const position = getScrollPosition();
  1589. const shouldScroll = behavior.call(
  1590. router,
  1591. to,
  1592. from,
  1593. isPop ? position : null
  1594. );
  1595. if (!shouldScroll) {
  1596. return
  1597. }
  1598. if (typeof shouldScroll.then === 'function') {
  1599. shouldScroll
  1600. .then(shouldScroll => {
  1601. scrollToPosition((shouldScroll), position);
  1602. })
  1603. .catch(err => {
  1604. {
  1605. assert(false, err.toString());
  1606. }
  1607. });
  1608. } else {
  1609. scrollToPosition(shouldScroll, position);
  1610. }
  1611. });
  1612. }
  1613. function saveScrollPosition () {
  1614. const key = getStateKey();
  1615. if (key) {
  1616. positionStore[key] = {
  1617. x: window.pageXOffset,
  1618. y: window.pageYOffset
  1619. };
  1620. }
  1621. }
  1622. function handlePopState (e) {
  1623. saveScrollPosition();
  1624. if (e.state && e.state.key) {
  1625. setStateKey(e.state.key);
  1626. }
  1627. }
  1628. function getScrollPosition () {
  1629. const key = getStateKey();
  1630. if (key) {
  1631. return positionStore[key]
  1632. }
  1633. }
  1634. function getElementPosition (el, offset) {
  1635. const docEl = document.documentElement;
  1636. const docRect = docEl.getBoundingClientRect();
  1637. const elRect = el.getBoundingClientRect();
  1638. return {
  1639. x: elRect.left - docRect.left - offset.x,
  1640. y: elRect.top - docRect.top - offset.y
  1641. }
  1642. }
  1643. function isValidPosition (obj) {
  1644. return isNumber(obj.x) || isNumber(obj.y)
  1645. }
  1646. function normalizePosition (obj) {
  1647. return {
  1648. x: isNumber(obj.x) ? obj.x : window.pageXOffset,
  1649. y: isNumber(obj.y) ? obj.y : window.pageYOffset
  1650. }
  1651. }
  1652. function normalizeOffset (obj) {
  1653. return {
  1654. x: isNumber(obj.x) ? obj.x : 0,
  1655. y: isNumber(obj.y) ? obj.y : 0
  1656. }
  1657. }
  1658. function isNumber (v) {
  1659. return typeof v === 'number'
  1660. }
  1661. const hashStartsWithNumberRE = /^#\d/;
  1662. function scrollToPosition (shouldScroll, position) {
  1663. const isObject = typeof shouldScroll === 'object';
  1664. if (isObject && typeof shouldScroll.selector === 'string') {
  1665. // getElementById would still fail if the selector contains a more complicated query like #main[data-attr]
  1666. // but at the same time, it doesn't make much sense to select an element with an id and an extra selector
  1667. const el = hashStartsWithNumberRE.test(shouldScroll.selector) // $flow-disable-line
  1668. ? document.getElementById(shouldScroll.selector.slice(1)) // $flow-disable-line
  1669. : document.querySelector(shouldScroll.selector);
  1670. if (el) {
  1671. let offset =
  1672. shouldScroll.offset && typeof shouldScroll.offset === 'object'
  1673. ? shouldScroll.offset
  1674. : {};
  1675. offset = normalizeOffset(offset);
  1676. position = getElementPosition(el, offset);
  1677. } else if (isValidPosition(shouldScroll)) {
  1678. position = normalizePosition(shouldScroll);
  1679. }
  1680. } else if (isObject && isValidPosition(shouldScroll)) {
  1681. position = normalizePosition(shouldScroll);
  1682. }
  1683. if (position) {
  1684. // $flow-disable-line
  1685. if ('scrollBehavior' in document.documentElement.style) {
  1686. window.scrollTo({
  1687. left: position.x,
  1688. top: position.y,
  1689. // $flow-disable-line
  1690. behavior: shouldScroll.behavior
  1691. });
  1692. } else {
  1693. window.scrollTo(position.x, position.y);
  1694. }
  1695. }
  1696. }
  1697. /* */
  1698. const supportsPushState =
  1699. inBrowser &&
  1700. (fun