Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vue-router.esm.browser.js 62KB

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