vue-router.js 66 KB

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