vue-router.common.js 66 KB

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