vue-router.js 55 KB

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