vue-router.common.js 64 KB

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