vue-router.esm.js 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629
  1. /*!
  2. * vue-router v3.0.3
  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 (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. params = params || {};
  932. try {
  933. var filler =
  934. regexpCompileCache[path] ||
  935. (regexpCompileCache[path] = pathToRegexp_1.compile(path));
  936. // Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }}
  937. if (params.pathMatch) { params[0] = params.pathMatch; }
  938. return filler(params, { pretty: true })
  939. } catch (e) {
  940. if (process.env.NODE_ENV !== 'production') {
  941. warn(false, ("missing param for " + routeMsg + ": " + (e.message)));
  942. }
  943. return ''
  944. } finally {
  945. // delete the 0 if it was added
  946. delete params[0];
  947. }
  948. }
  949. /* */
  950. function createRouteMap (
  951. routes,
  952. oldPathList,
  953. oldPathMap,
  954. oldNameMap
  955. ) {
  956. // the path list is used to control path matching priority
  957. var pathList = oldPathList || [];
  958. // $flow-disable-line
  959. var pathMap = oldPathMap || Object.create(null);
  960. // $flow-disable-line
  961. var nameMap = oldNameMap || Object.create(null);
  962. routes.forEach(function (route) {
  963. addRouteRecord(pathList, pathMap, nameMap, route);
  964. });
  965. // ensure wildcard routes are always at the end
  966. for (var i = 0, l = pathList.length; i < l; i++) {
  967. if (pathList[i] === '*') {
  968. pathList.push(pathList.splice(i, 1)[0]);
  969. l--;
  970. i--;
  971. }
  972. }
  973. return {
  974. pathList: pathList,
  975. pathMap: pathMap,
  976. nameMap: nameMap
  977. }
  978. }
  979. function addRouteRecord (
  980. pathList,
  981. pathMap,
  982. nameMap,
  983. route,
  984. parent,
  985. matchAs
  986. ) {
  987. var path = route.path;
  988. var name = route.name;
  989. if (process.env.NODE_ENV !== 'production') {
  990. assert(path != null, "\"path\" is required in a route configuration.");
  991. assert(
  992. typeof route.component !== 'string',
  993. "route config \"component\" for path: " + (String(path || name)) + " cannot be a " +
  994. "string id. Use an actual component instead."
  995. );
  996. }
  997. var pathToRegexpOptions = route.pathToRegexpOptions || {};
  998. var normalizedPath = normalizePath(
  999. path,
  1000. parent,
  1001. pathToRegexpOptions.strict
  1002. );
  1003. if (typeof route.caseSensitive === 'boolean') {
  1004. pathToRegexpOptions.sensitive = route.caseSensitive;
  1005. }
  1006. var record = {
  1007. path: normalizedPath,
  1008. regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
  1009. components: route.components || { default: route.component },
  1010. instances: {},
  1011. name: name,
  1012. parent: parent,
  1013. matchAs: matchAs,
  1014. redirect: route.redirect,
  1015. beforeEnter: route.beforeEnter,
  1016. meta: route.meta || {},
  1017. props: route.props == null
  1018. ? {}
  1019. : route.components
  1020. ? route.props
  1021. : { default: route.props }
  1022. };
  1023. if (route.children) {
  1024. // Warn if route is named, does not redirect and has a default child route.
  1025. // If users navigate to this route by name, the default child will
  1026. // not be rendered (GH Issue #629)
  1027. if (process.env.NODE_ENV !== 'production') {
  1028. if (route.name && !route.redirect && route.children.some(function (child) { return /^\/?$/.test(child.path); })) {
  1029. warn(
  1030. false,
  1031. "Named Route '" + (route.name) + "' has a default child route. " +
  1032. "When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " +
  1033. "the default child route will not be rendered. Remove the name from " +
  1034. "this route and use the name of the default child route for named " +
  1035. "links instead."
  1036. );
  1037. }
  1038. }
  1039. route.children.forEach(function (child) {
  1040. var childMatchAs = matchAs
  1041. ? cleanPath((matchAs + "/" + (child.path)))
  1042. : undefined;
  1043. addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
  1044. });
  1045. }
  1046. if (route.alias !== undefined) {
  1047. var aliases = Array.isArray(route.alias)
  1048. ? route.alias
  1049. : [route.alias];
  1050. aliases.forEach(function (alias) {
  1051. var aliasRoute = {
  1052. path: alias,
  1053. children: route.children
  1054. };
  1055. addRouteRecord(
  1056. pathList,
  1057. pathMap,
  1058. nameMap,
  1059. aliasRoute,
  1060. parent,
  1061. record.path || '/' // matchAs
  1062. );
  1063. });
  1064. }
  1065. if (!pathMap[record.path]) {
  1066. pathList.push(record.path);
  1067. pathMap[record.path] = record;
  1068. }
  1069. if (name) {
  1070. if (!nameMap[name]) {
  1071. nameMap[name] = record;
  1072. } else if (process.env.NODE_ENV !== 'production' && !matchAs) {
  1073. warn(
  1074. false,
  1075. "Duplicate named routes definition: " +
  1076. "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
  1077. );
  1078. }
  1079. }
  1080. }
  1081. function compileRouteRegex (path, pathToRegexpOptions) {
  1082. var regex = pathToRegexp_1(path, [], pathToRegexpOptions);
  1083. if (process.env.NODE_ENV !== 'production') {
  1084. var keys = Object.create(null);
  1085. regex.keys.forEach(function (key) {
  1086. warn(!keys[key.name], ("Duplicate param keys in route with path: \"" + path + "\""));
  1087. keys[key.name] = true;
  1088. });
  1089. }
  1090. return regex
  1091. }
  1092. function normalizePath (path, parent, strict) {
  1093. if (!strict) { path = path.replace(/\/$/, ''); }
  1094. if (path[0] === '/') { return path }
  1095. if (parent == null) { return path }
  1096. return cleanPath(((parent.path) + "/" + path))
  1097. }
  1098. /* */
  1099. function normalizeLocation (
  1100. raw,
  1101. current,
  1102. append,
  1103. router
  1104. ) {
  1105. var next = typeof raw === 'string' ? { path: raw } : raw;
  1106. // named target
  1107. if (next._normalized) {
  1108. return next
  1109. } else if (next.name) {
  1110. return extend({}, raw)
  1111. }
  1112. // relative params
  1113. if (!next.path && next.params && current) {
  1114. next = extend({}, next);
  1115. next._normalized = true;
  1116. var params = extend(extend({}, current.params), next.params);
  1117. if (current.name) {
  1118. next.name = current.name;
  1119. next.params = params;
  1120. } else if (current.matched.length) {
  1121. var rawPath = current.matched[current.matched.length - 1].path;
  1122. next.path = fillParams(rawPath, params, ("path " + (current.path)));
  1123. } else if (process.env.NODE_ENV !== 'production') {
  1124. warn(false, "relative params navigation requires a current route.");
  1125. }
  1126. return next
  1127. }
  1128. var parsedPath = parsePath(next.path || '');
  1129. var basePath = (current && current.path) || '/';
  1130. var path = parsedPath.path
  1131. ? resolvePath(parsedPath.path, basePath, append || next.append)
  1132. : basePath;
  1133. var query = resolveQuery(
  1134. parsedPath.query,
  1135. next.query,
  1136. router && router.options.parseQuery
  1137. );
  1138. var hash = next.hash || parsedPath.hash;
  1139. if (hash && hash.charAt(0) !== '#') {
  1140. hash = "#" + hash;
  1141. }
  1142. return {
  1143. _normalized: true,
  1144. path: path,
  1145. query: query,
  1146. hash: hash
  1147. }
  1148. }
  1149. /* */
  1150. function createMatcher (
  1151. routes,
  1152. router
  1153. ) {
  1154. var ref = createRouteMap(routes);
  1155. var pathList = ref.pathList;
  1156. var pathMap = ref.pathMap;
  1157. var nameMap = ref.nameMap;
  1158. function addRoutes (routes) {
  1159. createRouteMap(routes, pathList, pathMap, nameMap);
  1160. }
  1161. function match (
  1162. raw,
  1163. currentRoute,
  1164. redirectedFrom
  1165. ) {
  1166. var location = normalizeLocation(raw, currentRoute, false, router);
  1167. var name = location.name;
  1168. if (name) {
  1169. var record = nameMap[name];
  1170. if (process.env.NODE_ENV !== 'production') {
  1171. warn(record, ("Route with name '" + name + "' does not exist"));
  1172. }
  1173. if (!record) { return _createRoute(null, location) }
  1174. var paramNames = record.regex.keys
  1175. .filter(function (key) { return !key.optional; })
  1176. .map(function (key) { return key.name; });
  1177. if (typeof location.params !== 'object') {
  1178. location.params = {};
  1179. }
  1180. if (currentRoute && typeof currentRoute.params === 'object') {
  1181. for (var key in currentRoute.params) {
  1182. if (!(key in location.params) && paramNames.indexOf(key) > -1) {
  1183. location.params[key] = currentRoute.params[key];
  1184. }
  1185. }
  1186. }
  1187. if (record) {
  1188. location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
  1189. return _createRoute(record, location, redirectedFrom)
  1190. }
  1191. } else if (location.path) {
  1192. location.params = {};
  1193. for (var i = 0; i < pathList.length; i++) {
  1194. var path = pathList[i];
  1195. var record$1 = pathMap[path];
  1196. if (matchRoute(record$1.regex, location.path, location.params)) {
  1197. return _createRoute(record$1, location, redirectedFrom)
  1198. }
  1199. }
  1200. }
  1201. // no match
  1202. return _createRoute(null, location)
  1203. }
  1204. function redirect (
  1205. record,
  1206. location
  1207. ) {
  1208. var originalRedirect = record.redirect;
  1209. var redirect = typeof originalRedirect === 'function'
  1210. ? originalRedirect(createRoute(record, location, null, router))
  1211. : originalRedirect;
  1212. if (typeof redirect === 'string') {
  1213. redirect = { path: redirect };
  1214. }
  1215. if (!redirect || typeof redirect !== 'object') {
  1216. if (process.env.NODE_ENV !== 'production') {
  1217. warn(
  1218. false, ("invalid redirect option: " + (JSON.stringify(redirect)))
  1219. );
  1220. }
  1221. return _createRoute(null, location)
  1222. }
  1223. var re = redirect;
  1224. var name = re.name;
  1225. var path = re.path;
  1226. var query = location.query;
  1227. var hash = location.hash;
  1228. var params = location.params;
  1229. query = re.hasOwnProperty('query') ? re.query : query;
  1230. hash = re.hasOwnProperty('hash') ? re.hash : hash;
  1231. params = re.hasOwnProperty('params') ? re.params : params;
  1232. if (name) {
  1233. // resolved named direct
  1234. var targetRecord = nameMap[name];
  1235. if (process.env.NODE_ENV !== 'production') {
  1236. assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
  1237. }
  1238. return match({
  1239. _normalized: true,
  1240. name: name,
  1241. query: query,
  1242. hash: hash,
  1243. params: params
  1244. }, undefined, location)
  1245. } else if (path) {
  1246. // 1. resolve relative redirect
  1247. var rawPath = resolveRecordPath(path, record);
  1248. // 2. resolve params
  1249. var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\""));
  1250. // 3. rematch with existing query and hash
  1251. return match({
  1252. _normalized: true,
  1253. path: resolvedPath,
  1254. query: query,
  1255. hash: hash
  1256. }, undefined, location)
  1257. } else {
  1258. if (process.env.NODE_ENV !== 'production') {
  1259. warn(false, ("invalid redirect option: " + (JSON.stringify(redirect))));
  1260. }
  1261. return _createRoute(null, location)
  1262. }
  1263. }
  1264. function alias (
  1265. record,
  1266. location,
  1267. matchAs
  1268. ) {
  1269. var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
  1270. var aliasedMatch = match({
  1271. _normalized: true,
  1272. path: aliasedPath
  1273. });
  1274. if (aliasedMatch) {
  1275. var matched = aliasedMatch.matched;
  1276. var aliasedRecord = matched[matched.length - 1];
  1277. location.params = aliasedMatch.params;
  1278. return _createRoute(aliasedRecord, location)
  1279. }
  1280. return _createRoute(null, location)
  1281. }
  1282. function _createRoute (
  1283. record,
  1284. location,
  1285. redirectedFrom
  1286. ) {
  1287. if (record && record.redirect) {
  1288. return redirect(record, redirectedFrom || location)
  1289. }
  1290. if (record && record.matchAs) {
  1291. return alias(record, location, record.matchAs)
  1292. }
  1293. return createRoute(record, location, redirectedFrom, router)
  1294. }
  1295. return {
  1296. match: match,
  1297. addRoutes: addRoutes
  1298. }
  1299. }
  1300. function matchRoute (
  1301. regex,
  1302. path,
  1303. params
  1304. ) {
  1305. var m = path.match(regex);
  1306. if (!m) {
  1307. return false
  1308. } else if (!params) {
  1309. return true
  1310. }
  1311. for (var i = 1, len = m.length; i < len; ++i) {
  1312. var key = regex.keys[i - 1];
  1313. var val = typeof m[i] === 'string' ? decodeURIComponent(m[i]) : m[i];
  1314. if (key) {
  1315. // Fix #1994: using * with props: true generates a param named 0
  1316. params[key.name || 'pathMatch'] = val;
  1317. }
  1318. }
  1319. return true
  1320. }
  1321. function resolveRecordPath (path, record) {
  1322. return resolvePath(path, record.parent ? record.parent.path : '/', true)
  1323. }
  1324. /* */
  1325. var positionStore = Object.create(null);
  1326. function setupScroll () {
  1327. // Fix for #1585 for Firefox
  1328. // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
  1329. window.history.replaceState({ key: getStateKey() }, '', window.location.href.replace(window.location.origin, ''));
  1330. window.addEventListener('popstate', function (e) {
  1331. saveScrollPosition();
  1332. if (e.state && e.state.key) {
  1333. setStateKey(e.state.key);
  1334. }
  1335. });
  1336. }
  1337. function handleScroll (
  1338. router,
  1339. to,
  1340. from,
  1341. isPop
  1342. ) {
  1343. if (!router.app) {
  1344. return
  1345. }
  1346. var behavior = router.options.scrollBehavior;
  1347. if (!behavior) {
  1348. return
  1349. }
  1350. if (process.env.NODE_ENV !== 'production') {
  1351. assert(typeof behavior === 'function', "scrollBehavior must be a function");
  1352. }
  1353. // wait until re-render finishes before scrolling
  1354. router.app.$nextTick(function () {
  1355. var position = getScrollPosition();
  1356. var shouldScroll = behavior.call(router, to, from, isPop ? position : null);
  1357. if (!shouldScroll) {
  1358. return
  1359. }
  1360. if (typeof shouldScroll.then === 'function') {
  1361. shouldScroll.then(function (shouldScroll) {
  1362. scrollToPosition((shouldScroll), position);
  1363. }).catch(function (err) {
  1364. if (process.env.NODE_ENV !== 'production') {
  1365. assert(false, err.toString());
  1366. }
  1367. });
  1368. } else {
  1369. scrollToPosition(shouldScroll, position);
  1370. }
  1371. });
  1372. }
  1373. function saveScrollPosition () {
  1374. var key = getStateKey();
  1375. if (key) {
  1376. positionStore[key] = {
  1377. x: window.pageXOffset,
  1378. y: window.pageYOffset
  1379. };
  1380. }
  1381. }
  1382. function getScrollPosition () {
  1383. var key = getStateKey();
  1384. if (key) {
  1385. return positionStore[key]
  1386. }
  1387. }
  1388. function getElementPosition (el, offset) {
  1389. var docEl = document.documentElement;
  1390. var docRect = docEl.getBoundingClientRect();
  1391. var elRect = el.getBoundingClientRect();
  1392. return {
  1393. x: elRect.left - docRect.left - offset.x,
  1394. y: elRect.top - docRect.top - offset.y
  1395. }
  1396. }
  1397. function isValidPosition (obj) {
  1398. return isNumber(obj.x) || isNumber(obj.y)
  1399. }
  1400. function normalizePosition (obj) {
  1401. return {
  1402. x: isNumber(obj.x) ? obj.x : window.pageXOffset,
  1403. y: isNumber(obj.y) ? obj.y : window.pageYOffset
  1404. }
  1405. }
  1406. function normalizeOffset (obj) {
  1407. return {
  1408. x: isNumber(obj.x) ? obj.x : 0,
  1409. y: isNumber(obj.y) ? obj.y : 0
  1410. }
  1411. }
  1412. function isNumber (v) {
  1413. return typeof v === 'number'
  1414. }
  1415. function scrollToPosition (shouldScroll, position) {
  1416. var isObject = typeof shouldScroll === 'object';
  1417. if (isObject && typeof shouldScroll.selector === 'string') {
  1418. var el = document.querySelector(shouldScroll.selector);
  1419. if (el) {
  1420. var offset = shouldScroll.offset && typeof shouldScroll.offset === 'object' ? shouldScroll.offset : {};
  1421. offset = normalizeOffset(offset);
  1422. position = getElementPosition(el, offset);
  1423. } else if (isValidPosition(shouldScroll)) {
  1424. position = normalizePosition(shouldScroll);
  1425. }
  1426. } else if (isObject && isValidPosition(shouldScroll)) {
  1427. position = normalizePosition(shouldScroll);
  1428. }
  1429. if (position) {
  1430. window.scrollTo(position.x, position.y);
  1431. }
  1432. }
  1433. /* */
  1434. var supportsPushState = inBrowser && (function () {
  1435. var ua = window.navigator.userAgent;
  1436. if (
  1437. (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
  1438. ua.indexOf('Mobile Safari') !== -1 &&
  1439. ua.indexOf('Chrome') === -1 &&
  1440. ua.indexOf('Windows Phone') === -1
  1441. ) {
  1442. return false
  1443. }
  1444. return window.history && 'pushState' in window.history
  1445. })();
  1446. // use User Timing api (if present) for more accurate key precision
  1447. var Time = inBrowser && window.performance && window.performance.now
  1448. ? window.performance
  1449. : Date;
  1450. var _key = genKey();
  1451. function genKey () {
  1452. return Time.now().toFixed(3)
  1453. }
  1454. function getStateKey () {
  1455. return _key
  1456. }
  1457. function setStateKey (key) {
  1458. _key = key;
  1459. }
  1460. function pushState (url, replace) {
  1461. saveScrollPosition();
  1462. // try...catch the pushState call to get around Safari
  1463. // DOM Exception 18 where it limits to 100 pushState calls
  1464. var history = window.history;
  1465. try {
  1466. if (replace) {
  1467. history.replaceState({ key: _key }, '', url);
  1468. } else {
  1469. _key = genKey();
  1470. history.pushState({ key: _key }, '', url);
  1471. }
  1472. } catch (e) {
  1473. window.location[replace ? 'replace' : 'assign'](url);
  1474. }
  1475. }
  1476. function replaceState (url) {
  1477. pushState(url, true);
  1478. }
  1479. /* */
  1480. function runQueue (queue, fn, cb) {
  1481. var step = function (index) {
  1482. if (index >= queue.length) {
  1483. cb();
  1484. } else {
  1485. if (queue[index]) {
  1486. fn(queue[index], function () {
  1487. step(index + 1);
  1488. });
  1489. } else {
  1490. step(index + 1);
  1491. }
  1492. }
  1493. };
  1494. step(0);
  1495. }
  1496. /* */
  1497. function resolveAsyncComponents (matched) {
  1498. return function (to, from, next) {
  1499. var hasAsync = false;
  1500. var pending = 0;
  1501. var error = null;
  1502. flatMapComponents(matched, function (def, _, match, key) {
  1503. // if it's a function and doesn't have cid attached,
  1504. // assume it's an async component resolve function.
  1505. // we are not using Vue's default async resolving mechanism because
  1506. // we want to halt the navigation until the incoming component has been
  1507. // resolved.
  1508. if (typeof def === 'function' && def.cid === undefined) {
  1509. hasAsync = true;
  1510. pending++;
  1511. var resolve = once(function (resolvedDef) {
  1512. if (isESModule(resolvedDef)) {
  1513. resolvedDef = resolvedDef.default;
  1514. }
  1515. // save resolved on async factory in case it's used elsewhere
  1516. def.resolved = typeof resolvedDef === 'function'
  1517. ? resolvedDef
  1518. : _Vue.extend(resolvedDef);
  1519. match.components[key] = resolvedDef;
  1520. pending--;
  1521. if (pending <= 0) {
  1522. next();
  1523. }
  1524. });
  1525. var reject = once(function (reason) {
  1526. var msg = "Failed to resolve async component " + key + ": " + reason;
  1527. process.env.NODE_ENV !== 'production' && warn(false, msg);
  1528. if (!error) {
  1529. error = isError(reason)
  1530. ? reason
  1531. : new Error(msg);
  1532. next(error);
  1533. }
  1534. });
  1535. var res;
  1536. try {
  1537. res = def(resolve, reject);
  1538. } catch (e) {
  1539. reject(e);
  1540. }
  1541. if (res) {
  1542. if (typeof res.then === 'function') {
  1543. res.then(resolve, reject);
  1544. } else {
  1545. // new syntax in Vue 2.3
  1546. var comp = res.component;
  1547. if (comp && typeof comp.then === 'function') {
  1548. comp.then(resolve, reject);
  1549. }
  1550. }
  1551. }
  1552. }
  1553. });
  1554. if (!hasAsync) { next(); }
  1555. }
  1556. }
  1557. function flatMapComponents (
  1558. matched,
  1559. fn
  1560. ) {
  1561. return flatten(matched.map(function (m) {
  1562. return Object.keys(m.components).map(function (key) { return fn(
  1563. m.components[key],
  1564. m.instances[key],
  1565. m, key
  1566. ); })
  1567. }))
  1568. }
  1569. function flatten (arr) {
  1570. return Array.prototype.concat.apply([], arr)
  1571. }
  1572. var hasSymbol =
  1573. typeof Symbol === 'function' &&
  1574. typeof Symbol.toStringTag === 'symbol';
  1575. function isESModule (obj) {
  1576. return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
  1577. }
  1578. // in Webpack 2, require.ensure now also returns a Promise
  1579. // so the resolve/reject functions may get called an extra time
  1580. // if the user uses an arrow function shorthand that happens to
  1581. // return that Promise.
  1582. function once (fn) {
  1583. var called = false;
  1584. return function () {
  1585. var args = [], len = arguments.length;
  1586. while ( len-- ) args[ len ] = arguments[ len ];
  1587. if (called) { return }
  1588. called = true;
  1589. return fn.apply(this, args)
  1590. }
  1591. }
  1592. /* */
  1593. var History = function History (router, base) {
  1594. this.router = router;
  1595. this.base = normalizeBase(base);
  1596. // start with a route object that stands for "nowhere"
  1597. this.current = START;
  1598. this.pending = null;
  1599. this.ready = false;
  1600. this.readyCbs = [];
  1601. this.readyErrorCbs = [];
  1602. this.errorCbs = [];
  1603. };
  1604. History.prototype.listen = function listen (cb) {
  1605. this.cb = cb;
  1606. };
  1607. History.prototype.onReady = function onReady (cb, errorCb) {
  1608. if (this.ready) {
  1609. cb();
  1610. } else {
  1611. this.readyCbs.push(cb);
  1612. if (errorCb) {
  1613. this.readyErrorCbs.push(errorCb);
  1614. }
  1615. }
  1616. };
  1617. History.prototype.onError = function onError (errorCb) {
  1618. this.errorCbs.push(errorCb);
  1619. };
  1620. History.prototype.transitionTo = function transitionTo (location, onComplete, onAbort) {
  1621. var this$1 = this;
  1622. var route = this.router.match(location, this.current);
  1623. this.confirmTransition(route, function () {
  1624. this$1.updateRoute(route);
  1625. onComplete && onComplete(route);
  1626. this$1.ensureURL();
  1627. // fire ready cbs once
  1628. if (!this$1.ready) {
  1629. this$1.ready = true;
  1630. this$1.readyCbs.forEach(function (cb) { cb(route); });
  1631. }
  1632. }, function (err) {
  1633. if (onAbort) {
  1634. onAbort(err);
  1635. }
  1636. if (err && !this$1.ready) {
  1637. this$1.ready = true;
  1638. this$1.readyErrorCbs.forEach(function (cb) { cb(err); });
  1639. }
  1640. });
  1641. };
  1642. History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) {
  1643. var this$1 = this;
  1644. var current = this.current;
  1645. var abort = function (err) {
  1646. if (isError(err)) {
  1647. if (this$1.errorCbs.length) {
  1648. this$1.errorCbs.forEach(function (cb) { cb(err); });
  1649. } else {
  1650. warn(false, 'uncaught error during route navigation:');
  1651. console.error(err);
  1652. }
  1653. }
  1654. onAbort && onAbort(err);
  1655. };
  1656. if (
  1657. isSameRoute(route, current) &&
  1658. // in the case the route map has been dynamically appended to
  1659. route.matched.length === current.matched.length
  1660. ) {
  1661. this.ensureURL();
  1662. return abort()
  1663. }
  1664. var ref = resolveQueue(this.current.matched, route.matched);
  1665. var updated = ref.updated;
  1666. var deactivated = ref.deactivated;
  1667. var activated = ref.activated;
  1668. var queue = [].concat(
  1669. // in-component leave guards
  1670. extractLeaveGuards(deactivated),
  1671. // global before hooks
  1672. this.router.beforeHooks,
  1673. // in-component update hooks
  1674. extractUpdateHooks(updated),
  1675. // in-config enter guards
  1676. activated.map(function (m) { return m.beforeEnter; }),
  1677. // async components
  1678. resolveAsyncComponents(activated)
  1679. );
  1680. this.pending = route;
  1681. var iterator = function (hook, next) {
  1682. if (this$1.pending !== route) {
  1683. return abort()
  1684. }
  1685. try {
  1686. hook(route, current, function (to) {
  1687. if (to === false || isError(to)) {
  1688. // next(false) -> abort navigation, ensure current URL
  1689. this$1.ensureURL(true);
  1690. abort(to);
  1691. } else if (
  1692. typeof to === 'string' ||
  1693. (typeof to === 'object' && (
  1694. typeof to.path === 'string' ||
  1695. typeof to.name === 'string'
  1696. ))
  1697. ) {
  1698. // next('/') or next({ path: '/' }) -> redirect
  1699. abort();
  1700. if (typeof to === 'object' && to.replace) {
  1701. this$1.replace(to);
  1702. } else {
  1703. this$1.push(to);
  1704. }
  1705. } else {
  1706. // confirm transition and pass on the value
  1707. next(to);
  1708. }
  1709. });
  1710. } catch (e) {
  1711. abort(e);
  1712. }
  1713. };
  1714. runQueue(queue, iterator, function () {
  1715. var postEnterCbs = [];
  1716. var isValid = function () { return this$1.current === route; };
  1717. // wait until async components are resolved before
  1718. // extracting in-component enter guards
  1719. var enterGuards = extractEnterGuards(activated, postEnterCbs, isValid);
  1720. var queue = enterGuards.concat(this$1.router.resolveHooks);
  1721. runQueue(queue, iterator, function () {
  1722. if (this$1.pending !== route) {
  1723. return abort()
  1724. }
  1725. this$1.pending = null;
  1726. onComplete(route);
  1727. if (this$1.router.app) {
  1728. this$1.router.app.$nextTick(function () {
  1729. postEnterCbs.forEach(function (cb) { cb(); });
  1730. });
  1731. }
  1732. });
  1733. });
  1734. };
  1735. History.prototype.updateRoute = function updateRoute (route) {
  1736. var prev = this.current;
  1737. this.current = route;
  1738. this.cb && this.cb(route);
  1739. this.router.afterHooks.forEach(function (hook) {
  1740. hook && hook(route, prev);
  1741. });
  1742. };
  1743. function normalizeBase (base) {
  1744. if (!base) {
  1745. if (inBrowser) {
  1746. // respect <base> tag
  1747. var baseEl = document.querySelector('base');
  1748. base = (baseEl && baseEl.getAttribute('href')) || '/';
  1749. // strip full URL origin
  1750. base = base.replace(/^https?:\/\/[^\/]+/, '');
  1751. } else {
  1752. base = '/';
  1753. }
  1754. }
  1755. // make sure there's the starting slash
  1756. if (base.charAt(0) !== '/') {
  1757. base = '/' + base;
  1758. }
  1759. // remove trailing slash
  1760. return base.replace(/\/$/, '')
  1761. }
  1762. function resolveQueue (
  1763. current,
  1764. next
  1765. ) {
  1766. var i;
  1767. var max = Math.max(current.length, next.length);
  1768. for (i = 0; i < max; i++) {
  1769. if (current[i] !== next[i]) {
  1770. break
  1771. }
  1772. }
  1773. return {
  1774. updated: next.slice(0, i),
  1775. activated: next.slice(i),
  1776. deactivated: current.slice(i)
  1777. }
  1778. }
  1779. function extractGuards (
  1780. records,
  1781. name,
  1782. bind,
  1783. reverse
  1784. ) {
  1785. var guards = flatMapComponents(records, function (def, instance, match, key) {
  1786. var guard = extractGuard(def, name);
  1787. if (guard) {
  1788. return Array.isArray(guard)
  1789. ? guard.map(function (guard) { return bind(guard, instance, match, key); })
  1790. : bind(guard, instance, match, key)
  1791. }
  1792. });
  1793. return flatten(reverse ? guards.reverse() : guards)
  1794. }
  1795. function extractGuard (
  1796. def,
  1797. key
  1798. ) {
  1799. if (typeof def !== 'function') {
  1800. // extend now so that global mixins are applied.
  1801. def = _Vue.extend(def);
  1802. }
  1803. return def.options[key]
  1804. }
  1805. function extractLeaveGuards (deactivated) {
  1806. return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
  1807. }
  1808. function extractUpdateHooks (updated) {
  1809. return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
  1810. }
  1811. function bindGuard (guard, instance) {
  1812. if (instance) {
  1813. return function boundRouteGuard () {
  1814. return guard.apply(instance, arguments)
  1815. }
  1816. }
  1817. }
  1818. function extractEnterGuards (
  1819. activated,
  1820. cbs,
  1821. isValid
  1822. ) {
  1823. return extractGuards(activated, 'beforeRouteEnter', function (guard, _, match, key) {
  1824. return bindEnterGuard(guard, match, key, cbs, isValid)
  1825. })
  1826. }
  1827. function bindEnterGuard (
  1828. guard,
  1829. match,
  1830. key,
  1831. cbs,
  1832. isValid
  1833. ) {
  1834. return function routeEnterGuard (to, from, next) {
  1835. return guard(to, from, function (cb) {
  1836. next(cb);
  1837. if (typeof cb === 'function') {
  1838. cbs.push(function () {
  1839. // #750
  1840. // if a router-view is wrapped with an out-in transition,
  1841. // the instance may not have been registered at this time.
  1842. // we will need to poll for registration until current route
  1843. // is no longer valid.
  1844. poll(cb, match.instances, key, isValid);
  1845. });
  1846. }
  1847. })
  1848. }
  1849. }
  1850. function poll (
  1851. cb, // somehow flow cannot infer this is a function
  1852. instances,
  1853. key,
  1854. isValid
  1855. ) {
  1856. if (
  1857. instances[key] &&
  1858. !instances[key]._isBeingDestroyed // do not reuse being destroyed instance
  1859. ) {
  1860. cb(instances[key]);
  1861. } else if (isValid()) {
  1862. setTimeout(function () {
  1863. poll(cb, instances, key, isValid);
  1864. }, 16);
  1865. }
  1866. }
  1867. /* */
  1868. var HTML5History = /*@__PURE__*/(function (History$$1) {
  1869. function HTML5History (router, base) {
  1870. var this$1 = this;
  1871. History$$1.call(this, router, base);
  1872. var expectScroll = router.options.scrollBehavior;
  1873. var supportsScroll = supportsPushState && expectScroll;
  1874. if (supportsScroll) {
  1875. setupScroll();
  1876. }
  1877. var initLocation = getLocation(this.base);
  1878. window.addEventListener('popstate', function (e) {
  1879. var current = this$1.current;
  1880. // Avoiding first `popstate` event dispatched in some browsers but first
  1881. // history route not updated since async guard at the same time.
  1882. var location = getLocation(this$1.base);
  1883. if (this$1.current === START && location === initLocation) {
  1884. return
  1885. }
  1886. this$1.transitionTo(location, function (route) {
  1887. if (supportsScroll) {
  1888. handleScroll(router, route, current, true);
  1889. }
  1890. });
  1891. });
  1892. }
  1893. if ( History$$1 ) HTML5History.__proto__ = History$$1;
  1894. HTML5History.prototype = Object.create( History$$1 && History$$1.prototype );
  1895. HTML5History.prototype.constructor = HTML5History;
  1896. HTML5History.prototype.go = function go (n) {
  1897. window.history.go(n);
  1898. };
  1899. HTML5History.prototype.push = function push (location, onComplete, onAbort) {
  1900. var this$1 = this;
  1901. var ref = this;
  1902. var fromRoute = ref.current;
  1903. this.transitionTo(location, function (route) {
  1904. pushState(cleanPath(this$1.base + route.fullPath));
  1905. handleScroll(this$1.router, route, fromRoute, false);
  1906. onComplete && onComplete(route);
  1907. }, onAbort);
  1908. };
  1909. HTML5History.prototype.replace = function replace (location, onComplete, onAbort) {
  1910. var this$1 = this;
  1911. var ref = this;
  1912. var fromRoute = ref.current;
  1913. this.transitionTo(location, function (route) {
  1914. replaceState(cleanPath(this$1.base + route.fullPath));
  1915. handleScroll(this$1.router, route, fromRoute, false);
  1916. onComplete && onComplete(route);
  1917. }, onAbort);
  1918. };
  1919. HTML5History.prototype.ensureURL = function ensureURL (push) {
  1920. if (getLocation(this.base) !== this.current.fullPath) {
  1921. var current = cleanPath(this.base + this.current.fullPath);
  1922. push ? pushState(current) : replaceState(current);
  1923. }
  1924. };
  1925. HTML5History.prototype.getCurrentLocation = function getCurrentLocation () {
  1926. return getLocation(this.base)
  1927. };
  1928. return HTML5History;
  1929. }(History));
  1930. function getLocation (base) {
  1931. var path = decodeURI(window.location.pathname);
  1932. if (base && path.indexOf(base) === 0) {
  1933. path = path.slice(base.length);
  1934. }
  1935. return (path || '/') + window.location.search + window.location.hash
  1936. }
  1937. /* */
  1938. var HashHistory = /*@__PURE__*/(function (History$$1) {
  1939. function HashHistory (router, base, fallback) {
  1940. History$$1.call(this, router, base);
  1941. // check history fallback deeplinking
  1942. if (fallback && checkFallback(this.base)) {
  1943. return
  1944. }
  1945. ensureSlash();
  1946. }
  1947. if ( History$$1 ) HashHistory.__proto__ = History$$1;
  1948. HashHistory.prototype = Object.create( History$$1 && History$$1.prototype );
  1949. HashHistory.prototype.constructor = HashHistory;
  1950. // this is delayed until the app mounts
  1951. // to avoid the hashchange listener being fired too early
  1952. HashHistory.prototype.setupListeners = function setupListeners () {
  1953. var this$1 = this;
  1954. var router = this.router;
  1955. var expectScroll = router.options.scrollBehavior;
  1956. var supportsScroll = supportsPushState && expectScroll;
  1957. if (supportsScroll) {
  1958. setupScroll();
  1959. }
  1960. window.addEventListener(supportsPushState ? 'popstate' : 'hashchange', function () {
  1961. var current = this$1.current;
  1962. if (!ensureSlash()) {
  1963. return
  1964. }
  1965. this$1.transitionTo(getHash(), function (route) {
  1966. if (supportsScroll) {
  1967. handleScroll(this$1.router, route, current, true);
  1968. }
  1969. if (!supportsPushState) {
  1970. replaceHash(route.fullPath);
  1971. }
  1972. });
  1973. });
  1974. };
  1975. HashHistory.prototype.push = function push (location, onComplete, onAbort) {
  1976. var this$1 = this;
  1977. var ref = this;
  1978. var fromRoute = ref.current;
  1979. this.transitionTo(location, function (route) {
  1980. pushHash(route.fullPath);
  1981. handleScroll(this$1.router, route, fromRoute, false);
  1982. onComplete && onComplete(route);
  1983. }, onAbort);
  1984. };
  1985. HashHistory.prototype.replace = function replace (location, onComplete, onAbort) {
  1986. var this$1 = this;
  1987. var ref = this;
  1988. var fromRoute = ref.current;
  1989. this.transitionTo(location, function (route) {
  1990. replaceHash(route.fullPath);
  1991. handleScroll(this$1.router, route, fromRoute, false);
  1992. onComplete && onComplete(route);
  1993. }, onAbort);
  1994. };
  1995. HashHistory.prototype.go = function go (n) {
  1996. window.history.go(n);
  1997. };
  1998. HashHistory.prototype.ensureURL = function ensureURL (push) {
  1999. var current = this.current.fullPath;
  2000. if (getHash() !== current) {
  2001. push ? pushHash(current) : replaceHash(current);
  2002. }
  2003. };
  2004. HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
  2005. return getHash()
  2006. };
  2007. return HashHistory;
  2008. }(History));
  2009. function checkFallback (base) {
  2010. var location = getLocation(base);
  2011. if (!/^\/#/.test(location)) {
  2012. window.location.replace(
  2013. cleanPath(base + '/#' + location)
  2014. );
  2015. return true
  2016. }
  2017. }
  2018. function ensureSlash () {
  2019. var path = getHash();
  2020. if (path.charAt(0) === '/') {
  2021. return true
  2022. }
  2023. replaceHash('/' + path);
  2024. return false
  2025. }
  2026. function getHash () {
  2027. // We can't use window.location.hash here because it's not
  2028. // consistent across browsers - Firefox will pre-decode it!
  2029. var href = window.location.href;
  2030. var index = href.indexOf('#');
  2031. return index === -1 ? '' : decodeURI(href.slice(index + 1))
  2032. }
  2033. function getUrl (path) {
  2034. var href = window.location.href;
  2035. var i = href.indexOf('#');
  2036. var base = i >= 0 ? href.slice(0, i) : href;
  2037. return (base + "#" + path)
  2038. }
  2039. function pushHash (path) {
  2040. if (supportsPushState) {
  2041. pushState(getUrl(path));
  2042. } else {
  2043. window.location.hash = path;
  2044. }
  2045. }
  2046. function replaceHash (path) {
  2047. if (supportsPushState) {
  2048. replaceState(getUrl(path));
  2049. } else {
  2050. window.location.replace(getUrl(path));
  2051. }
  2052. }
  2053. /* */
  2054. var AbstractHistory = /*@__PURE__*/(function (History$$1) {
  2055. function AbstractHistory (router, base) {
  2056. History$$1.call(this, router, base);
  2057. this.stack = [];
  2058. this.index = -1;
  2059. }
  2060. if ( History$$1 ) AbstractHistory.__proto__ = History$$1;
  2061. AbstractHistory.prototype = Object.create( History$$1 && History$$1.prototype );
  2062. AbstractHistory.prototype.constructor = AbstractHistory;
  2063. AbstractHistory.prototype.push = function push (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 + 1).concat(route);
  2067. this$1.index++;
  2068. onComplete && onComplete(route);
  2069. }, onAbort);
  2070. };
  2071. AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) {
  2072. var this$1 = this;
  2073. this.transitionTo(location, function (route) {
  2074. this$1.stack = this$1.stack.slice(0, this$1.index).concat(route);
  2075. onComplete && onComplete(route);
  2076. }, onAbort);
  2077. };
  2078. AbstractHistory.prototype.go = function go (n) {
  2079. var this$1 = this;
  2080. var targetIndex = this.index + n;
  2081. if (targetIndex < 0 || targetIndex >= this.stack.length) {
  2082. return
  2083. }
  2084. var route = this.stack[targetIndex];
  2085. this.confirmTransition(route, function () {
  2086. this$1.index = targetIndex;
  2087. this$1.updateRoute(route);
  2088. });
  2089. };
  2090. AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () {
  2091. var current = this.stack[this.stack.length - 1];
  2092. return current ? current.fullPath : '/'
  2093. };
  2094. AbstractHistory.prototype.ensureURL = function ensureURL () {
  2095. // noop
  2096. };
  2097. return AbstractHistory;
  2098. }(History));
  2099. /* */
  2100. var VueRouter = function VueRouter (options) {
  2101. if ( options === void 0 ) options = {};
  2102. this.app = null;
  2103. this.apps = [];
  2104. this.options = options;
  2105. this.beforeHooks = [];
  2106. this.resolveHooks = [];
  2107. this.afterHooks = [];
  2108. this.matcher = createMatcher(options.routes || [], this);
  2109. var mode = options.mode || 'hash';
  2110. this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false;
  2111. if (this.fallback) {
  2112. mode = 'hash';
  2113. }
  2114. if (!inBrowser) {
  2115. mode = 'abstract';
  2116. }
  2117. this.mode = mode;
  2118. switch (mode) {
  2119. case 'history':
  2120. this.history = new HTML5History(this, options.base);
  2121. break
  2122. case 'hash':
  2123. this.history = new HashHistory(this, options.base, this.fallback);
  2124. break
  2125. case 'abstract':
  2126. this.history = new AbstractHistory(this, options.base);
  2127. break
  2128. default:
  2129. if (process.env.NODE_ENV !== 'production') {
  2130. assert(false, ("invalid mode: " + mode));
  2131. }
  2132. }
  2133. };
  2134. var prototypeAccessors = { currentRoute: { configurable: true } };
  2135. VueRouter.prototype.match = function match (
  2136. raw,
  2137. current,
  2138. redirectedFrom
  2139. ) {
  2140. return this.matcher.match(raw, current, redirectedFrom)
  2141. };
  2142. prototypeAccessors.currentRoute.get = function () {
  2143. return this.history && this.history.current
  2144. };
  2145. VueRouter.prototype.init = function init (app /* Vue component instance */) {
  2146. var this$1 = this;
  2147. process.env.NODE_ENV !== 'production' && assert(
  2148. install.installed,
  2149. "not installed. Make sure to call `Vue.use(VueRouter)` " +
  2150. "before creating root instance."
  2151. );
  2152. this.apps.push(app);
  2153. // main app already initialized.
  2154. if (this.app) {
  2155. return
  2156. }
  2157. this.app = app;
  2158. var history = this.history;
  2159. if (history instanceof HTML5History) {
  2160. history.transitionTo(history.getCurrentLocation());
  2161. } else if (history instanceof HashHistory) {
  2162. var setupHashListener = function () {
  2163. history.setupListeners();
  2164. };
  2165. history.transitionTo(
  2166. history.getCurrentLocation(),
  2167. setupHashListener,
  2168. setupHashListener
  2169. );
  2170. }
  2171. history.listen(function (route) {
  2172. this$1.apps.forEach(function (app) {
  2173. app._route = route;
  2174. });
  2175. });
  2176. };
  2177. VueRouter.prototype.beforeEach = function beforeEach (fn) {
  2178. return registerHook(this.beforeHooks, fn)
  2179. };
  2180. VueRouter.prototype.beforeResolve = function beforeResolve (fn) {
  2181. return registerHook(this.resolveHooks, fn)
  2182. };
  2183. VueRouter.prototype.afterEach = function afterEach (fn) {
  2184. return registerHook(this.afterHooks, fn)
  2185. };
  2186. VueRouter.prototype.onReady = function onReady (cb, errorCb) {
  2187. this.history.onReady(cb, errorCb);
  2188. };
  2189. VueRouter.prototype.onError = function onError (errorCb) {
  2190. this.history.onError(errorCb);
  2191. };
  2192. VueRouter.prototype.push = function push (location, onComplete, onAbort) {
  2193. this.history.push(location, onComplete, onAbort);
  2194. };
  2195. VueRouter.prototype.replace = function replace (location, onComplete, onAbort) {
  2196. this.history.replace(location, onComplete, onAbort);
  2197. };
  2198. VueRouter.prototype.go = function go (n) {
  2199. this.history.go(n);
  2200. };
  2201. VueRouter.prototype.back = function back () {
  2202. this.go(-1);
  2203. };
  2204. VueRouter.prototype.forward = function forward () {
  2205. this.go(1);
  2206. };
  2207. VueRouter.prototype.getMatchedComponents = function getMatchedComponents (to) {
  2208. var route = to
  2209. ? to.matched
  2210. ? to
  2211. : this.resolve(to).route
  2212. : this.currentRoute;
  2213. if (!route) {
  2214. return []
  2215. }
  2216. return [].concat.apply([], route.matched.map(function (m) {
  2217. return Object.keys(m.components).map(function (key) {
  2218. return m.components[key]
  2219. })
  2220. }))
  2221. };
  2222. VueRouter.prototype.resolve = function resolve (
  2223. to,
  2224. current,
  2225. append
  2226. ) {
  2227. current = current || this.history.current;
  2228. var location = normalizeLocation(
  2229. to,
  2230. current,
  2231. append,
  2232. this
  2233. );
  2234. var route = this.match(location, current);
  2235. var fullPath = route.redirectedFrom || route.fullPath;
  2236. var base = this.history.base;
  2237. var href = createHref(base, fullPath, this.mode);
  2238. return {
  2239. location: location,
  2240. route: route,
  2241. href: href,
  2242. // for backwards compat
  2243. normalizedTo: location,
  2244. resolved: route
  2245. }
  2246. };
  2247. VueRouter.prototype.addRoutes = function addRoutes (routes) {
  2248. this.matcher.addRoutes(routes);
  2249. if (this.history.current !== START) {
  2250. this.history.transitionTo(this.history.getCurrentLocation());
  2251. }
  2252. };
  2253. Object.defineProperties( VueRouter.prototype, prototypeAccessors );
  2254. function registerHook (list, fn) {
  2255. list.push(fn);
  2256. return function () {
  2257. var i = list.indexOf(fn);
  2258. if (i > -1) { list.splice(i, 1); }
  2259. }
  2260. }
  2261. function createHref (base, fullPath, mode) {
  2262. var path = mode === 'hash' ? '#' + fullPath : fullPath;
  2263. return base ? cleanPath(base + '/' + path) : path
  2264. }
  2265. VueRouter.install = install;
  2266. VueRouter.version = '3.0.3';
  2267. if (inBrowser && window.Vue) {
  2268. window.Vue.use(VueRouter);
  2269. }
  2270. export default VueRouter;