From 67c74f8b9d478336e7894be593d6690aa0c5307f Mon Sep 17 00:00:00 2001 From: guoxl Date: Tue, 1 Oct 2019 12:07:07 +0800 Subject: [PATCH] update esm --- esm/index.js | 9 -- esm/match-path.js | 10 ++ esm/router-link.js | 210 +++++++++++++++++++++++++++++++++++++ esm/router-view.js | 210 ++++++++++++++++--------------------- esm/router.js | 134 ++++++++++-------------- esm/util.js | 255 ++++++++++++++++++++++++++++++++++----------- 6 files changed, 557 insertions(+), 271 deletions(-) create mode 100644 esm/router-link.js diff --git a/esm/index.js b/esm/index.js index 17853cf..fd816b0 100644 --- a/esm/index.js +++ b/esm/index.js @@ -12,18 +12,11 @@ Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { - RouterLink: true, RouterView: true, useRouteGuards: true, REACT_FORWARD_REF_TYPE: true, lazyImport: true }; -Object.defineProperty(exports, "RouterLink", { - enumerable: true, - get: function get() { - return _reactRouterDom.NavLink; - } -}); Object.defineProperty(exports, "RouterView", { enumerable: true, get: function get() { @@ -52,8 +45,6 @@ exports.default = void 0; var _router = _interopRequireDefault(require("./router")); -var _reactRouterDom = require("react-router-dom"); - var _routerView = _interopRequireDefault(require("./router-view")); var _routeGuard = require("./route-guard"); diff --git a/esm/match-path.js b/esm/match-path.js index b73647f..5bdc814 100644 --- a/esm/match-path.js +++ b/esm/match-path.js @@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); +exports.computeRootMatch = computeRootMatch; exports.default = void 0; require("core-js/modules/es6.string.iterator"); @@ -114,5 +115,14 @@ function matchPath(pathname) { }, null); } +function computeRootMatch(pathname) { + return { + path: '/', + url: '/', + params: {}, + isExact: pathname === '/' + }; +} + var _default = matchPath; exports.default = _default; \ No newline at end of file diff --git a/esm/router-link.js b/esm/router-link.js new file mode 100644 index 0000000..2aebfad --- /dev/null +++ b/esm/router-link.js @@ -0,0 +1,210 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; + +require("core-js/modules/es6.string.iterator"); + +require("core-js/modules/es6.array.from"); + +require("core-js/modules/es6.regexp.to-string"); + +require("core-js/modules/es7.symbol.async-iterator"); + +require("core-js/modules/es6.symbol"); + +require("core-js/modules/web.dom.iterable"); + +require("core-js/modules/es6.array.iterator"); + +require("core-js/modules/es6.object.to-string"); + +require("core-js/modules/es6.object.keys"); + +require("core-js/modules/es6.object.set-prototype-of"); + +require("core-js/modules/es6.string.starts-with"); + +require("core-js/modules/es6.regexp.replace"); + +var _react = _interopRequireDefault(require("react")); + +var _propTypes = _interopRequireDefault(require("prop-types")); + +var _util = require("./util"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } + +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function guardEvent(e) { + // don't redirect with control keys + if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return; // don't redirect when preventDefault called + + if (e.defaultPrevented) return; // don't redirect on right click + + if (e.button !== undefined && e.button !== 0) return; // don't redirect if `target="_blank"` + + if (e.currentTarget && e.currentTarget.getAttribute) { + var target = e.currentTarget.getAttribute('target'); + if (/\b_blank\b/i.test(target)) return; + } // this may be a Weex event which doesn't have this method + + + if (e.preventDefault) { + e.preventDefault(); + } + + return true; +} + +function _default(router) { + var _class, _temp; + + return _temp = _class = + /*#__PURE__*/ + function (_React$Component) { + _inherits(RouterLink, _React$Component); + + function RouterLink(props) { + var _this; + + _classCallCheck(this, RouterLink); + + _this = _possibleConstructorReturn(this, _getPrototypeOf(RouterLink).call(this, props)); + _this.state = { + inited: false, + currentRoute: router.currentRoute, + parentRoute: null + }; + return _this; + } + + _createClass(RouterLink, [{ + key: "componentDidMount", + value: function componentDidMount() { + var _this2 = this; + + this.unplugin = router.plugin({ + name: 'router-link-plugin', + onRouteChange: function onRouteChange(currentRoute) { + return _this2.setState({ + currentRoute: currentRoute + }); + } + }); + var routerView = (0, _util.getParentRouterView)(this); + this.setState({ + inited: true, + parentRoute: routerView ? routerView.state.currentRoute : null + }); + } + }, { + key: "componentWillUnmount", + value: function componentWillUnmount() { + if (this.unplugin) this.unplugin(); + } + }, { + key: "shouldComponentUpdate", + value: function shouldComponentUpdate(nextProps, nextState) { + if (this.props.to !== nextProps.to) return true; + if (this.props.replace !== nextProps.replace) return true; + if (this.props.tag !== nextProps.tag) return true; + if (this.props.activeClass !== nextProps.activeClass) return true; + if (this.props.exact !== nextProps.exact) return true; + if (this.props.exactActiveClass !== nextProps.exactActiveClass) return true; + if (this.props.event !== nextProps.event) return true; + if (this.state.inited !== nextState.inited) return true; + if ((0, _util.isRouteChanged)(this.state.parentRoute, nextState.parentRoute)) return true; + if ((0, _util.isRouteChanged)(this.state.currentRoute, nextState.currentRoute)) return true; + return false; + } + }, { + key: "render", + value: function render() { + if (!this.state.inited) return null; + + var _this$props = this.props, + tag = _this$props.tag, + to = _this$props.to, + exact = _this$props.exact, + replace = _this$props.replace, + append = _this$props.append, + event = _this$props.event, + _this$props$children = _this$props.children, + children = _this$props$children === void 0 ? [] : _this$props$children, + activeClass = _this$props.activeClass, + exactActiveClass = _this$props.exactActiveClass, + remainProps = _objectWithoutProperties(_this$props, ["tag", "to", "exact", "replace", "append", "event", "children", "activeClass", "exactActiveClass"]); + + var current = this.state.currentRoute; + to = (0, _util.normalizeLocation)(to, this.state.parentRoute, append); + if (router.linkActiveClass) activeClass = router.linkActiveClass; + if (router.linkExactActiveClass) exactActiveClass = router.linkExactActiveClass; + var fallbackClass = exact ? to.path === current.path ? exactActiveClass : '' : current.path.startsWith(to.path) ? activeClass : ''; + + if (fallbackClass) { + if (remainProps.className) remainProps.className = "".concat(fallbackClass, " ").concat(remainProps.className);else remainProps.className = fallbackClass; + } + + if (!Array.isArray(event)) event = [event]; + event.forEach(function (evt) { + remainProps[(0, _util.camelize)("on-".concat(evt))] = function (e) { + guardEvent(e); + if (replace) router.replace(to);else router.push(to); + }; + }); + if (tag === 'a') remainProps.href = to.path; + return _react.default.createElement.apply(_react.default, [tag, remainProps].concat(_toConsumableArray(children))); + } + }]); + + return RouterLink; + }(_react.default.Component), _defineProperty(_class, "propTypes", { + to: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.object]).isRequired, + replace: _propTypes.default.bool, + append: _propTypes.default.bool, + tag: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.elementType]), + activeClass: _propTypes.default.string, + exact: _propTypes.default.bool, + exactActiveClass: _propTypes.default.string, + event: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.arrayOf(_propTypes.default.string)]) + }), _defineProperty(_class, "defaultProps", { + tag: 'a', + activeClass: 'router-link-active', + exactActiveClass: 'exact-active-class', + event: 'click' + }), _temp; +} \ No newline at end of file diff --git a/esm/router-view.js b/esm/router-view.js index ba602fa..57a8682 100644 --- a/esm/router-view.js +++ b/esm/router-view.js @@ -39,12 +39,8 @@ require("core-js/modules/es6.number.constructor"); var _react = _interopRequireDefault(require("react")); -var _reactRouterDom = require("react-router-dom"); - var _util = require("./util"); -var _config = _interopRequireDefault(require("./config")); - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } @@ -121,17 +117,11 @@ function (_React$Component) { _createClass(RouterView, [{ key: "_updateRef", value: function _updateRef(ref) { - var newRoute = this._refreshCurrentRoute(); - - var oldRoute = this.state.currentRoute; - - if (newRoute) { - newRoute.componentInstances[this.name] = ref; - } - + var currentRoute = this.state.currentRoute; + if (currentRoute) currentRoute.componentInstances[this.name] = ref; if (this.props && this.props._updateRef) this.props._updateRef(ref); - if (oldRoute !== newRoute) this.setState({ - currentRoute: newRoute + this.setState({ + currentRoute: currentRoute }); } }, { @@ -149,14 +139,27 @@ function (_React$Component) { if (filter) ret = filter(ret); return ret; } + }, { + key: "_getRouteMatch", + value: function _getRouteMatch(state) { + var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + if (!state) state = this.state; + var matched = state.router.currentRoute && state.router.currentRoute.matched || []; + return matched.length > depth ? matched[depth] : null; + } }, { key: "_refreshCurrentRoute", value: function _refreshCurrentRoute(state) { if (!state) state = this.state; - var matched = state.router.currentRoute && state.router.currentRoute.matched || []; - var ret = matched.length > state._routerDepth ? matched[state._routerDepth] : null; - if (ret) ret.viewInstance = this; - return ret; + + var currentRoute = this._getRouteMatch(state, state._routerDepth); + + if (!currentRoute || currentRoute.redirect) currentRoute = null; + if (currentRoute) currentRoute.viewInstances[this.name] = this; + if (this.state && this.state._routerInited) this.setState({ + currentRoute: currentRoute + }); + return currentRoute; } }, { key: "_updateResolving", @@ -190,7 +193,7 @@ function (_React$Component) { regeneratorRuntime.mark(function _callee() { var _this2 = this; - var state, props, parent, memoizedState, memoizedProps, matched; + var state, parent; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { @@ -204,68 +207,54 @@ function (_React$Component) { case 2: state = _objectSpread({}, this.state); - props = this.props || {}; - if (!(props.depth === undefined && this._reactInternalFiber)) { - _context.next = 19; + if (!(state._routerRoot && state.router)) { + _context.next = 7; break; } - parent = this._reactInternalFiber.return; + state.router.viewRoot = this; - case 6: - if (!(parent && parent.type !== _reactRouterDom.Router)) { - _context.next = 19; - break; - } + state.router._handleRouteInterceptor(state.router.history.location, function (ok) { + if (!ok) return; + state.currentRoute = _this2._refreshCurrentRoute(); + + _this2.setState(Object.assign(state, { + _routerInited: true + })); + }, true); - memoizedState = parent.memoizedState; - memoizedProps = parent.memoizedProps; + return _context.abrupt("return"); - if (!(memoizedState && memoizedState._routerView)) { - _context.next = 15; + case 7: + if (this._reactInternalFiber) { + _context.next = 9; break; } - state._routerRoot = false; - state._routerParent = memoizedState._routerView; - if (!state.router) state.router = memoizedState.router; - state._routerDepth = memoizedState._routerDepth + 1; - return _context.abrupt("break", 19); - - case 15: - if (!state.router && parent.type === _reactRouterDom.Router && memoizedProps && memoizedProps.history) state.router = memoizedProps.history; - parent = parent.return; - _context.next = 6; - break; - - case 19: - if (!state.routes.length) { - matched = state.router.currentRoute && state.router.currentRoute.matched || []; - state.currentRoute = this._refreshCurrentRoute(state); + return _context.abrupt("return"); - if (state._routerDepth) { - // state.router.updateRoute(); - state.parentRoute = matched.length >= state._routerDepth ? matched[state._routerDepth - 1] : null; - state.routes = state.parentRoute ? this._filterRoutes(state.parentRoute.config.children) : []; - } + case 9: + parent = (0, _util.getParentRouterView)(this); + + if (parent) { + state._routerRoot = false; + state._routerParent = parent.state._routerView; + if (!state.router) state.router = parent.state.router; + state._routerDepth = parent.state._routerDepth + 1; } - if (state._routerRoot && state.router) { - state.router.viewRoot = this; + if (state._routerDepth) { + state.currentRoute = this._refreshCurrentRoute(state); + state.parentRoute = this._getRouteMatch(state, state._routerDepth - 1); + state.routes = state.parentRoute ? this._filterRoutes(state.parentRoute.config.children) : []; + } else console.error('[RouterView] cannot find root RouterView instance!', this); - state.router._handleRouteInterceptor(state.router.history.location, function (ok) { - return ok && _this2.setState(Object.assign(state, { - _routerInited: true - })); - }, true); - } else { - this.setState(Object.assign(state, { - _routerInited: true - })); - } + this.setState(Object.assign(state, { + _routerInited: true + })); - case 21: + case 13: case "end": return _context.stop(); } @@ -279,36 +268,16 @@ function (_React$Component) { return componentDidMount; }() - }, { - key: "isRouteChanged", - value: function isRouteChanged(prev, next) { - if (prev && next) return prev.path !== next.path; - if ((!prev || !next) && prev !== next) return true; - return false; - } - }, { - key: "isRoutesChanged", - value: function isRoutesChanged(prevs, nexts) { - var _this3 = this; - - if (!prevs || !nexts) return true; - if (prevs.length !== nexts.length) return true; - var changed = false; - prevs.some(function (prev, i) { - changed = _this3.isRouteChanged(prev, nexts[i]); - return changed; - }); - return changed; - } }, { key: "shouldComponentUpdate", value: function shouldComponentUpdate(nextProps, nextState) { + if (this.props.name !== nextProps.name) return true; if (this.state._routerResolving !== nextState._routerResolving) return true; if (this.state._routerInited !== nextState._routerInited) return true; if (this.state._routerDepth !== nextState._routerDepth) return true; if (this.state.router !== nextState.router) return true; - if (this.isRouteChanged(this.state.parentRoute, nextState.parentRoute)) return true; - if (this.isRoutesChanged(this.state.routes, nextState.routes)) return true; + if ((0, _util.isRouteChanged)(this.state.currentRoute, nextState.currentRoute)) return true; + if ((0, _util.isRoutesChanged)(this.state.routes, nextState.routes)) return true; return false; } }, { @@ -371,36 +340,39 @@ function (_React$Component) { }, { key: "render", value: function render() { - var _this$state = this.state, - routes = _this$state.routes, - _routerResolving = _this$state._routerResolving, - _routerInited = _this$state._routerInited; // eslint-disable-next-line - - var _ref = this.props || {}, - _updateRef = _ref._updateRef, - container = _ref.container, - router = _ref.router, - props = _objectWithoutProperties(_ref, ["_updateRef", "container", "router"]); - - if (!_routerInited) return this._resolveFallback(); - var _this$state$router$cu = this.state.router.currentRoute, - query = _this$state$router$cu.query, - params = _this$state$router$cu.params; - var ret = renderRoute(routes, props, { - name: this.name, - query: query, - params: params, - container: container, - ref: this._updateRef - }); - if (_routerResolving) ret = _react.default.createElement(_react.default.Fragment, {}, ret, this._resolveFallback());else if (!ret) ret = this._resolveFallback(); + if (!this.state._routerInited) return this._resolveFallback(); + var currentRoute = this.state.currentRoute; + var ret = null; + + if (currentRoute) { + var routes = this.state.routes; // eslint-disable-next-line + + var _ref = this.props || {}, + _updateRef = _ref._updateRef, + container = _ref.container, + router = _ref.router, + children = _ref.children, + props = _objectWithoutProperties(_ref, ["_updateRef", "container", "router", "children"]); + + var _this$state$router$cu = this.state.router.currentRoute, + query = _this$state$router$cu.query, + params = _this$state$router$cu.params; + ret = (0, _util.renderRoute)(currentRoute, routes, props, children, { + name: this.name, + query: query, + params: params, + container: container, + ref: this._updateRef + }); + } + + if (this.state._routerResolving && ret) ret = _react.default.createElement(_react.default.Fragment, {}, ret, this._resolveFallback());else if (!ret) ret = this._resolveFallback(); return ret; } }, { key: "name", get: function get() { - var name = this.props.name; - return name || 'default'; + return this.props.name || 'default'; } }]); @@ -408,17 +380,9 @@ function (_React$Component) { }(_react.default.Component); var _default = _react.default.forwardRef(function (props, ref) { - var ret = _react.default.createElement(RouterView, _objectSpread({}, props, { + return _react.default.createElement(RouterView, _objectSpread({}, props, { _updateRef: ref })); - - if (props.router) { - ret = _react.default.createElement(_reactRouterDom.Router, { - history: props.router - }, ret); - } - - return ret; }); exports.default = _default; \ No newline at end of file diff --git a/esm/router.js b/esm/router.js index 9a370ec..da4519e 100644 --- a/esm/router.js +++ b/esm/router.js @@ -53,6 +53,8 @@ var _routeLazy = require("./route-lazy"); var _routeGuard = require("./route-guard"); +var _routerLink = _interopRequireDefault(require("./router-link")); + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } @@ -84,7 +86,7 @@ function _routetInterceptors() { _routetInterceptors = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee6(interceptors, to, from, next) { - var isBlock, routetInterceptor, _routetInterceptor, i, interceptor; + var isBlock, routetInterceptor, _routetInterceptor; return regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { @@ -212,7 +214,7 @@ function _routetInterceptors() { }; if (!next) { - _context6.next = 7; + _context6.next = 8; break; } @@ -220,58 +222,13 @@ function _routetInterceptors() { return routetInterceptor(interceptors[0], 0, to, from, next); case 6: - return _context6.abrupt("return", _context6.sent); - - case 7: - i = 0; - - case 8: - if (!(i < interceptors.length)) { - _context6.next = 25; - break; - } - - interceptor = interceptors[i]; - - case 10: - if (!(interceptor && interceptor.lazy)) { - _context6.next = 16; - break; - } - - _context6.next = 13; - return interceptor(interceptors, i); - - case 13: - interceptor = _context6.sent; - _context6.next = 10; + _context6.next = 9; break; - case 16: - if (interceptor) { - _context6.next = 18; - break; - } - - return _context6.abrupt("return"); - - case 18: - _context6.t0 = interceptor; - - if (!_context6.t0) { - _context6.next = 22; - break; - } - - _context6.next = 22; - return interceptor(to, from); - - case 22: - i++; - _context6.next = 8; - break; + case 8: + (0, _util.afterInterceptors)(interceptors, to, from); - case 25: + case 9: case "end": return _context6.stop(); } @@ -322,11 +279,11 @@ function () { this.mode = options.mode; this.basename = options.basename || ''; this.routes = []; + this.plugins = []; this.beforeEachGuards = []; this.afterEachGuards = []; this.currentRoute = null; this.viewRoot = null; - this.plugins = []; this._unlisten = this.history.listen(function (location) { return _this.updateRoute(location); }); @@ -389,7 +346,7 @@ function () { }).filter(function (v) { return v !== undefined; }); - return ret.length === 1 ? ret[0] : ret; + return ret; } catch (ex) { if (plugin && plugin.name && ex && ex.message) ex.message = "[".concat(plugin.name, ":").concat(event, "]").concat(ex.message); throw ex; @@ -514,7 +471,7 @@ function () { } }, { key: "_getChangeMatched", - value: function _getChangeMatched(route, compare) { + value: function _getChangeMatched(route, compare, count) { var ret = []; if (!compare) return _toConsumableArray(route.matched); var start = false; @@ -527,6 +484,7 @@ function () { } ret.push(tr); + return count !== undefined && ret.length === count; }); return ret.filter(function (r) { return !r.redirect; @@ -534,7 +492,7 @@ function () { } }, { key: "_getBeforeEachGuards", - value: function _getBeforeEachGuards(to, from) { + value: function _getBeforeEachGuards(to, from, current) { var _this3 = this; var ret = _toConsumableArray(this.beforeEachGuards); @@ -573,13 +531,14 @@ function () { ret.push.apply(ret, _toConsumableArray(guards)); }); + if (from !== current) tm = this._getChangeMatched(to, current); tm.forEach(function (r) { var compGuards = {}; var allGuards = _this3._getComponentGurads(r, 'afterRouteEnter', function (fn, name) { if (!compGuards[name]) compGuards[name] = []; compGuards[name].push(function () { - return fn.call(this, to, from); + return fn.call(this, to, current); }); return null; }); @@ -605,7 +564,9 @@ function () { if (!fr || fr.path !== tr.path) return true; fm.push(fr); }); - ret.push.apply(ret, _toConsumableArray(this._getRouteComponentGurads(fm, 'beforeRouteUpdate', true))); + ret.push.apply(ret, _toConsumableArray(this._getRouteComponentGurads(fm.filter(function (r) { + return !r.redirect; + }), 'beforeRouteUpdate', true))); return ret; } }, { @@ -621,10 +582,7 @@ function () { }); ret.push.apply(ret, _toConsumableArray(this._getRouteComponentGurads(fm, 'afterRouteLeave', true))); - } // if (to) { - // const tm = this._getChangeMatched(to, from); - // } - + } ret.push.apply(ret, _toConsumableArray(this.afterEachGuards)); return (0, _util.flatten)(ret); @@ -682,6 +640,7 @@ function () { isContinue, to, from, + current, fallbackView, _args3 = arguments; return regeneratorRuntime.wrap(function _callee3$(_context3) { @@ -703,26 +662,27 @@ function () { _context3.prev = 5; to = this.createRoute(location); from = isInit ? null : to.redirectedFrom || this.currentRoute; + current = this.currentRoute; if (!(to && from && to.fullPath === from.fullPath)) { - _context3.next = 10; + _context3.next = 11; break; } return _context3.abrupt("return", callback(true)); - case 10: + case 11: if ((0, _routeLazy.hasMatchedRouteLazy)(to.matched)) { fallbackView = this.viewRoot; this._getSameMatched(isInit ? null : this.currentRoute, to).reverse().some(function (m) { - if (!m.viewInstance || !m.viewInstance.props.fallback) return; - return fallbackView = m.viewInstance; + if (!m.viewInstances.default || !m.viewInstances.default.props.fallback) return; + return fallbackView = m.viewInstances.default; }); } fallbackView && fallbackView._updateResolving(true); - routetInterceptors(this._getBeforeEachGuards(to, from), to, from, function (ok) { + routetInterceptors(this._getBeforeEachGuards(to, from, current), to, from, function (ok) { nexting = null; fallbackView && setTimeout(function () { return fallbackView._updateResolving(false); @@ -755,26 +715,26 @@ function () { _this4.nextTick(function () { if ((0, _util.isFunction)(ok)) ok(to); - if (!isInit && from.fullPath !== to.fullPath) routetInterceptors(_this4._getRouteUpdateGuards(to, from), to, from); + if (!isInit && current.fullPath !== to.fullPath) routetInterceptors(_this4._getRouteUpdateGuards(to, current), to, current); if (to && (0, _util.isFunction)(to.onComplete)) to.onComplete(); - routetInterceptors(_this4._getAfterEachGuards(to, from), to, from); + routetInterceptors(_this4._getAfterEachGuards(to, current), to, current); }); }); - _context3.next = 19; + _context3.next = 20; break; - case 15: - _context3.prev = 15; + case 16: + _context3.prev = 16; _context3.t0 = _context3["catch"](5); console.error(_context3.t0); if (!isContinue) callback(isContinue); - case 19: + case 20: case "end": return _context3.stop(); } } - }, _callee3, this, [[5, 15]]); + }, _callee3, this, [[5, 16]]); })); function _internalHandleRouteInterceptor(_x7, _x8) { @@ -800,7 +760,7 @@ function () { function copyInstance(to, from) { if (!from) return; if (from.componentInstances) to.componentInstances = from.componentInstances; - if (from.viewInstance) to.viewInstance = from.viewInstance; + if (from.viewInstances) to.viewInstances = from.viewInstances; } var matched = (0, _util.matchRoutes)(this.routes, to, parent); @@ -808,7 +768,8 @@ function () { var route = _ref3.route, match = _ref3.match; var ret = { - componentInstances: {} + componentInstances: {}, + viewInstances: {} }; Object.keys(route).forEach(function (key) { return ['path', 'name', 'subpath', 'meta', 'redirect', 'alias'].includes(key) && (ret[key] = route[key]); @@ -837,7 +798,7 @@ function () { key: "getMatchedViews", value: function getMatchedViews(to, from, parent) { return this.getMatched(to, from, parent).map(function (r) { - return r.viewInstance; + return r.viewInstances.default; }).filter(Boolean); } }, { @@ -881,7 +842,16 @@ function () { key: "updateRoute", value: function updateRoute(to) { if (!to) to = this.history.location; - this.currentRoute = this.createRoute(to); + var current = this.currentRoute; + this.currentRoute = this.createRoute(to, current); + + var tm = current && this._getChangeMatched(current, this.currentRoute, 1)[0]; + + if (tm) { + Object.keys(tm.viewInstances).forEach(function (key) { + return tm.viewInstances[key]._refreshCurrentRoute(); + }); + } else if (this.viewRoot) this.viewRoot._refreshCurrentRoute(); this._callEvent('onRouteChange', this.currentRoute, this); } @@ -950,6 +920,7 @@ function () { }, { key: "addRoutes", value: function addRoutes(routes, parentRoute) { + var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'default'; if (!routes) return; if (!Array.isArray(routes)) routes = [routes]; routes = (0, _util.normalizeRoutes)(routes, parentRoute); @@ -961,7 +932,7 @@ function () { }); if (~i) children.splice(i, 1, r);else children.push(r); }); - if (parentRoute && parentRoute.viewInstance) parentRoute.viewInstance.setState({ + if (parentRoute && parentRoute.viewInstances[name]) parentRoute.viewInstances[name].setState({ routes: routes });else if (this.state.viewRoot) this.state.viewRoot.setState({ routes: routes @@ -1010,6 +981,13 @@ function () { }) }); } + }, { + key: "RouterLink", + get: function get() { + if (this._RouterLink) return this._RouterLink; + (0, _util.innumerable)(this, '_RouterLink', (0, _routerLink.default)(this)); + return this._RouterLink; + } }]); return ReactViewRouter; diff --git a/esm/util.js b/esm/util.js index 5a49952..6ec8e5f 100644 --- a/esm/util.js +++ b/esm/util.js @@ -1,8 +1,11 @@ "use strict"; +require("core-js/modules/es6.weak-map"); + Object.defineProperty(exports, "__esModule", { value: true }); +exports.camelize = camelize; exports.flatten = flatten; exports.warn = warn; exports.once = once; @@ -12,6 +15,8 @@ exports.nextTick = nextTick; exports.isPlainObject = isPlainObject; exports.isFunction = isFunction; exports.isLocation = isLocation; +exports.isRouteChanged = isRouteChanged; +exports.isRoutesChanged = isRoutesChanged; exports.resolveRedirect = resolveRedirect; exports.normalizePath = normalizePath; exports.normalizeRoute = normalizeRoute; @@ -20,21 +25,23 @@ exports.normalizeRoutePath = normalizeRoutePath; exports.normalizeLocation = normalizeLocation; exports.normalizeProps = normalizeProps; exports.matchRoutes = matchRoutes; -exports.renderRoutes = renderRoutes; +exports.renderRoute = renderRoute; exports.innumerable = innumerable; +exports.afterInterceptors = afterInterceptors; +exports.getParentRouterView = getParentRouterView; Object.defineProperty(exports, "matchPath", { enumerable: true, get: function get() { - return _reactRouterDom.matchPath; - } -}); -Object.defineProperty(exports, "withRouter", { - enumerable: true, - get: function get() { - return _reactRouterDom.withRouter; + return _matchPath.default; } }); +require("core-js/modules/es6.string.iterator"); + +require("core-js/modules/es6.array.from"); + +require("regenerator-runtime/runtime"); + require("core-js/modules/es7.object.get-own-property-descriptors"); require("core-js/modules/es6.regexp.to-string"); @@ -47,6 +54,8 @@ require("core-js/modules/es7.symbol.async-iterator"); require("core-js/modules/es6.symbol"); +require("core-js/modules/es6.array.find"); + require("core-js/modules/web.dom.iterable"); require("core-js/modules/es6.array.iterator"); @@ -63,8 +72,6 @@ require("core-js/modules/es6.promise"); require("core-js/modules/es6.object.to-string"); -var _reactRouterDom = require("react-router-dom"); - var _react = _interopRequireDefault(require("react")); var _config = _interopRequireDefault(require("./config")); @@ -73,13 +80,31 @@ var _routeLazy = require("./route-lazy"); var _routeGuard = require("./route-guard"); +var _matchPath = _interopRequireWildcard(require("./match-path")); + +function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } @@ -179,10 +204,10 @@ function normalizeRoutes(routes, parent, depth) { return routes; } -function normalizeRoutePath(path, route) { +function normalizeRoutePath(path, route, append) { if (!path || path[0] === '/' || !route) return path || ''; if (route.config) route = route.config; - var parent = route.parent; + var parent = append ? route : route.parent; while (parent && path[0] !== '/') { path = "".concat(parent.path, "/").concat(path); @@ -192,6 +217,13 @@ function normalizeRoutePath(path, route) { return normalizePath(path); } +function resloveIndex(index, routes) { + index = isFunction(index) ? index() : index; + return routes.find(function (r) { + return r.subpath === index; + }); +} + function matchRoutes(routes, to, parent, branch) { if (branch === undefined) branch = []; to = normalizeLocation(to); @@ -213,8 +245,13 @@ function matchRoutes(routes, to, parent, branch) { try { for (var _iterator = routes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var route = _step.value; - var match = route.path ? (0, _reactRouterDom.matchPath)(to.path, route) : branch.length ? branch[branch.length - 1].match // use parent match - : _reactRouterDom.Router.computeRootMatch(to.path); // use default "root" match + var match = route.path ? (0, _matchPath.default)(to.path, route) : branch.length ? branch[branch.length - 1].match // use parent match + : (0, _matchPath.computeRootMatch)(to.path); // use default "root" match + + if (match && route.index) { + route = resloveIndex(route.index, routes); + if (!route) continue; + } if (match) { branch.push({ @@ -244,7 +281,7 @@ function matchRoutes(routes, to, parent, branch) { return branch; } -function normalizeLocation(to, route) { +function normalizeLocation(to, route, append) { if (!to) return to; if (typeof to === 'string') { @@ -261,9 +298,10 @@ function normalizeLocation(to, route) { if (to.query) Object.keys(to.query).forEach(function (key) { return to.query[key] === undefined && delete to.query[key]; - }); - to.pathname = to.path = normalizeRoutePath(to.pathname || to.path, route); + });else if (to.search) to.query = _config.default.parseQuery(to.search.substr(1)); + to.pathname = to.path = normalizeRoutePath(to.pathname || to.path, route, append); to.search = to.search || (to.query ? _config.default.stringifyQuery(to.query) : ''); + if (!to.query) to.query = {}; return to; } @@ -355,6 +393,7 @@ function resolveRedirect(to, route, from) { if (isFunction(to)) to = to.call(route, from); if (!to) return ''; to = normalizeLocation(to, route); + from && Object.assign(to.query, from.query); to.isRedirect = true; return to; } @@ -365,11 +404,93 @@ function warn() { (_console = console).warn.apply(_console, arguments); } -function renderRoutes(routes, extraProps, switchProps) { - var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - if (!routes) return null; - if (extraProps === undefined) extraProps = {}; - if (switchProps === undefined) switchProps = {}; +function afterInterceptors(_x) { + return _afterInterceptors.apply(this, arguments); +} + +function _afterInterceptors() { + _afterInterceptors = _asyncToGenerator( + /*#__PURE__*/ + regeneratorRuntime.mark(function _callee(interceptors) { + var _len4, + args, + _key4, + i, + _interceptor, + interceptor, + _args = arguments; + + return regeneratorRuntime.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + for (_len4 = _args.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + args[_key4 - 1] = _args[_key4]; + } + + i = 0; + + case 2: + if (!(i < interceptors.length)) { + _context.next = 19; + break; + } + + interceptor = interceptors[i]; + + case 4: + if (!(interceptor && interceptor.lazy)) { + _context.next = 10; + break; + } + + _context.next = 7; + return interceptor(interceptors, i); + + case 7: + interceptor = _context.sent; + _context.next = 4; + break; + + case 10: + if (interceptor) { + _context.next = 12; + break; + } + + return _context.abrupt("return"); + + case 12: + _context.t0 = interceptor; + + if (!_context.t0) { + _context.next = 16; + break; + } + + _context.next = 16; + return (_interceptor = interceptor).call.apply(_interceptor, [this].concat(args)); + + case 16: + i++; + _context.next = 2; + break; + + case 19: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + return _afterInterceptors.apply(this, arguments); +} + +function renderRoute(route, routes, props, children) { + var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + if (props === undefined) props = {}; + if (!route) return null; + if (route.config) route = route.config; function configProps(_props, configs, obj, name) { if (!obj) return; @@ -393,20 +514,18 @@ function renderRoutes(routes, extraProps, switchProps) { } } - function renderComp(route, component, routeProps, options) { + function createComp(route, props, children, options) { + var component = route.components[options.name || 'default']; if (!component) return null; var _props = {}; if (route.defaultProps) { - Object.assign(_props, isFunction(route.defaultProps) ? route.defaultProps(routeProps) : route.defaultProps); + Object.assign(_props, isFunction(route.defaultProps) ? route.defaultProps(props) : route.defaultProps); } if (route.props) configProps(_props, route.props, options.params, options.name); if (route.paramsProps) configProps(_props, route.paramsProps, options.params, options.name); if (route.queryProps) configProps(_props, route.queryProps, options.query, options.name); - if (route.render) return route.render(Object.assign(_props, _config.default.inheritProps ? routeProps : null, extraProps, _config.default.inheritProps ? { - route: route - } : null)); var ref = null; if (component) { @@ -438,9 +557,7 @@ function renderRoutes(routes, extraProps, switchProps) { } completeCallback && completeCallback(el); - afterEnterGuards && afterEnterGuards.forEach(function (v) { - return v.call(el); - }); + afterEnterGuards && afterInterceptors.call(el, afterEnterGuards); } }); _pending.completeCallbacks[options.name] = null; @@ -450,43 +567,23 @@ function renderRoutes(routes, extraProps, switchProps) { }); if (component.__component) component = (0, _routeGuard.getGuardsComponent)(component); - var ret = _react.default.createElement(component, Object.assign(_props, _config.default.inheritProps ? routeProps : null, extraProps, _config.default.inheritProps ? { + var ret = _react.default.createElement.apply(_react.default, [component, Object.assign(_props, _config.default.inheritProps ? props : null, _config.default.inheritProps ? { route: route } : null, { ref: ref - })); + })].concat(_toConsumableArray(Array.isArray(children) ? children : [children]))); if (!ref) nextTick(refHandler); return ret; - } // const currentRoute = options.router && options.router.currentRoute; - - - var children = routes.map(function (route, i) { - if (route.redirect) { - return; // return React.createElement(Redirect, { - // key: route.key || i, - // exact: route.exact, - // strict: route.strict, - // from: route.path, - // to: resolveRedirect(route.redirect, route, currentRoute) - // }); - } - - return _react.default.createElement(_reactRouterDom.Route, { - key: route.key || i, - path: route.path, - exact: route.exact, - strict: route.strict, - render: function render(props) { - return renderComp(route, route.components[options.name || 'default'], props, options); - } - }); - }).filter(Boolean); - if (options.container) children = options.container(children); - - var ret = _react.default.createElement(_reactRouterDom.Switch, switchProps, children); + } - return ret; + var renderRoute = route; + if (route.redirect) return null; + if (route.index) renderRoute = resloveIndex(route.index, routes); + if (!renderRoute) return null; + var result = createComp(renderRoute, props, children, options); + if (options.container) result = options.container(result); + return result; } function flatten(array) { @@ -499,4 +596,40 @@ function flatten(array) { })(array); return flattend; +} + +function camelize(str) { + var ret = str.replace(/[-|:](\w)/g, function (_, c) { + return c ? c.toUpperCase() : ''; + }); + if (/^[A-Z]/.test(ret)) ret = ret.charAt(0).toLowerCase() + ret.substr(1); + return ret; +} + +function isRouteChanged(prev, next) { + if (prev && next) return prev.path !== next.path; + if ((!prev || !next) && prev !== next) return true; + return false; +} + +function isRoutesChanged(prevs, nexts) { + if (!prevs || !nexts) return true; + if (prevs.length !== nexts.length) return true; + var changed = false; + prevs.some(function (prev, i) { + changed = isRouteChanged(prev, nexts[i]); + return changed; + }); + return changed; +} + +function getParentRouterView(ctx) { + var parent = ctx._reactInternalFiber.return; + + while (parent) { + var memoizedState = parent.memoizedState; // const memoizedProps = parent.memoizedProps; + + if (memoizedState && memoizedState._routerView) return parent.stateNode; + parent = parent.return; + } } \ No newline at end of file