No Description

router.js 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. /*eslint-disable*/
  2. module.exports =
  3. /******/ (function(modules) { // webpackBootstrap
  4. /******/ // The module cache
  5. /******/ var installedModules = {};
  6. /******/
  7. /******/ // The require function
  8. /******/ function __webpack_require__(moduleId) {
  9. /******/
  10. /******/ // Check if module is in cache
  11. /******/ if(installedModules[moduleId]) {
  12. /******/ return installedModules[moduleId].exports;
  13. /******/ }
  14. /******/ // Create a new module (and put it into the cache)
  15. /******/ var module = installedModules[moduleId] = {
  16. /******/ i: moduleId,
  17. /******/ l: false,
  18. /******/ exports: {}
  19. /******/ };
  20. /******/
  21. /******/ // Execute the module function
  22. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  23. /******/
  24. /******/ // Flag the module as loaded
  25. /******/ module.l = true;
  26. /******/
  27. /******/ // Return the exports of the module
  28. /******/ return module.exports;
  29. /******/ }
  30. /******/
  31. /******/
  32. /******/ // expose the modules object (__webpack_modules__)
  33. /******/ __webpack_require__.m = modules;
  34. /******/
  35. /******/ // expose the module cache
  36. /******/ __webpack_require__.c = installedModules;
  37. /******/
  38. /******/ // define getter function for harmony exports
  39. /******/ __webpack_require__.d = function(exports, name, getter) {
  40. /******/ if(!__webpack_require__.o(exports, name)) {
  41. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  42. /******/ }
  43. /******/ };
  44. /******/
  45. /******/ // define __esModule on exports
  46. /******/ __webpack_require__.r = function(exports) {
  47. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  48. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  49. /******/ }
  50. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  51. /******/ };
  52. /******/
  53. /******/ // create a fake namespace object
  54. /******/ // mode & 1: value is a module id, require it
  55. /******/ // mode & 2: merge all properties of value into the ns
  56. /******/ // mode & 4: return value when already ns object
  57. /******/ // mode & 8|1: behave like require
  58. /******/ __webpack_require__.t = function(value, mode) {
  59. /******/ if(mode & 1) value = __webpack_require__(value);
  60. /******/ if(mode & 8) return value;
  61. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  62. /******/ var ns = Object.create(null);
  63. /******/ __webpack_require__.r(ns);
  64. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  65. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  66. /******/ return ns;
  67. /******/ };
  68. /******/
  69. /******/ // getDefaultExport function for compatibility with non-harmony modules
  70. /******/ __webpack_require__.n = function(module) {
  71. /******/ var getter = module && module.__esModule ?
  72. /******/ function getDefault() { return module['default']; } :
  73. /******/ function getModuleExports() { return module; };
  74. /******/ __webpack_require__.d(getter, 'a', getter);
  75. /******/ return getter;
  76. /******/ };
  77. /******/
  78. /******/ // Object.prototype.hasOwnProperty.call
  79. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  80. /******/
  81. /******/ // __webpack_public_path__
  82. /******/ __webpack_require__.p = "";
  83. /******/
  84. /******/
  85. /******/ // Load entry module and return exports
  86. /******/ return __webpack_require__(__webpack_require__.s = "./src/index.ts");
  87. /******/ })
  88. /************************************************************************/
  89. /******/ ({
  90. /***/ "./node_modules/path-to-regexp/index.js":
  91. /*!**********************************************!*\
  92. !*** ./node_modules/path-to-regexp/index.jsx ***!
  93. \**********************************************/
  94. /*! no static exports found */
  95. /***/ (function(module, exports) {
  96. /**
  97. * Expose `pathToRegexp`.
  98. */
  99. module.exports = pathToRegexp
  100. module.exports.parse = parse
  101. module.exports.compile = compile
  102. module.exports.tokensToFunction = tokensToFunction
  103. module.exports.tokensToRegExp = tokensToRegExp
  104. /**
  105. * Default configs.
  106. */
  107. var DEFAULT_DELIMITER = '/'
  108. /**
  109. * The main path matching regexp utility.
  110. *
  111. * @type {RegExp}
  112. */
  113. var PATH_REGEXP = new RegExp([
  114. // Match escaped characters that would otherwise appear in future matches.
  115. // This allows the user to escape special characters that won't transform.
  116. '(\\\\.)',
  117. // Match Express-style parameters and un-named parameters with a prefix
  118. // and optional suffixes. Matches appear as:
  119. //
  120. // ":test(\\d+)?" => ["test", "\d+", undefined, "?"]
  121. // "(\\d+)" => [undefined, undefined, "\d+", undefined]
  122. '(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?'
  123. ].join('|'), 'g')
  124. /**
  125. * Parse a string for the raw tokens.
  126. *
  127. * @param {string} str
  128. * @param {Object=} options
  129. * @return {!Array}
  130. */
  131. function parse (str, options) {
  132. var tokens = []
  133. var key = 0
  134. var index = 0
  135. var path = ''
  136. var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER
  137. var whitelist = (options && options.whitelist) || undefined
  138. var pathEscaped = false
  139. var res
  140. while ((res = PATH_REGEXP.exec(str)) !== null) {
  141. var m = res[0]
  142. var escaped = res[1]
  143. var offset = res.index
  144. path += str.slice(index, offset)
  145. index = offset + m.length
  146. // Ignore already escaped sequences.
  147. if (escaped) {
  148. path += escaped[1]
  149. pathEscaped = true
  150. continue
  151. }
  152. var prev = ''
  153. var name = res[2]
  154. var capture = res[3]
  155. var group = res[4]
  156. var modifier = res[5]
  157. if (!pathEscaped && path.length) {
  158. var k = path.length - 1
  159. var c = path[k]
  160. var matches = whitelist ? whitelist.indexOf(c) > -1 : true
  161. if (matches) {
  162. prev = c
  163. path = path.slice(0, k)
  164. }
  165. }
  166. // Push the current path onto the tokens.
  167. if (path) {
  168. tokens.push(path)
  169. path = ''
  170. pathEscaped = false
  171. }
  172. var repeat = modifier === '+' || modifier === '*'
  173. var optional = modifier === '?' || modifier === '*'
  174. var pattern = capture || group
  175. var delimiter = prev || defaultDelimiter
  176. tokens.push({
  177. name: name || key++,
  178. prefix: prev,
  179. delimiter: delimiter,
  180. optional: optional,
  181. repeat: repeat,
  182. pattern: pattern
  183. ? escapeGroup(pattern)
  184. : '[^' + escapeString(delimiter === defaultDelimiter ? delimiter : (delimiter + defaultDelimiter)) + ']+?'
  185. })
  186. }
  187. // Push any remaining characters.
  188. if (path || index < str.length) {
  189. tokens.push(path + str.substr(index))
  190. }
  191. return tokens
  192. }
  193. /**
  194. * Compile a string to a template function for the path.
  195. *
  196. * @param {string} str
  197. * @param {Object=} options
  198. * @return {!function(Object=, Object=)}
  199. */
  200. function compile (str, options) {
  201. return tokensToFunction(parse(str, options))
  202. }
  203. /**
  204. * Expose a method for transforming tokens into the path function.
  205. */
  206. function tokensToFunction (tokens) {
  207. // Compile all the tokens into regexps.
  208. var matches = new Array(tokens.length)
  209. // Compile all the patterns before compilation.
  210. for (var i = 0; i < tokens.length; i++) {
  211. if (typeof tokens[i] === 'object') {
  212. matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$')
  213. }
  214. }
  215. return function (data, options) {
  216. var path = ''
  217. var encode = (options && options.encode) || encodeURIComponent
  218. for (var i = 0; i < tokens.length; i++) {
  219. var token = tokens[i]
  220. if (typeof token === 'string') {
  221. path += token
  222. continue
  223. }
  224. var value = data ? data[token.name] : undefined
  225. var segment
  226. if (Array.isArray(value)) {
  227. if (!token.repeat) {
  228. throw new TypeError('Expected "' + token.name + '" to not repeat, but got array')
  229. }
  230. if (value.length === 0) {
  231. if (token.optional) continue
  232. throw new TypeError('Expected "' + token.name + '" to not be empty')
  233. }
  234. for (var j = 0; j < value.length; j++) {
  235. segment = encode(value[j], token)
  236. if (!matches[i].test(segment)) {
  237. throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"')
  238. }
  239. path += (j === 0 ? token.prefix : token.delimiter) + segment
  240. }
  241. continue
  242. }
  243. if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  244. segment = encode(String(value), token)
  245. if (!matches[i].test(segment)) {
  246. throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"')
  247. }
  248. path += token.prefix + segment
  249. continue
  250. }
  251. if (token.optional) continue
  252. throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string'))
  253. }
  254. return path
  255. }
  256. }
  257. /**
  258. * Escape a regular expression string.
  259. *
  260. * @param {string} str
  261. * @return {string}
  262. */
  263. function escapeString (str) {
  264. return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1')
  265. }
  266. /**
  267. * Escape the capturing group by escaping special characters and meaning.
  268. *
  269. * @param {string} group
  270. * @return {string}
  271. */
  272. function escapeGroup (group) {
  273. return group.replace(/([=!:$/()])/g, '\\$1')
  274. }
  275. /**
  276. * Get the flags for a regexp from the options.
  277. *
  278. * @param {Object} options
  279. * @return {string}
  280. */
  281. function flags (options) {
  282. return options && options.sensitive ? '' : 'i'
  283. }
  284. /**
  285. * Pull out keys from a regexp.
  286. *
  287. * @param {!RegExp} path
  288. * @param {Array=} keys
  289. * @return {!RegExp}
  290. */
  291. function regexpToRegexp (path, keys) {
  292. if (!keys) return path
  293. // Use a negative lookahead to match only capturing groups.
  294. var groups = path.source.match(/\((?!\?)/g)
  295. if (groups) {
  296. for (var i = 0; i < groups.length; i++) {
  297. keys.push({
  298. name: i,
  299. prefix: null,
  300. delimiter: null,
  301. optional: false,
  302. repeat: false,
  303. pattern: null
  304. })
  305. }
  306. }
  307. return path
  308. }
  309. /**
  310. * Transform an array into a regexp.
  311. *
  312. * @param {!Array} path
  313. * @param {Array=} keys
  314. * @param {Object=} options
  315. * @return {!RegExp}
  316. */
  317. function arrayToRegexp (path, keys, options) {
  318. var parts = []
  319. for (var i = 0; i < path.length; i++) {
  320. parts.push(pathToRegexp(path[i], keys, options).source)
  321. }
  322. return new RegExp('(?:' + parts.join('|') + ')', flags(options))
  323. }
  324. /**
  325. * Create a path regexp from string input.
  326. *
  327. * @param {string} path
  328. * @param {Array=} keys
  329. * @param {Object=} options
  330. * @return {!RegExp}
  331. */
  332. function stringToRegexp (path, keys, options) {
  333. return tokensToRegExp(parse(path, options), keys, options)
  334. }
  335. /**
  336. * Expose a function for taking tokens and returning a RegExp.
  337. *
  338. * @param {!Array} tokens
  339. * @param {Array=} keys
  340. * @param {Object=} options
  341. * @return {!RegExp}
  342. */
  343. function tokensToRegExp (tokens, keys, options) {
  344. options = options || {}
  345. var strict = options.strict
  346. var start = options.start !== false
  347. var end = options.end !== false
  348. var delimiter = options.delimiter || DEFAULT_DELIMITER
  349. var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|')
  350. var route = start ? '^' : ''
  351. // Iterate over the tokens and create our regexp string.
  352. for (var i = 0; i < tokens.length; i++) {
  353. var token = tokens[i]
  354. if (typeof token === 'string') {
  355. route += escapeString(token)
  356. } else {
  357. var capture = token.repeat
  358. ? '(?:' + token.pattern + ')(?:' + escapeString(token.delimiter) + '(?:' + token.pattern + '))*'
  359. : token.pattern
  360. if (keys) keys.push(token)
  361. if (token.optional) {
  362. if (!token.prefix) {
  363. route += '(' + capture + ')?'
  364. } else {
  365. route += '(?:' + escapeString(token.prefix) + '(' + capture + '))?'
  366. }
  367. } else {
  368. route += escapeString(token.prefix) + '(' + capture + ')'
  369. }
  370. }
  371. }
  372. if (end) {
  373. if (!strict) route += '(?:' + escapeString(delimiter) + ')?'
  374. route += endsWith === '$' ? '$' : '(?=' + endsWith + ')'
  375. } else {
  376. var endToken = tokens[tokens.length - 1]
  377. var isEndDelimited = typeof endToken === 'string'
  378. ? endToken[endToken.length - 1] === delimiter
  379. : endToken === undefined
  380. if (!strict) route += '(?:' + escapeString(delimiter) + '(?=' + endsWith + '))?'
  381. if (!isEndDelimited) route += '(?=' + escapeString(delimiter) + '|' + endsWith + ')'
  382. }
  383. return new RegExp(route, flags(options))
  384. }
  385. /**
  386. * Normalize the given path string, returning a regular expression.
  387. *
  388. * An empty array can be passed in for the keys, which will hold the
  389. * placeholder key descriptions. For example, using `/user/:id`, `keys` will
  390. * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
  391. *
  392. * @param {(string|RegExp|Array)} path
  393. * @param {Array=} keys
  394. * @param {Object=} options
  395. * @return {!RegExp}
  396. */
  397. function pathToRegexp (path, keys, options) {
  398. if (path instanceof RegExp) {
  399. return regexpToRegexp(path, keys)
  400. }
  401. if (Array.isArray(path)) {
  402. return arrayToRegexp(/** @type {!Array} */ (path), keys, options)
  403. }
  404. return stringToRegexp(/** @type {string} */ (path), keys, options)
  405. }
  406. /***/ }),
  407. /***/ "./src/creat-route-map.ts":
  408. /*!********************************!*\
  409. !*** ./src/creat-route-map.ts ***!
  410. \********************************/
  411. /*! no static exports found */
  412. /***/ (function(module, exports, __webpack_require__) {
  413. "use strict";
  414. var __values = (this && this.__values) || function (o) {
  415. var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
  416. if (m) return m.call(o);
  417. return {
  418. next: function () {
  419. if (o && i >= o.length) o = void 0;
  420. return { value: o && o[i++], done: !o };
  421. }
  422. };
  423. };
  424. var __importDefault = (this && this.__importDefault) || function (mod) {
  425. return (mod && mod.__esModule) ? mod : { "default": mod };
  426. };
  427. Object.defineProperty(exports, "__esModule", { value: true });
  428. var path_to_regexp_1 = __importDefault(__webpack_require__(/*! path-to-regexp */ "./node_modules/path-to-regexp/index.js"));
  429. var path_1 = __webpack_require__(/*! ./utils/path */ "./src/utils/path.ts");
  430. function default_1(routes) {
  431. var e_1, _a;
  432. var routeMap = new Map();
  433. try {
  434. for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
  435. var $route = routes_1_1.value;
  436. createRouteRecoed($route);
  437. }
  438. }
  439. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  440. finally {
  441. try {
  442. if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
  443. }
  444. finally { if (e_1) throw e_1.error; }
  445. }
  446. return routeMap;
  447. //递归遍历,编写路由定义时确保*在最后一个
  448. function createRouteRecoed(route, parent) {
  449. var keys = [];
  450. var path = path_1.normalizePath(route.path, parent);
  451. var componentName = route.component;
  452. var regex = path_to_regexp_1.default(path, keys);
  453. var record = {
  454. abstract: !!route.abstract,
  455. path: path,
  456. componentName: componentName,
  457. regex: regex,
  458. paramsName: keys.filter(function (key) { return !key.optional; }).map(function (key) { return key.name; })
  459. };
  460. if (parent)
  461. record.parentPath = parent.path;
  462. if (parent)
  463. record.parent = parent;
  464. routeMap.set(path, record);
  465. if (route.children) {
  466. record.children=route.children.map(function ($route) { return createRouteRecoed($route, record); });
  467. }
  468. return record;
  469. }
  470. }
  471. exports.default = default_1;
  472. /***/ }),
  473. /***/ "./src/get-match.ts":
  474. /*!**************************!*\
  475. !*** ./src/get-match.ts ***!
  476. \**************************/
  477. /*! no static exports found */
  478. /***/ (function(module, exports, __webpack_require__) {
  479. "use strict";
  480. var __values = (this && this.__values) || function (o) {
  481. var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
  482. if (m) return m.call(o);
  483. return {
  484. next: function () {
  485. if (o && i >= o.length) o = void 0;
  486. return { value: o && o[i++], done: !o };
  487. }
  488. };
  489. };
  490. Object.defineProperty(exports, "__esModule", { value: true });
  491. function matchRecord(path, routeRecord) {
  492. var e_1, _a;
  493. try {
  494. for (var _b = __values(routeRecord.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  495. let paramPath = path;
  496. var record = _c.value;
  497. if (paramPath.split('/').length < record.path.split('/').length) {
  498. paramPath += '/0';
  499. }
  500. var matchVal = record.regex.exec(paramPath);
  501. if (matchVal) {
  502. var params = {};
  503. var componentNameList = getComponentNameList(record);
  504. for (var i = 0; i < record.paramsName.length; i++) {
  505. params[record.paramsName[i]] = matchVal[i + 1];
  506. }
  507. return { params: params, componentNameList: componentNameList, path: path,record:record };
  508. }
  509. }
  510. }
  511. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  512. finally {
  513. try {
  514. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  515. }
  516. finally { if (e_1) throw e_1.error; }
  517. }
  518. }
  519. exports.matchRecord = matchRecord;
  520. function getComponentNameList(record) {
  521. var componentNameList = [];
  522. recursiveRecord(record);
  523. return componentNameList;
  524. function recursiveRecord(record) {
  525. if (record.componentName) {
  526. componentNameList.unshift(record.componentName);
  527. }
  528. if (record.parent)
  529. recursiveRecord(record.parent);
  530. }
  531. }
  532. /***/ }),
  533. /***/ "./src/index.ts":
  534. /*!**********************!*\
  535. !*** ./src/index.ts ***!
  536. \**********************/
  537. /*! no static exports found */
  538. /***/ (function(module, exports, __webpack_require__) {
  539. "use strict";
  540. var __importDefault = (this && this.__importDefault) || function (mod) {
  541. return (mod && mod.__esModule) ? mod : { "default": mod };
  542. };
  543. Object.defineProperty(exports, "__esModule", { value: true });
  544. var warn_1 = __webpack_require__(/*! ./utils/warn */ "./src/utils/warn.ts");
  545. var const_1 = __webpack_require__(/*! ./utils/const */ "./src/utils/const.ts");
  546. var router_1 = __importDefault(__webpack_require__(/*! ./router */ "./src/router.ts"));
  547. function default_1(config) {
  548. if (!this)
  549. warn_1.error('this is not found');
  550. var __router = new router_1.default(config);
  551. var namespace = '$router';
  552. if (config && config.option && config.option.namespace) {
  553. namespace = config.option.namespace;
  554. }
  555. this[namespace] = {
  556. get currentPath() {
  557. return __router.currentPath;
  558. },
  559. get params() {
  560. return __router.params;
  561. },
  562. //方法
  563. get push() {
  564. return __router.push.bind(__router);
  565. },
  566. get replace() {
  567. return __router.replace.bind(__router);
  568. },
  569. get setBeforeChange() {
  570. return __router.setBeforeChange.bind(__router);
  571. },
  572. get setAfterChange() {
  573. return __router.setAfterChange.bind(__router);
  574. },
  575. get addParamsListener() {
  576. return __router.addParamsListener.bind(__router);
  577. },
  578. get removeParamsListener() {
  579. return __router.removeParamsListener.bind(__router);
  580. },
  581. };
  582. this[const_1.mountName] = __router;
  583. }
  584. exports.default = default_1;
  585. /***/ }),
  586. /***/ "./src/router.ts":
  587. /*!***********************!*\
  588. !*** ./src/router.ts ***!
  589. \***********************/
  590. /*! no static exports found */
  591. /***/ (function(module, exports, __webpack_require__) {
  592. "use strict";
  593. var __values = (this && this.__values) || function (o) {
  594. var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
  595. if (m) return m.call(o);
  596. return {
  597. next: function () {
  598. if (o && i >= o.length) o = void 0;
  599. return { value: o && o[i++], done: !o };
  600. }
  601. };
  602. };
  603. var __read = (this && this.__read) || function (o, n) {
  604. var m = typeof Symbol === "function" && o[Symbol.iterator];
  605. if (!m) return o;
  606. var i = m.call(o), r, ar = [], e;
  607. try {
  608. while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  609. }
  610. catch (error) { e = { error: error }; }
  611. finally {
  612. try {
  613. if (r && !r.done && (m = i["return"])) m.call(i);
  614. }
  615. finally { if (e) throw e.error; }
  616. }
  617. return ar;
  618. };
  619. var __importDefault = (this && this.__importDefault) || function (mod) {
  620. return (mod && mod.__esModule) ? mod : { "default": mod };
  621. };
  622. Object.defineProperty(exports, "__esModule", { value: true });
  623. var warn_1 = __webpack_require__(/*! ./utils/warn */ "./src/utils/warn.ts");
  624. var creat_route_map_1 = __importDefault(__webpack_require__(/*! ./creat-route-map */ "./src/creat-route-map.ts"));
  625. var get_match_1 = __webpack_require__(/*! ./get-match */ "./src/get-match.ts");
  626. var Router = /** @class */ (function () {
  627. function Router(config) {
  628. if (config === void 0) { config = {}; }
  629. this.histry = [];
  630. this.registerComponents = new Map();
  631. this.routeRecord = new Map();
  632. this.waitCallComponents = [];
  633. this.onParamsHooks = new Map();
  634. this.__beforePathChange = null;
  635. this.__afterPathChange = null;
  636. this.currentPath = '';
  637. this.params = {};
  638. this.query = {};
  639. if (!config.routes)
  640. warn_1.error('not found routes in config');
  641. this.routeRecord = creat_route_map_1.default(config.routes);
  642. //不设置初始initPath的话,默认为 /
  643. var initPath = '/';
  644. if (config.option && config.option.initPath)
  645. initPath = config.option.initPath;
  646. this.push(initPath);
  647. }
  648. Router.prototype.__matchrouteRecord = function (path) {
  649. var e_1, _a;
  650. var result = get_match_1.matchRecord(path, this.routeRecord);
  651. //没有匹配到路由
  652. if (!result) {
  653. this.__clearComponentName();
  654. return;
  655. }
  656. this.waitCallComponents = result.componentNameList;
  657. try {
  658. //触发router-view变化
  659. for (var _b = __values(this.registerComponents.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  660. var com = _c.value;
  661. var oldName = com.data.name;
  662. var newName = this.waitCallComponents.shift();
  663. com.setData({ name: newName });
  664. if (oldName !== newName)
  665. break;
  666. }
  667. }
  668. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  669. finally {
  670. try {
  671. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  672. }
  673. finally { if (e_1) throw e_1.error; }
  674. }
  675. this.currentPath = result.path;
  676. //触发路由参数变化
  677. this.__setParams(result.params);
  678. };
  679. Router.prototype.__clearComponentName = function () {
  680. var e_2, _a;
  681. if (this.registerComponents.size > 0) {
  682. try {
  683. for (var _b = __values(this.registerComponents.values()), _c = _b.next(); !_c.done; _c = _b.next()) {
  684. var _com = _c.value;
  685. _com.setData({ name: null });
  686. break;
  687. }
  688. }
  689. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  690. finally {
  691. try {
  692. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  693. }
  694. finally { if (e_2) throw e_2.error; }
  695. }
  696. }
  697. this.currentPath = '';
  698. this.__setParams(Object.create(null));
  699. };
  700. Router.prototype.__invokeBeforeHooks = function (nextPath) {
  701. if (this.__beforePathChange === null)
  702. return true;
  703. return this.__beforePathChange(this.currentPath, nextPath);
  704. };
  705. Router.prototype.__invokeAfterHooks = function () {
  706. if (this.__afterPathChange === null)
  707. return true;
  708. return this.__afterPathChange();
  709. };
  710. Router.prototype.__setCurrentPath = function (path) {
  711. this.currentPath = path;
  712. };
  713. Router.prototype.__setParams = function (params) {
  714. var e_3, _a;
  715. var oldParams = this.params;
  716. this.params = params;
  717. try {
  718. for (var _b = __values(this.onParamsHooks.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
  719. var _d = __read(_c.value, 2), com = _d[0], methodName = _d[1];
  720. if (com)
  721. com[methodName](oldParams, params);
  722. }
  723. }
  724. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  725. finally {
  726. try {
  727. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  728. }
  729. finally { if (e_3) throw e_3.error; }
  730. }
  731. };
  732. Router.prototype.registerComponent = function (_this) {
  733. var $id = _this.$id;
  734. if (this.waitCallComponents.length > 0)
  735. _this.setData({ name: this.waitCallComponents.shift() });
  736. this.registerComponents.set($id, _this);
  737. };
  738. Router.prototype.removeComponent = function (_this) {
  739. var $id = _this.$id;
  740. var success = this.registerComponents.delete($id);
  741. if (!success)
  742. warn_1.warn('delete router-view fail');
  743. };
  744. Router.prototype.go = function (n) { };
  745. Router.prototype.push = function (path) {
  746. if (!this.__invokeBeforeHooks(path))
  747. return;
  748. path = this.getPathForAbstract(path);
  749. this.__matchrouteRecord(path);
  750. this.histry.push(path);
  751. this.__setCurrentPath(path);
  752. this.__invokeAfterHooks && this.__invokeAfterHooks();
  753. };
  754. Router.prototype.replace = function (path) {
  755. if (!this.__invokeBeforeHooks(path))
  756. return;
  757. path = this.getPathForAbstract(path);
  758. this.__matchrouteRecord(path);
  759. this.histry.pop();
  760. this.histry.push(path);
  761. this.__setCurrentPath(path);
  762. this.__invokeAfterHooks && this.__invokeAfterHooks();
  763. };
  764. Router.prototype.getPathForAbstract = function (path) {
  765. let result = get_match_1.matchRecord(path, this.routeRecord);
  766. if (!result) {
  767. debugger;
  768. }
  769. let record = result.record;
  770. if (record.abstract == true && record.children && record.children.length) {
  771. let defaultChild = record.children.find(item => item.default);
  772. if (!defaultChild) {
  773. defaultChild = record.children[0];
  774. }
  775. path = path.replace(new RegExp("^" + record.path), defaultChild.path);
  776. return path;
  777. }
  778. return path;
  779. };
  780. Router.prototype.setBeforeChange = function (_this, methodName) {
  781. if (_this === null) {
  782. this.__beforePathChange = null;
  783. return;
  784. }
  785. if (_this[methodName] instanceof Function) {
  786. this.__beforePathChange = _this[methodName].bind(_this);
  787. }
  788. };
  789. Router.prototype.setAfterChange = function (_this, methodName) {
  790. if (_this === null) {
  791. this.__afterPathChange = null;
  792. return;
  793. }
  794. if (_this[methodName] instanceof Function) {
  795. this.__afterPathChange = _this[methodName].bind(_this);
  796. }
  797. };
  798. Router.prototype.addParamsListener = function (_this, methodName) {
  799. if (_this[methodName] instanceof Function) {
  800. this.onParamsHooks.set(_this, methodName);
  801. return;
  802. }
  803. warn_1.warn(_this.is + ": can't found methor [" + methodName + "]");
  804. };
  805. Router.prototype.removeParamsListener = function (_this) {
  806. this.onParamsHooks.delete(_this);
  807. };
  808. return Router;
  809. }());
  810. exports.default = Router;
  811. /***/ }),
  812. /***/ "./src/utils/const.ts":
  813. /*!****************************!*\
  814. !*** ./src/utils/const.ts ***!
  815. \****************************/
  816. /*! no static exports found */
  817. /***/ (function(module, exports, __webpack_require__) {
  818. "use strict";
  819. Object.defineProperty(exports, "__esModule", { value: true });
  820. exports.mountName = '__routerInstance';
  821. /***/ }),
  822. /***/ "./src/utils/path.ts":
  823. /*!***************************!*\
  824. !*** ./src/utils/path.ts ***!
  825. \***************************/
  826. /*! no static exports found */
  827. /***/ (function(module, exports, __webpack_require__) {
  828. "use strict";
  829. Object.defineProperty(exports, "__esModule", { value: true });
  830. function cleanPath(path) {
  831. return path.replace(/\/\//g, '/');
  832. }
  833. exports.cleanPath = cleanPath;
  834. function normalizePath(path, parent) {
  835. if (!parent)
  836. return path;
  837. return cleanPath(parent.path + "/" + path);
  838. }
  839. exports.normalizePath = normalizePath;
  840. /***/ }),
  841. /***/ "./src/utils/warn.ts":
  842. /*!***************************!*\
  843. !*** ./src/utils/warn.ts ***!
  844. \***************************/
  845. /*! no static exports found */
  846. /***/ (function(module, exports, __webpack_require__) {
  847. "use strict";
  848. Object.defineProperty(exports, "__esModule", { value: true });
  849. function error(message) {
  850. throw new Error("[miniapp-router] " + message);
  851. }
  852. exports.error = error;
  853. function warn(message) {
  854. console.warn("[miniapp-router] " + message);
  855. }
  856. exports.warn = warn;
  857. /***/ })
  858. /******/ });
  859. //# sourceMappingURL=router.js.map