vue-router.js 64 KB

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