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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618
  1. /*!
  2. * vue-router v3.0.2
  3. * (c) 2018 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 (process.env.NODE_ENV !== '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 (var 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: function render (_, ref) {
  36. var props = ref.props;
  37. var children = ref.children;
  38. var parent = ref.parent;
  39. var data = ref.data;
  40. // used by devtools to display a router-view badge
  41. data.routerView = true;
  42. // directly use parent context's createElement() function
  43. // so that components rendered by router-view can resolve named slots
  44. var h = parent.$createElement;
  45. var name = props.name;
  46. var route = parent.$route;
  47. var cache = parent._routerViewCache || (parent._routerViewCache = {});
  48. // determine current view depth, also check to see if the tree
  49. // has been toggled inactive but kept-alive.
  50. var depth = 0;
  51. var inactive = false;
  52. while (parent && parent._routerRoot !== parent) {
  53. if (parent.$vnode && parent.$vnode.data.routerView) {
  54. depth++;
  55. }
  56. if (parent._inactive) {
  57. inactive = true;
  58. }
  59. parent = parent.$parent;
  60. }
  61. data.routerViewDepth = depth;
  62. // render previous view if the tree is inactive and kept-alive
  63. if (inactive) {
  64. return h(cache[name], data, children)
  65. }
  66. var matched = route.matched[depth];
  67. // render empty node if no matched route
  68. if (!matched) {
  69. cache[name] = null;
  70. return h()
  71. }
  72. var component = cache[name] = matched.components[name];
  73. // attach instance registration hook
  74. // this will be called in the instance's injected lifecycle hooks
  75. data.registerRouteInstance = function (vm, val) {
  76. // val could be undefined for unregistration
  77. var current = matched.instances[name];
  78. if (
  79. (val && current !== vm) ||
  80. (!val && current === vm)
  81. ) {
  82. matched.instances[name] = val;
  83. }
  84. }
  85. // also register instance in prepatch hook
  86. // in case the same component instance is reused across different routes
  87. ;(data.hook || (data.hook = {})).prepatch = function (_, vnode) {
  88. matched.instances[name] = vnode.componentInstance;
  89. };
  90. // resolve props
  91. var propsToPass = data.props = resolveProps(route, matched.props && matched.props[name]);
  92. if (propsToPass) {
  93. // clone to prevent mutation
  94. propsToPass = data.props = extend({}, propsToPass);
  95. // pass non-declared props as attrs
  96. var attrs = data.attrs = data.attrs || {};
  97. for (var key in propsToPass) {
  98. if (!component.props || !(key in component.props)) {
  99. attrs[key] = propsToPass[key];
  100. delete propsToPass[key];
  101. }
  102. }
  103. }
  104. return h(component, data, children)
  105. }
  106. }
  107. function resolveProps (route, config) {
  108. switch (typeof config) {
  109. case 'undefined':
  110. return
  111. case 'object':
  112. return config
  113. case 'function':
  114. return config(route)
  115. case 'boolean':
  116. return config ? route.params : undefined
  117. default:
  118. if (process.env.NODE_ENV !== 'production') {
  119. warn(
  120. false,
  121. "props in \"" + (route.path) + "\" is a " + (typeof config) + ", " +
  122. "expecting an object, function or boolean."
  123. );
  124. }
  125. }
  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: 'RouterLink',
  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 aData = a.data = extend({}, a.data);
  412. aData.on = on;
  413. var aAttrs = a.data.attrs = extend({}, a.data.attrs);
  414. aAttrs.href = href;
  415. } else {
  416. // doesn't have <a> child, apply listener to self
  417. data.on = on;
  418. }
  419. }
  420. return h(this.tag, data, this.$slots.default)
  421. }
  422. }
  423. function guardEvent (e) {
  424. // don't redirect with control keys
  425. if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return }
  426. // don't redirect when preventDefault called
  427. if (e.defaultPrevented) { return }
  428. // don't redirect on right click
  429. if (e.button !== undefined && e.button !== 0) { return }
  430. // don't redirect if `target="_blank"`
  431. if (e.currentTarget && e.currentTarget.getAttribute) {
  432. var target = e.currentTarget.getAttribute('target');
  433. if (/\b_blank\b/i.test(target)) { return }
  434. }
  435. // this may be a Weex event which doesn't have this method
  436. if (e.preventDefault) {
  437. e.preventDefault();
  438. }
  439. return true
  440. }
  441. function findAnchor (children) {
  442. if (children) {
  443. var child;
  444. for (var i = 0; i < children.length; i++) {
  445. child = children[i];
  446. if (child.tag === 'a') {
  447. return child
  448. }
  449. if (child.children && (child = findAnchor(child.children))) {
  450. return child
  451. }
  452. }
  453. }
  454. }
  455. var _Vue;
  456. function install (Vue) {
  457. if (install.installed && _Vue === Vue) { return }
  458. install.installed = true;
  459. _Vue = Vue;
  460. var isDef = function (v) { return v !== undefined; };
  461. var registerInstance = function (vm, callVal) {
  462. var i = vm.$options._parentVnode;
  463. if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
  464. i(vm, callVal);
  465. }
  466. };
  467. Vue.mixin({
  468. beforeCreate: function beforeCreate () {
  469. if (isDef(this.$options.router)) {
  470. this._routerRoot = this;
  471. this._router = this.$options.router;
  472. this._router.init(this);
  473. Vue.util.defineReactive(this, '_route', this._router.history.current);
  474. } else {
  475. this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
  476. }
  477. registerInstance(this, this);
  478. },
  479. destroyed: function destroyed () {
  480. registerInstance(this);
  481. }
  482. });
  483. Object.defineProperty(Vue.prototype, '$router', {
  484. get: function get () { return this._routerRoot._router }
  485. });
  486. Object.defineProperty(Vue.prototype, '$route', {
  487. get: function get () { return this._routerRoot._route }
  488. });
  489. Vue.component('RouterView', View);
  490. Vue.component('RouterLink', Link);
  491. var strats = Vue.config.optionMergeStrategies;
  492. // use the same hook merging strategy for route hooks
  493. strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
  494. }
  495. /* */
  496. var inBrowser = typeof window !== 'undefined';
  497. /* */
  498. function resolvePath (
  499. relative,
  500. base,
  501. append
  502. ) {
  503. var firstChar = relative.charAt(0);
  504. if (firstChar === '/') {
  505. return relative
  506. }
  507. if (firstChar === '?' || firstChar === '#') {
  508. return base + relative
  509. }
  510. var stack = base.split('/');
  511. // remove trailing segment if:
  512. // - not appending
  513. // - appending to trailing slash (last segment is empty)
  514. if (!append || !stack[stack.length - 1]) {
  515. stack.pop();
  516. }
  517. // resolve relative path
  518. var segments = relative.replace(/^\//, '').split('/');
  519. for (var i = 0; i < segments.length; i++) {
  520. var segment = segments[i];
  521. if (segment === '..') {
  522. stack.pop();
  523. } else if (segment !== '.') {
  524. stack.push(segment);
  525. }
  526. }
  527. // ensure leading slash
  528. if (stack[0] !== '') {
  529. stack.unshift('');
  530. }
  531. return stack.join('/')
  532. }
  533. function parsePath (path) {
  534. var hash = '';
  535. var query = '';
  536. var hashIndex = path.indexOf('#');
  537. if (hashIndex >= 0) {
  538. hash = path.slice(hashIndex);
  539. path = path.slice(0, hashIndex);
  540. }
  541. var queryIndex = path.indexOf('?');
  542. if (queryIndex >= 0) {
  543. query = path.slice(queryIndex + 1);
  544. path = path.slice(0, queryIndex);
  545. }
  546. return {
  547. path: path,
  548. query: query,
  549. hash: hash
  550. }
  551. }
  552. function cleanPath (path) {
  553. return path.replace(/\/\//g, '/')
  554. }
  555. var isarray = Array.isArray || function (arr) {
  556. return Object.prototype.toString.call(arr) == '[object Array]';
  557. };
  558. /**
  559. * Expose `pathToRegexp`.
  560. */
  561. var pathToRegexp_1 = pathToRegexp;
  562. var parse_1 = parse;
  563. var compile_1 = compile;
  564. var tokensToFunction_1 = tokensToFunction;
  565. var tokensToRegExp_1 = tokensToRegExp;
  566. /**
  567. * The main path matching regexp utility.
  568. *
  569. * @type {RegExp}
  570. */
  571. var PATH_REGEXP = new RegExp([
  572. // Match escaped characters that would otherwise appear in future matches.
  573. // This allows the user to escape special characters that won't transform.
  574. '(\\\\.)',
  575. // Match Express-style parameters and un-named parameters with a prefix
  576. // and optional suffixes. Matches appear as:
  577. //
  578. // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
  579. // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
  580. // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
  581. '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
  582. ].join('|'), 'g');
  583. /**
  584. * Parse a string for the raw tokens.
  585. *
  586. * @param {string} str
  587. * @param {Object=} options
  588. * @return {!Array}
  589. */
  590. function parse (str, options) {
  591. var tokens = [];
  592. var key = 0;
  593. var index = 0;
  594. var path = '';
  595. var defaultDelimiter = options && options.delimiter || '/';
  596. var res;
  597. while ((res = PATH_REGEXP.exec(str)) != null) {
  598. var m = res[0];
  599. var escaped = res[1];
  600. var offset = res.index;
  601. path += str.slice(index, offset);
  602. index = offset + m.length;
  603. // Ignore already escaped sequences.
  604. if (escaped) {
  605. path += escaped[1];
  606. continue
  607. }
  608. var next = str[index];
  609. var prefix = res[2];
  610. var name = res[3];
  611. var capture = res[4];
  612. var group = res[5];
  613. var modifier = res[6];
  614. var asterisk = res[7];
  615. // Push the current path onto the tokens.
  616. if (path) {
  617. tokens.push(path);
  618. path = '';
  619. }
  620. var partial = prefix != null && next != null && next !== prefix;
  621. var repeat = modifier === '+' || modifier === '*';
  622. var optional = modifier === '?' || modifier === '*';
  623. var delimiter = res[2] || defaultDelimiter;
  624. var pattern = capture || group;
  625. tokens.push({
  626. name: name || key++,
  627. prefix: prefix || '',
  628. delimiter: delimiter,
  629. optional: optional,
  630. repeat: repeat,
  631. partial: partial,
  632. asterisk: !!asterisk,
  633. pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
  634. });
  635. }
  636. // Match any characters still remaining.
  637. if (index < str.length) {
  638. path += str.substr(index);
  639. }
  640. // If the path exists, push it onto the end.
  641. if (path) {
  642. tokens.push(path);
  643. }
  644. return tokens
  645. }
  646. /**
  647. * Compile a string to a template function for the path.
  648. *
  649. * @param {string} str
  650. * @param {Object=} options
  651. * @return {!function(Object=, Object=)}
  652. */
  653. function compile (str, options) {
  654. return tokensToFunction(parse(str, options))
  655. }
  656. /**
  657. * Prettier encoding of URI path segments.
  658. *
  659. * @param {string}
  660. * @return {string}
  661. */
  662. function encodeURIComponentPretty (str) {
  663. return encodeURI(str).replace(/[\/?#]/g, function (c) {
  664. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  665. })
  666. }
  667. /**
  668. * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
  669. *
  670. * @param {string}
  671. * @return {string}
  672. */
  673. function encodeAsterisk (str) {
  674. return encodeURI(str).replace(/[?#]/g, function (c) {
  675. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  676. })
  677. }
  678. /**
  679. * Expose a method for transforming tokens into the path function.
  680. */
  681. function tokensToFunction (tokens) {
  682. // Compile all the tokens into regexps.
  683. var matches = new Array(tokens.length);
  684. // Compile all the patterns before compilation.
  685. for (var i = 0; i < tokens.length; i++) {
  686. if (typeof tokens[i] === 'object') {
  687. matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
  688. }
  689. }
  690. return function (obj, opts) {
  691. var path = '';
  692. var data = obj || {};
  693. var options = opts || {};
  694. var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
  695. for (var i = 0; i < tokens.length; i++) {
  696. var token = tokens[i];
  697. if (typeof token === 'string') {
  698. path += token;
  699. continue
  700. }
  701. var value = data[token.name];
  702. var segment;
  703. if (value == null) {
  704. if (token.optional) {
  705. // Prepend partial segment prefixes.
  706. if (token.partial) {
  707. path += token.prefix;
  708. }
  709. continue
  710. } else {
  711. throw new TypeError('Expected "' + token.name + '" to be defined')
  712. }
  713. }
  714. if (isarray(value)) {
  715. if (!token.repeat) {
  716. throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
  717. }
  718. if (value.length === 0) {
  719. if (token.optional) {
  720. continue
  721. } else {
  722. throw new TypeError('Expected "' + token.name + '" to not be empty')
  723. }
  724. }
  725. for (var j = 0; j < value.length; j++) {
  726. segment = encode(value[j]);
  727. if (!matches[i].test(segment)) {
  728. throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
  729. }
  730. path += (j === 0 ? token.prefix : token.delimiter) + segment;
  731. }
  732. continue
  733. }
  734. segment = token.asterisk ? encodeAsterisk(value) : encode(value);
  735. if (!matches[i].test(segment)) {
  736. throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
  737. }
  738. path += token.prefix + segment;
  739. }
  740. return path
  741. }
  742. }
  743. /**
  744. * Escape a regular expression string.
  745. *
  746. * @param {string} str
  747. * @return {string}
  748. */
  749. function escapeString (str) {
  750. return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
  751. }
  752. /**
  753. * Escape the capturing group by escaping special characters and meaning.
  754. *
  755. * @param {string} group
  756. * @return {string}
  757. */
  758. function escapeGroup (group) {
  759. return group.replace(/([=!:$\/()])/g, '\\$1')
  760. }
  761. /**
  762. * Attach the keys as a property of the regexp.
  763. *
  764. * @param {!RegExp} re
  765. * @param {Array} keys
  766. * @return {!RegExp}
  767. */
  768. function attachKeys (re, keys) {
  769. re.keys = keys;
  770. return re
  771. }
  772. /**
  773. * Get the flags for a regexp from the options.
  774. *
  775. * @param {Object} options
  776. * @return {string}
  777. */
  778. function flags (options) {
  779. return options.sensitive ? '' : 'i'
  780. }
  781. /**
  782. * Pull out keys from a regexp.
  783. *
  784. * @param {!RegExp} path
  785. * @param {!Array} keys
  786. * @return {!RegExp}
  787. */
  788. function regexpToRegexp (path, keys) {
  789. // Use a negative lookahead to match only capturing groups.
  790. var groups = path.source.match(/\((?!\?)/g);
  791. if (groups) {
  792. for (var i = 0; i < groups.length; i++) {
  793. keys.push({
  794. name: i,
  795. prefix: null,
  796. delimiter: null,
  797. optional: false,
  798. repeat: false,
  799. partial: false,
  800. asterisk: false,
  801. pattern: null
  802. });
  803. }
  804. }
  805. return attachKeys(path, keys)
  806. }
  807. /**
  808. * Transform an array into a regexp.
  809. *
  810. * @param {!Array} path
  811. * @param {Array} keys
  812. * @param {!Object} options
  813. * @return {!RegExp}
  814. */
  815. function arrayToRegexp (path, keys, options) {
  816. var parts = [];
  817. for (var i = 0; i < path.length; i++) {
  818. parts.push(pathToRegexp(path[i], keys, options).source);
  819. }
  820. var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
  821. return attachKeys(regexp, keys)
  822. }
  823. /**
  824. * Create a path regexp from string input.
  825. *
  826. * @param {string} path
  827. * @param {!Array} keys
  828. * @param {!Object} options
  829. * @return {!RegExp}
  830. */
  831. function stringToRegexp (path, keys, options) {
  832. return tokensToRegExp(parse(path, options), keys, options)
  833. }
  834. /**
  835. * Expose a function for taking tokens and returning a RegExp.
  836. *
  837. * @param {!Array} tokens
  838. * @param {(Array|Object)=} keys
  839. * @param {Object=} options
  840. * @return {!RegExp}
  841. */
  842. function tokensToRegExp (tokens, keys, options) {
  843. if (!isarray(keys)) {
  844. options = /** @type {!Object} */ (keys || options);
  845. keys = [];
  846. }
  847. options = options || {};
  848. var strict = options.strict;
  849. var end = options.end !== false;
  850. var route = '';
  851. // Iterate over the tokens and create our regexp string.
  852. for (var i = 0; i < tokens.length; i++) {
  853. var token = tokens[i];
  854. if (typeof token === 'string') {
  855. route += escapeString(token);
  856. } else {
  857. var prefix = escapeString(token.prefix);
  858. var capture = '(?:' + token.pattern + ')';
  859. keys.push(token);
  860. if (token.repeat) {
  861. capture += '(?:' + prefix + capture + ')*';
  862. }
  863. if (token.optional) {
  864. if (!token.partial) {
  865. capture = '(?:' + prefix + '(' + capture + '))?';
  866. } else {
  867. capture = prefix + '(' + capture + ')?';
  868. }
  869. } else {
  870. capture = prefix + '(' + capture + ')';
  871. }
  872. route += capture;
  873. }
  874. }
  875. var delimiter = escapeString(options.delimiter || '/');
  876. var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
  877. // In non-strict mode we allow a slash at the end of match. If the path to
  878. // match already ends with a slash, we remove it for consistency. The slash
  879. // is valid at the end of a path match, not in the middle. This is important
  880. // in non-ending mode, where "/test/" shouldn't match "/test//route".
  881. if (!strict) {
  882. route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
  883. }
  884. if (end) {
  885. route += '$';
  886. } else {
  887. // In non-ending mode, we need the capturing groups to match as much as
  888. // possible by using a positive lookahead to the end or next path segment.
  889. route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
  890. }
  891. return attachKeys(new RegExp('^' + route, flags(options)), keys)
  892. }
  893. /**
  894. * Normalize the given path string, returning a regular expression.
  895. *
  896. * An empty array can be passed in for the keys, which will hold the
  897. * placeholder key descriptions. For example, using `/user/:id`, `keys` will
  898. * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
  899. *
  900. * @param {(string|RegExp|Array)} path
  901. * @param {(Array|Object)=} keys
  902. * @param {Object=} options
  903. * @return {!RegExp}
  904. */
  905. function pathToRegexp (path, keys, options) {
  906. if (!isarray(keys)) {
  907. options = /** @type {!Object} */ (keys || options);
  908. keys = [];
  909. }
  910. options = options || {};
  911. if (path instanceof RegExp) {
  912. return regexpToRegexp(path, /** @type {!Array} */ (keys))
  913. }
  914. if (isarray(path)) {
  915. return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
  916. }
  917. return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
  918. }
  919. pathToRegexp_1.parse = parse_1;
  920. pathToRegexp_1.compile = compile_1;
  921. pathToRegexp_1.tokensToFunction = tokensToFunction_1;
  922. pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
  923. /* */
  924. // $flow-disable-line
  925. var regexpCompileCache = Object.create(null);
  926. function fillParams (
  927. path,
  928. params,
  929. routeMsg
  930. ) {
  931. try {
  932. var filler =
  933. regexpCompileCache[path] ||
  934. (regexpCompileCache[path] = pathToRegexp_1.compile(path));
  935. return filler(params || {}, { pretty: true })
  936. } catch (e) {
  937. if (process.env.NODE_ENV !== 'production') {
  938. warn(false, ("missing param for " + routeMsg + ": " + (e.message)));
  939. }
  940. return ''
  941. }
  942. }
  943. /* */
  944. function createRouteMap (
  945. routes,
  946. oldPathList,
  947. oldPathMap,
  948. oldNameMap
  949. ) {
  950. // the path list is used to control path matching priority
  951. var pathList = oldPathList || [];
  952. // $flow-disable-line
  953. var pathMap = oldPathMap || Object.create(null);
  954. // $flow-disable-line
  955. var nameMap = oldNameMap || Object.create(null);
  956. routes.forEach(function (route) {
  957. addRouteRecord(pathList, pathMap, nameMap, route);
  958. });
  959. // ensure wildcard routes are always at the end
  960. for (var i = 0, l = pathList.length; i < l; i++) {
  961. if (pathList[i] === '*') {
  962. pathList.push(pathList.splice(i, 1)[0]);
  963. l--;
  964. i--;
  965. }
  966. }
  967. return {
  968. pathList: pathList,
  969. pathMap: pathMap,
  970. nameMap: nameMap
  971. }
  972. }
  973. function addRouteRecord (
  974. pathList,
  975. pathMap,
  976. nameMap,
  977. route,
  978. parent,
  979. matchAs
  980. ) {
  981. var path = route.path;
  982. var name = route.name;
  983. if (process.env.NODE_ENV !== 'production') {
  984. assert(path != null, "\"path\" is required in a route configuration.");
  985. assert(
  986. typeof route.component !== 'string',
  987. "route config \"component\" for path: " + (String(path || name)) + " cannot be a " +
  988. "string id. Use an actual component instead."
  989. );
  990. }
  991. var pathToRegexpOptions = route.pathToRegexpOptions || {};
  992. var normalizedPath = normalizePath(
  993. path,
  994. parent,
  995. pathToRegexpOptions.strict
  996. );
  997. if (typeof route.caseSensitive === 'boolean') {
  998. pathToRegexpOptions.sensitive = route.caseSensitive;
  999. }
  1000. var record = {
  1001. path: normalizedPath,
  1002. regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
  1003. components: route.components || { default: route.component },
  1004. instances: {},
  1005. name: name,
  1006. parent: parent,
  1007. matchAs: matchAs,
  1008. redirect: route.redirect,
  1009. beforeEnter: route.beforeEnter,
  1010. meta: route.meta || {},
  1011. props: route.props == null
  1012. ? {}
  1013. : route.components
  1014. ? route.props
  1015. : { default: route.props }
  1016. };
  1017. if (route.children) {
  1018. // Warn if route is named, does not redirect and has a default child route.
  1019. // If users navigate to this route by name, the default child will
  1020. // not be rendered (GH Issue #629)
  1021. if (process.env.NODE_ENV !== 'production') {
  1022. if (route.name && !route.redirect && route.children.some(function (child) { return /^\/?$/.test(child.path); })) {
  1023. warn(
  1024. false,
  1025. "Named Route '" + (route.name) + "' has a default child route. " +
  1026. "When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " +
  1027. "the default child route will not be rendered. Remove the name from " +
  1028. "this route and use the name of the default child route for named " +
  1029. "links instead."
  1030. );
  1031. }
  1032. }
  1033. route.children.forEach(function (child) {
  1034. var childMatchAs = matchAs
  1035. ? cleanPath((matchAs + "/" + (child.path)))
  1036. : undefined;
  1037. addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
  1038. });
  1039. }
  1040. if (route.alias !== undefined) {
  1041. var aliases = Array.isArray(route.alias)
  1042. ? route.alias
  1043. : [route.alias];
  1044. aliases.forEach(function (alias) {
  1045. var aliasRoute = {
  1046. path: alias,
  1047. children: route.children
  1048. };
  1049. addRouteRecord(
  1050. pathList,
  1051. pathMap,
  1052. nameMap,
  1053. aliasRoute,
  1054. parent,
  1055. record.path || '/' // matchAs
  1056. );
  1057. });
  1058. }
  1059. if (!pathMap[record.path]) {
  1060. pathList.push(record.path);
  1061. pathMap[record.path] = record;
  1062. }
  1063. if (name) {
  1064. if (!nameMap[name]) {
  1065. nameMap[name] = record;
  1066. } else if (process.env.NODE_ENV !== 'production' && !matchAs) {
  1067. warn(
  1068. false,
  1069. "Duplicate named routes definition: " +
  1070. "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
  1071. );
  1072. }
  1073. }
  1074. }
  1075. function compileRouteRegex (path, pathToRegexpOptions) {
  1076. var regex = pathToRegexp_1(path, [], pathToRegexpOptions);
  1077. if (process.env.NODE_ENV !== 'production') {
  1078. var keys = Object.create(null);
  1079. regex.keys.forEach(function (key) {
  1080. warn(!keys[key.name], ("Duplicate param keys in route with path: \"" + path + "\""));
  1081. keys[key.name] = true;
  1082. });
  1083. }
  1084. return regex
  1085. }
  1086. function normalizePath (path, parent, strict) {
  1087. if (!strict) { path = path.replace(/\/$/, ''); }
  1088. if (path[0] === '/') { return path }
  1089. if (parent == null) { return path }
  1090. return cleanPath(((parent.path) + "/" + path))
  1091. }
  1092. /* */
  1093. function normalizeLocation (
  1094. raw,
  1095. current,
  1096. append,
  1097. router
  1098. ) {
  1099. var next = typeof raw === 'string' ? { path: raw } : raw;
  1100. // named target
  1101. if (next.name || next._normalized) {
  1102. return next
  1103. }
  1104. // relative params
  1105. if (!next.path && next.params && current) {
  1106. next = extend({}, next);
  1107. next._normalized = true;
  1108. var params = extend(extend({}, current.params), next.params);
  1109. if (current.name) {
  1110. next.name = current.name;
  1111. next.params = params;
  1112. } else if (current.matched.length) {
  1113. var rawPath = current.matched[current.matched.length - 1].path;
  1114. next.path = fillParams(rawPath, params, ("path " + (current.path)));
  1115. } else if (process.env.NODE_ENV !== 'production') {
  1116. warn(false, "relative params navigation requires a current route.");
  1117. }
  1118. return next
  1119. }
  1120. var parsedPath = parsePath(next.path || '');
  1121. var basePath = (current && current.path) || '/';
  1122. var path = parsedPath.path
  1123. ? resolvePath(parsedPath.path, basePath, append || next.append)
  1124. : basePath;
  1125. var query = resolveQuery(
  1126. parsedPath.query,
  1127. next.query,
  1128. router && router.options.parseQuery
  1129. );
  1130. var hash = next.hash || parsedPath.hash;
  1131. if (hash && hash.charAt(0) !== '#') {
  1132. hash = "#" + hash;
  1133. }
  1134. return {
  1135. _normalized: true,
  1136. path: path,
  1137. query: query,
  1138. hash: hash
  1139. }
  1140. }
  1141. /* */
  1142. function createMatcher (
  1143. routes,
  1144. router
  1145. ) {
  1146. var ref = createRouteMap(routes);
  1147. var pathList = ref.pathList;
  1148. var pathMap = ref.pathMap;
  1149. var nameMap = ref.nameMap;
  1150. function addRoutes (routes) {
  1151. createRouteMap(routes, pathList, pathMap, nameMap);
  1152. }
  1153. function match (
  1154. raw,
  1155. currentRoute,
  1156. redirectedFrom
  1157. ) {
  1158. var location = normalizeLocation(raw, currentRoute, false, router);
  1159. var name = location.name;
  1160. if (name) {
  1161. var record = nameMap[name];
  1162. if (process.env.NODE_ENV !== 'production') {
  1163. warn(record, ("Route with name '" + name + "' does not exist"));
  1164. }
  1165. if (!record) { return _createRoute(null, location) }
  1166. var paramNames = record.regex.keys
  1167. .filter(function (key) { return !key.optional; })
  1168. .map(function (key) { return key.name; });
  1169. if (typeof location.params !== 'object') {
  1170. location.params = {};
  1171. }
  1172. if (currentRoute && typeof currentRoute.params === 'object') {
  1173. for (var key in currentRoute.params) {
  1174. if (!(key in location.params) && paramNames.indexOf(key) > -1) {
  1175. location.params[key] = currentRoute.params[key];
  1176. }
  1177. }
  1178. }
  1179. if (record) {
  1180. location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
  1181. return _createRoute(record, location, redirectedFrom)
  1182. }
  1183. } else if (location.path) {
  1184. location.params = {};
  1185. for (var i = 0; i < pathList.length; i++) {
  1186. var path = pathList[i];
  1187. var record$1 = pathMap[path];
  1188. if (matchRoute(record$1.regex, location.path, location.params)) {
  1189. return _createRoute(record$1, location, redirectedFrom)
  1190. }
  1191. }
  1192. }
  1193. // no match
  1194. return _createRoute(null, location)
  1195. }
  1196. function redirect (
  1197. record,
  1198. location
  1199. ) {
  1200. var originalRedirect = record.redirect;
  1201. var redirect = typeof originalRedirect === 'function'
  1202. ? originalRedirect(createRoute(record, location, null, router))
  1203. : originalRedirect;
  1204. if (typeof redirect === 'string') {
  1205. redirect = { path: redirect };
  1206. }
  1207. if (!redirect || typeof redirect !== 'object') {
  1208. if (process.env.NODE_ENV !== 'production') {
  1209. warn(
  1210. false, ("invalid redirect option: " + (JSON.stringify(redirect)))
  1211. );
  1212. }
  1213. return _createRoute(null, location)
  1214. }
  1215. var re = redirect;
  1216. var name = re.name;
  1217. var path = re.path;
  1218. var query = location.query;
  1219. var hash = location.hash;
  1220. var params = location.params;
  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. var targetRecord = nameMap[name];
  1227. if (process.env.NODE_ENV !== 'production') {
  1228. assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
  1229. }
  1230. return match({
  1231. _normalized: true,
  1232. name: name,
  1233. query: query,
  1234. hash: hash,
  1235. params: params
  1236. }, undefined, location)
  1237. } else if (path) {
  1238. // 1. resolve relative redirect
  1239. var rawPath = resolveRecordPath(path, record);
  1240. // 2. resolve params
  1241. var 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: query,
  1247. hash: hash
  1248. }, undefined, location)
  1249. } else {
  1250. if (process.env.NODE_ENV !== 'production') {
  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. var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
  1262. var aliasedMatch = match({
  1263. _normalized: true,
  1264. path: aliasedPath
  1265. });
  1266. if (aliasedMatch) {
  1267. var matched = aliasedMatch.matched;
  1268. var 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: match,
  1289. addRoutes: addRoutes
  1290. }
  1291. }
  1292. function matchRoute (
  1293. regex,
  1294. path,
  1295. params
  1296. ) {
  1297. var m = path.match(regex);
  1298. if (!m) {
  1299. return false
  1300. } else if (!params) {
  1301. return true
  1302. }
  1303. for (var i = 1, len = m.length; i < len; ++i) {
  1304. var key = regex.keys[i - 1];
  1305. var 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. var 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', function (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. var behavior = router.options.scrollBehavior;
  1339. if (!behavior) {
  1340. return
  1341. }
  1342. if (process.env.NODE_ENV !== 'production') {
  1343. assert(typeof behavior === 'function', "scrollBehavior must be a function");
  1344. }
  1345. // wait until re-render finishes before scrolling
  1346. router.app.$nextTick(function () {
  1347. var position = getScrollPosition();
  1348. var shouldScroll = behavior.call(router, to, from, isPop ? position : null);
  1349. if (!shouldScroll) {
  1350. return
  1351. }
  1352. if (typeof shouldScroll.then === 'function') {
  1353. shouldScroll.then(function (shouldScroll) {
  1354. scrollToPosition((shouldScroll), position);
  1355. }).catch(function (err) {
  1356. if (process.env.NODE_ENV !== 'production') {
  1357. assert(false, err.toString());
  1358. }
  1359. });
  1360. } else {
  1361. scrollToPosition(shouldScroll, position);
  1362. }
  1363. });
  1364. }
  1365. function saveScrollPosition () {
  1366. var key = getStateKey();
  1367. if (key) {
  1368. positionStore[key] = {
  1369. x: window.pageXOffset,
  1370. y: window.pageYOffset
  1371. };
  1372. }
  1373. }
  1374. function getScrollPosition () {
  1375. var key = getStateKey();
  1376. if (key) {
  1377. return positionStore[key]
  1378. }
  1379. }
  1380. function getElementPosition (el, offset) {
  1381. var docEl = document.documentElement;
  1382. var docRect = docEl.getBoundingClientRect();
  1383. var 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. var isObject = typeof shouldScroll === 'object';
  1409. if (isObject && typeof shouldScroll.selector === 'string') {
  1410. var el = document.querySelector(shouldScroll.selector);
  1411. if (el) {
  1412. var 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. var supportsPushState = inBrowser && (function () {
  1427. var 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. var Time = inBrowser && window.performance && window.performance.now
  1440. ? window.performance
  1441. : Date;
  1442. var _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. var 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. var step = function (index) {
  1474. if (index >= queue.length) {
  1475. cb();
  1476. } else {
  1477. if (queue[index]) {
  1478. fn(queue[index], function () {
  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 function (to, from, next) {
  1491. var hasAsync = false;
  1492. var pending = 0;
  1493. var error = null;
  1494. flatMapComponents(matched, function (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. var resolve = once(function (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. var reject = once(function (reason) {
  1518. var msg = "Failed to resolve async component " + key + ": " + reason;
  1519. process.env.NODE_ENV !== 'production' && warn(false, msg);
  1520. if (!error) {
  1521. error = isError(reason)
  1522. ? reason
  1523. : new Error(msg);
  1524. next(error);
  1525. }
  1526. });
  1527. var 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. var 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(function (m) {
  1554. return Object.keys(m.components).map(function (key) { return 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. var 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. var called = false;
  1576. return function () {
  1577. var args = [], len = arguments.length;
  1578. while ( len-- ) args[ len ] = arguments[ len ];
  1579. if (called) { return }
  1580. called = true;
  1581. return fn.apply(this, args)
  1582. }
  1583. }
  1584. /* */
  1585. var History = function History (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. History.prototype.listen = function listen (cb) {
  1597. this.cb = cb;
  1598. };
  1599. History.prototype.onReady = function 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. History.prototype.onError = function onError (errorCb) {
  1610. this.errorCbs.push(errorCb);
  1611. };
  1612. History.prototype.transitionTo = function transitionTo (location, onComplete, onAbort) {
  1613. var this$1 = this;
  1614. var route = this.router.match(location, this.current);
  1615. this.confirmTransition(route, function () {
  1616. this$1.updateRoute(route);
  1617. onComplete && onComplete(route);
  1618. this$1.ensureURL();
  1619. // fire ready cbs once
  1620. if (!this$1.ready) {
  1621. this$1.ready = true;
  1622. this$1.readyCbs.forEach(function (cb) { cb(route); });
  1623. }
  1624. }, function (err) {
  1625. if (onAbort) {
  1626. onAbort(err);
  1627. }
  1628. if (err && !this$1.ready) {
  1629. this$1.ready = true;
  1630. this$1.readyErrorCbs.forEach(function (cb) { cb(err); });
  1631. }
  1632. });
  1633. };
  1634. History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) {
  1635. var this$1 = this;
  1636. var current = this.current;
  1637. var abort = function (err) {
  1638. if (isError(err)) {
  1639. if (this$1.errorCbs.length) {
  1640. this$1.errorCbs.forEach(function (cb) { cb(err); });
  1641. } else {
  1642. warn(false, 'uncaught error during route navigation:');
  1643. console.error(err);
  1644. }
  1645. }
  1646. onAbort && onAbort(err);
  1647. };
  1648. if (
  1649. isSameRoute(route, current) &&
  1650. // in the case the route map has been dynamically appended to
  1651. route.matched.length === current.matched.length
  1652. ) {
  1653. this.ensureURL();
  1654. return abort()
  1655. }
  1656. var ref = resolveQueue(this.current.matched, route.matched);
  1657. var updated = ref.updated;
  1658. var deactivated = ref.deactivated;
  1659. var activated = ref.activated;
  1660. var queue = [].concat(
  1661. // in-component leave guards
  1662. extractLeaveGuards(deactivated),
  1663. // global before hooks
  1664. this.router.beforeHooks,
  1665. // in-component update hooks
  1666. extractUpdateHooks(updated),
  1667. // in-config enter guards
  1668. activated.map(function (m) { return m.beforeEnter; }),
  1669. // async components
  1670. resolveAsyncComponents(activated)
  1671. );
  1672. this.pending = route;
  1673. var iterator = function (hook, next) {
  1674. if (this$1.pending !== route) {
  1675. return abort()
  1676. }
  1677. try {
  1678. hook(route, current, function (to) {
  1679. if (to === false || isError(to)) {
  1680. // next(false) -> abort navigation, ensure current URL
  1681. this$1.ensureURL(true);
  1682. abort(to);
  1683. } else if (
  1684. typeof to === 'string' ||
  1685. (typeof to === 'object' && (
  1686. typeof to.path === 'string' ||
  1687. typeof to.name === 'string'
  1688. ))
  1689. ) {
  1690. // next('/') or next({ path: '/' }) -> redirect
  1691. abort();
  1692. if (typeof to === 'object' && to.replace) {
  1693. this$1.replace(to);
  1694. } else {
  1695. this$1.push(to);
  1696. }
  1697. } else {
  1698. // confirm transition and pass on the value
  1699. next(to);
  1700. }
  1701. });
  1702. } catch (e) {
  1703. abort(e);
  1704. }
  1705. };
  1706. runQueue(queue, iterator, function () {
  1707. var postEnterCbs = [];
  1708. var isValid = function () { return this$1.current === route; };
  1709. // wait until async components are resolved before
  1710. // extracting in-component enter guards
  1711. var enterGuards = extractEnterGuards(activated, postEnterCbs, isValid);
  1712. var queue = enterGuards.concat(this$1.router.resolveHooks);
  1713. runQueue(queue, iterator, function () {
  1714. if (this$1.pending !== route) {
  1715. return abort()
  1716. }
  1717. this$1.pending = null;
  1718. onComplete(route);
  1719. if (this$1.router.app) {
  1720. this$1.router.app.$nextTick(function () {
  1721. postEnterCbs.forEach(function (cb) { cb(); });
  1722. });
  1723. }
  1724. });
  1725. });
  1726. };
  1727. History.prototype.updateRoute = function updateRoute (route) {
  1728. var prev = this.current;
  1729. this.current = route;
  1730. this.cb && this.cb(route);
  1731. this.router.afterHooks.forEach(function (hook) {
  1732. hook && hook(route, prev);
  1733. });
  1734. };
  1735. function normalizeBase (base) {
  1736. if (!base) {
  1737. if (inBrowser) {
  1738. // respect <base> tag
  1739. var 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. var i;
  1759. var 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. var guards = flatMapComponents(records, function (def, instance, match, key) {
  1778. var guard = extractGuard(def, name);
  1779. if (guard) {
  1780. return Array.isArray(guard)
  1781. ? guard.map(function (guard) { return 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', function (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, function (cb) {
  1828. next(cb);
  1829. if (typeof cb === 'function') {
  1830. cbs.push(function () {
  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(function () {
  1855. poll(cb, instances, key, isValid);
  1856. }, 16);
  1857. }
  1858. }
  1859. /* */
  1860. var HTML5History = (function (History$$1) {
  1861. function HTML5History (router, base) {
  1862. var this$1 = this;
  1863. History$$1.call(this, router, base);
  1864. var expectScroll = router.options.scrollBehavior;
  1865. var supportsScroll = supportsPushState && expectScroll;
  1866. if (supportsScroll) {
  1867. setupScroll();
  1868. }
  1869. var initLocation = getLocation(this.base);
  1870. window.addEventListener('popstate', function (e) {
  1871. var current = this$1.current;
  1872. // Avoiding first `popstate` event dispatched in some browsers but first
  1873. // history route not updated since async guard at the same time.
  1874. var location = getLocation(this$1.base);
  1875. if (this$1.current === START && location === initLocation) {
  1876. return
  1877. }
  1878. this$1.transitionTo(location, function (route) {
  1879. if (supportsScroll) {
  1880. handleScroll(router, route, current, true);
  1881. }
  1882. });
  1883. });
  1884. }
  1885. if ( History$$1 ) HTML5History.__proto__ = History$$1;
  1886. HTML5History.prototype = Object.create( History$$1 && History$$1.prototype );
  1887. HTML5History.prototype.constructor = HTML5History;
  1888. HTML5History.prototype.go = function go (n) {
  1889. window.history.go(n);
  1890. };
  1891. HTML5History.prototype.push = function push (location, onComplete, onAbort) {
  1892. var this$1 = this;
  1893. var ref = this;
  1894. var fromRoute = ref.current;
  1895. this.transitionTo(location, function (route) {
  1896. pushState(cleanPath(this$1.base + route.fullPath));
  1897. handleScroll(this$1.router, route, fromRoute, false);
  1898. onComplete && onComplete(route);
  1899. }, onAbort);
  1900. };
  1901. HTML5History.prototype.replace = function replace (location, onComplete, onAbort) {
  1902. var this$1 = this;
  1903. var ref = this;
  1904. var fromRoute = ref.current;
  1905. this.transitionTo(location, function (route) {
  1906. replaceState(cleanPath(this$1.base + route.fullPath));
  1907. handleScroll(this$1.router, route, fromRoute, false);
  1908. onComplete && onComplete(route);
  1909. }, onAbort);
  1910. };
  1911. HTML5History.prototype.ensureURL = function ensureURL (push) {
  1912. if (getLocation(this.base) !== this.current.fullPath) {
  1913. var current = cleanPath(this.base + this.current.fullPath);
  1914. push ? pushState(current) : replaceState(current);
  1915. }
  1916. };
  1917. HTML5History.prototype.getCurrentLocation = function getCurrentLocation () {
  1918. return getLocation(this.base)
  1919. };
  1920. return HTML5History;
  1921. }(History));
  1922. function getLocation (base) {
  1923. var path = decodeURI(window.location.pathname);
  1924. if (base && path.indexOf(base) === 0) {
  1925. path = path.slice(base.length);
  1926. }
  1927. return (path || '/') + window.location.search + window.location.hash
  1928. }
  1929. /* */
  1930. var HashHistory = (function (History$$1) {
  1931. function HashHistory (router, base, fallback) {
  1932. History$$1.call(this, router, base);
  1933. // check history fallback deeplinking
  1934. if (fallback && checkFallback(this.base)) {
  1935. return
  1936. }
  1937. ensureSlash();
  1938. }
  1939. if ( History$$1 ) HashHistory.__proto__ = History$$1;
  1940. HashHistory.prototype = Object.create( History$$1 && History$$1.prototype );
  1941. HashHistory.prototype.constructor = HashHistory;
  1942. // this is delayed until the app mounts
  1943. // to avoid the hashchange listener being fired too early
  1944. HashHistory.prototype.setupListeners = function setupListeners () {
  1945. var this$1 = this;
  1946. var router = this.router;
  1947. var expectScroll = router.options.scrollBehavior;
  1948. var supportsScroll = supportsPushState && expectScroll;
  1949. if (supportsScroll) {
  1950. setupScroll();
  1951. }
  1952. window.addEventListener(supportsPushState ? 'popstate' : 'hashchange', function () {
  1953. var current = this$1.current;
  1954. if (!ensureSlash()) {
  1955. return
  1956. }
  1957. this$1.transitionTo(getHash(), function (route) {
  1958. if (supportsScroll) {
  1959. handleScroll(this$1.router, route, current, true);
  1960. }
  1961. if (!supportsPushState) {
  1962. replaceHash(route.fullPath);
  1963. }
  1964. });
  1965. });
  1966. };
  1967. HashHistory.prototype.push = function push (location, onComplete, onAbort) {
  1968. var this$1 = this;
  1969. var ref = this;
  1970. var fromRoute = ref.current;
  1971. this.transitionTo(location, function (route) {
  1972. pushHash(route.fullPath);
  1973. handleScroll(this$1.router, route, fromRoute, false);
  1974. onComplete && onComplete(route);
  1975. }, onAbort);
  1976. };
  1977. HashHistory.prototype.replace = function replace (location, onComplete, onAbort) {
  1978. var this$1 = this;
  1979. var ref = this;
  1980. var fromRoute = ref.current;
  1981. this.transitionTo(location, function (route) {
  1982. replaceHash(route.fullPath);
  1983. handleScroll(this$1.router, route, fromRoute, false);
  1984. onComplete && onComplete(route);
  1985. }, onAbort);
  1986. };
  1987. HashHistory.prototype.go = function go (n) {
  1988. window.history.go(n);
  1989. };
  1990. HashHistory.prototype.ensureURL = function ensureURL (push) {
  1991. var current = this.current.fullPath;
  1992. if (getHash() !== current) {
  1993. push ? pushHash(current) : replaceHash(current);
  1994. }
  1995. };
  1996. HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
  1997. return getHash()
  1998. };
  1999. return HashHistory;
  2000. }(History));
  2001. function checkFallback (base) {
  2002. var location = getLocation(base);
  2003. if (!/^\/#/.test(location)) {
  2004. window.location.replace(
  2005. cleanPath(base + '/#' + location)
  2006. );
  2007. return true
  2008. }
  2009. }
  2010. function ensureSlash () {
  2011. var path = getHash();
  2012. if (path.charAt(0) === '/') {
  2013. return true
  2014. }
  2015. replaceHash('/' + path);
  2016. return false
  2017. }
  2018. function getHash () {
  2019. // We can't use window.location.hash here because it's not
  2020. // consistent across browsers - Firefox will pre-decode it!
  2021. var href = window.location.href;
  2022. var index = href.indexOf('#');
  2023. return index === -1 ? '' : decodeURI(href.slice(index + 1))
  2024. }
  2025. function getUrl (path) {
  2026. var href = window.location.href;
  2027. var i = href.indexOf('#');
  2028. var base = i >= 0 ? href.slice(0, i) : href;
  2029. return (base + "#" + path)
  2030. }
  2031. function pushHash (path) {
  2032. if (supportsPushState) {
  2033. pushState(getUrl(path));
  2034. } else {
  2035. window.location.hash = path;
  2036. }
  2037. }
  2038. function replaceHash (path) {
  2039. if (supportsPushState) {
  2040. replaceState(getUrl(path));
  2041. } else {
  2042. window.location.replace(getUrl(path));
  2043. }
  2044. }
  2045. /* */
  2046. var AbstractHistory = (function (History$$1) {
  2047. function AbstractHistory (router, base) {
  2048. History$$1.call(this, router, base);
  2049. this.stack = [];
  2050. this.index = -1;
  2051. }
  2052. if ( History$$1 ) AbstractHistory.__proto__ = History$$1;
  2053. AbstractHistory.prototype = Object.create( History$$1 && History$$1.prototype );
  2054. AbstractHistory.prototype.constructor = AbstractHistory;
  2055. AbstractHistory.prototype.push = function push (location, onComplete, onAbort) {
  2056. var this$1 = this;
  2057. this.transitionTo(location, function (route) {
  2058. this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route);
  2059. this$1.index++;
  2060. onComplete && onComplete(route);
  2061. }, onAbort);
  2062. };
  2063. AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) {
  2064. var this$1 = this;
  2065. this.transitionTo(location, function (route) {
  2066. this$1.stack = this$1.stack.slice(0, this$1.index).concat(route);
  2067. onComplete && onComplete(route);
  2068. }, onAbort);
  2069. };
  2070. AbstractHistory.prototype.go = function go (n) {
  2071. var this$1 = this;
  2072. var targetIndex = this.index + n;
  2073. if (targetIndex < 0 || targetIndex >= this.stack.length) {
  2074. return
  2075. }
  2076. var route = this.stack[targetIndex];
  2077. this.confirmTransition(route, function () {
  2078. this$1.index = targetIndex;
  2079. this$1.updateRoute(route);
  2080. });
  2081. };
  2082. AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () {
  2083. var current = this.stack[this.stack.length - 1];
  2084. return current ? current.fullPath : '/'
  2085. };
  2086. AbstractHistory.prototype.ensureURL = function ensureURL () {
  2087. // noop
  2088. };
  2089. return AbstractHistory;
  2090. }(History));
  2091. /* */
  2092. var VueRouter = function VueRouter (options) {
  2093. if ( options === void 0 ) options = {};
  2094. this.app = null;
  2095. this.apps = [];
  2096. this.options = options;
  2097. this.beforeHooks = [];
  2098. this.resolveHooks = [];
  2099. this.afterHooks = [];
  2100. this.matcher = createMatcher(options.routes || [], this);
  2101. var mode = options.mode || 'hash';
  2102. this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false;
  2103. if (this.fallback) {
  2104. mode = 'hash';
  2105. }
  2106. if (!inBrowser) {
  2107. mode = 'abstract';
  2108. }
  2109. this.mode = mode;
  2110. switch (mode) {
  2111. case 'history':
  2112. this.history = new HTML5History(this, options.base);
  2113. break
  2114. case 'hash':
  2115. this.history = new HashHistory(this, options.base, this.fallback);
  2116. break
  2117. case 'abstract':
  2118. this.history = new AbstractHistory(this, options.base);
  2119. break
  2120. default:
  2121. if (process.env.NODE_ENV !== 'production') {
  2122. assert(false, ("invalid mode: " + mode));
  2123. }
  2124. }
  2125. };
  2126. var prototypeAccessors = { currentRoute: { configurable: true } };
  2127. VueRouter.prototype.match = function match (
  2128. raw,
  2129. current,
  2130. redirectedFrom
  2131. ) {
  2132. return this.matcher.match(raw, current, redirectedFrom)
  2133. };
  2134. prototypeAccessors.currentRoute.get = function () {
  2135. return this.history && this.history.current
  2136. };
  2137. VueRouter.prototype.init = function init (app /* Vue component instance */) {
  2138. var this$1 = this;
  2139. process.env.NODE_ENV !== 'production' && assert(
  2140. install.installed,
  2141. "not installed. Make sure to call `Vue.use(VueRouter)` " +
  2142. "before creating root instance."
  2143. );
  2144. this.apps.push(app);
  2145. // main app already initialized.
  2146. if (this.app) {
  2147. return
  2148. }
  2149. this.app = app;
  2150. var history = this.history;
  2151. if (history instanceof HTML5History) {
  2152. history.transitionTo(history.getCurrentLocation());
  2153. } else if (history instanceof HashHistory) {
  2154. var setupHashListener = function () {
  2155. history.setupListeners();
  2156. };
  2157. history.transitionTo(
  2158. history.getCurrentLocation(),
  2159. setupHashListener,
  2160. setupHashListener
  2161. );
  2162. }
  2163. history.listen(function (route) {
  2164. this$1.apps.forEach(function (app) {
  2165. app._route = route;
  2166. });
  2167. });
  2168. };
  2169. VueRouter.prototype.beforeEach = function beforeEach (fn) {
  2170. return registerHook(this.beforeHooks, fn)
  2171. };
  2172. VueRouter.prototype.beforeResolve = function beforeResolve (fn) {
  2173. return registerHook(this.resolveHooks, fn)
  2174. };
  2175. VueRouter.prototype.afterEach = function afterEach (fn) {
  2176. return registerHook(this.afterHooks, fn)
  2177. };
  2178. VueRouter.prototype.onReady = function onReady (cb, errorCb) {
  2179. this.history.onReady(cb, errorCb);
  2180. };
  2181. VueRouter.prototype.onError = function onError (errorCb) {
  2182. this.history.onError(errorCb);
  2183. };
  2184. VueRouter.prototype.push = function push (location, onComplete, onAbort) {
  2185. this.history.push(location, onComplete, onAbort);
  2186. };
  2187. VueRouter.prototype.replace = function replace (location, onComplete, onAbort) {
  2188. this.history.replace(location, onComplete, onAbort);
  2189. };
  2190. VueRouter.prototype.go = function go (n) {
  2191. this.history.go(n);
  2192. };
  2193. VueRouter.prototype.back = function back () {
  2194. this.go(-1);
  2195. };
  2196. VueRouter.prototype.forward = function forward () {
  2197. this.go(1);
  2198. };
  2199. VueRouter.prototype.getMatchedComponents = function getMatchedComponents (to) {
  2200. var route = to
  2201. ? to.matched
  2202. ? to
  2203. : this.resolve(to).route
  2204. : this.currentRoute;
  2205. if (!route) {
  2206. return []
  2207. }
  2208. return [].concat.apply([], route.matched.map(function (m) {
  2209. return Object.keys(m.components).map(function (key) {
  2210. return m.components[key]
  2211. })
  2212. }))
  2213. };
  2214. VueRouter.prototype.resolve = function resolve (
  2215. to,
  2216. current,
  2217. append
  2218. ) {
  2219. var location = normalizeLocation(
  2220. to,
  2221. current || this.history.current,
  2222. append,
  2223. this
  2224. );
  2225. var route = this.match(location, current);
  2226. var fullPath = route.redirectedFrom || route.fullPath;
  2227. var base = this.history.base;
  2228. var href = createHref(base, fullPath, this.mode);
  2229. return {
  2230. location: location,
  2231. route: route,
  2232. href: href,
  2233. // for backwards compat
  2234. normalizedTo: location,
  2235. resolved: route
  2236. }
  2237. };
  2238. VueRouter.prototype.addRoutes = function addRoutes (routes) {
  2239. this.matcher.addRoutes(routes);
  2240. if (this.history.current !== START) {
  2241. this.history.transitionTo(this.history.getCurrentLocation());
  2242. }
  2243. };
  2244. Object.defineProperties( VueRouter.prototype, prototypeAccessors );
  2245. function registerHook (list, fn) {
  2246. list.push(fn);
  2247. return function () {
  2248. var i = list.indexOf(fn);
  2249. if (i > -1) { list.splice(i, 1); }
  2250. }
  2251. }
  2252. function createHref (base, fullPath, mode) {
  2253. var path = mode === 'hash' ? '#' + fullPath : fullPath;
  2254. return base ? cleanPath(base + '/' + path) : path
  2255. }
  2256. VueRouter.install = install;
  2257. VueRouter.version = '3.0.2';
  2258. if (inBrowser && window.Vue) {
  2259. window.Vue.use(VueRouter);
  2260. }
  2261. export default VueRouter;