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

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