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.js 64KB

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