Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vue-router.esm.js 66KB

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