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 66KB

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