UNPKG

react-router-4-compat

Version:

A wrapped version of react router 4 which compatible with react router 3

1,549 lines (1,321 loc) 50.7 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('prop-types'), require('react-router/Route'), require('react-router/Switch'), require('react-router/matchPath'), require('react-router/Router')) : typeof define === 'function' && define.amd ? define(['exports', 'react', 'prop-types', 'react-router/Route', 'react-router/Switch', 'react-router/matchPath', 'react-router/Router'], factory) : (factory((global.index = {}),global.React,global.PropTypes,global.Route,global.Switch,global.matchPath,global.Router)); }(this, (function (exports,React,PropTypes,Route,Switch,matchPath,Router) { 'use strict'; React = React && React.hasOwnProperty('default') ? React['default'] : React; PropTypes = PropTypes && PropTypes.hasOwnProperty('default') ? PropTypes['default'] : PropTypes; Route = Route && Route.hasOwnProperty('default') ? Route['default'] : Route; Switch = Switch && Switch.hasOwnProperty('default') ? Switch['default'] : Switch; matchPath = matchPath && matchPath.hasOwnProperty('default') ? matchPath['default'] : matchPath; Router = Router && Router.hasOwnProperty('default') ? Router['default'] : Router; function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function step(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 _next(value) { step("next", value); } function _throw(err) { step("throw", err); } _next(); }); }; } 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 _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _inheritsLoose(subClass, superClass) { subClass.prototype.__proto__ = superClass && superClass.prototype; subClass.__proto__ = superClass; } function _objectWithoutProperties(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]; } 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; } var isPromise_1 = isPromise; function isPromise(obj) { return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; } var some = function some(arr, pred) { arr = arr || []; for (var i = 0; i < arr.length; ++i) { if (pred && pred(arr[i])) { return true; } } return false; }; var toPairs = function toPairs(obj) { return obj ? Object.keys(obj).map(function (k) { return [k, obj[k]]; }) : []; }; var fromPairs = function fromPairs(arr) { var ret = {}; (arr || []).forEach(function (_ref) { var k = _ref[0], v = _ref[1]; return ret[k] = v; }); return ret; }; var mapValues = function mapValues(obj, mapper, filter) { if (mapper === void 0) { mapper = function mapper(v) { return v; }; } if (filter === void 0) { filter = function filter() { return true; }; } return fromPairs(toPairs(obj).filter(function (_ref2) { var k = _ref2[0], v = _ref2[1]; return filter(v, k); }).map(function (_ref3) { var k = _ref3[0], v = _ref3[1]; return [k, mapper(v, k)]; })); }; var isFunction = function isFunction(func) { return typeof func === 'function'; }; function _extends$1() { _extends$1 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$1.apply(this, arguments); } function _objectWithoutProperties$1(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]; } 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 _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty$1(target, key, source[key]); }); } return target; } function _defineProperty$1(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 _inheritsLoose$1(subClass, superClass) { subClass.prototype.__proto__ = superClass && superClass.prototype; subClass.__proto__ = superClass; } var isStateless = function isStateless(Component) { return !Component.prototype.render; }; var DefaultLoadingComponent = function DefaultLoadingComponent() { return null; }; var DefaultErrorComponent = function DefaultErrorComponent() { return null; }; var SymbolComp = Symbol('component'); var SymbolJob = Symbol('job'); var majorVersion = React.version ? Number.parseInt(React.version.slice(0, React.version.indexOf('.')), 10) : 0; function shallowEqual(o1, o2, excludes) { if (excludes === void 0) { excludes = []; } if (o1 === o2) { return true; } if (typeof o1 !== 'object' || typeof o2 !== 'object' || o1 === null || o2 === null) { return false; } if (Array.isArray(o1) && Array.isArray(o2)) { var len = o1.length; if (len !== o2.length) { return false; } for (var i = 0; i < len; ++i) { if (o1[i] !== o2[i]) { return false; } } return true; } var keys1 = Object.keys(o1); var keys2 = Object.keys(o2); if (keys1.length !== keys2.length) { return false; } for (var _i = 0; _i < keys1.length; ++_i) { var key = keys1[_i]; if (!excludes.includes(key) && (!keys2.includes(key) || o1[key] !== o2[key])) { return false; } } return true; } var AsyncComponent = /*#__PURE__*/ function (_React$PureComponent) { function AsyncComponent(props) { var _this; for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } _this = _React$PureComponent.call.apply(_React$PureComponent, [this, props].concat(args)) || this; _this.setStateSafe = function (newState) { if (_this.mounted) { _this.setState(newState); } else { Object.assign(_this.state, newState); } }; _this.updateProgress = function (propName) { return function (progress) { return _this.setState(function (preState) { var _objectSpread2; return { progress: _objectSpread$1({}, preState.progress, (_objectSpread2 = {}, _objectSpread2[propName] = progress, _objectSpread2)) }; }); }; }; _this.loadSuccess = function (pairs) { var compPair = null; for (var i = 0; i < pairs.length; ++i) { var _pairs$i = pairs[i], k = _pairs$i[0]; if (k === SymbolComp) { var _pairs$splice = pairs.splice(i, 1); compPair = _pairs$splice[0]; } } var newState = { resolvedProps: fromPairs(pairs), progress: fromPairs(pairs.map(function (_ref) { var k = _ref[0]; return [k, 1]; })), error: null, loading: false }; if (compPair) { var _compPair = compPair; newState.component = _compPair[1]; } _this.setStateSafe(newState); }; _this.state = { error: null, loading: true, resolvedProps: {}, component: null, progress: fromPairs(Object.keys(props.asyncProps || {}).map(function (k) { return [k, 0]; })) }; return _this; } var _proto = AsyncComponent.prototype; _proto.componentDidMount = function componentDidMount() { this.mounted = true; this.load(); }; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { // noinspection JSUnresolvedFunction if (nextProps.reloader && nextProps.reloader.isReload()) { // noinspection JSUnresolvedFunction nextProps.reloader.resetReload(); if (!this.state.loading) { this.load(); } } if (nextProps.reloadOnUpdate && !this.state.loading) { if (nextProps.reloadDependents === null || nextProps.reloadDependents === undefined) { if (!shallowEqual(this.props, nextProps, ['batch', 'errorComponent', 'loadingComponent', 'onError', 'delay', 'reloadOnUpdate', 'reloadDependents', 'reloader'])) { this.load(); } } else if (!shallowEqual(this.props.reloadDependents, nextProps.reloadDependents)) { this.load(); } } }; _proto.componentWillUnmount = function componentWillUnmount() { this.mounted = false; }; _proto.load = function load() { var _this2 = this; var _this$props = this.props, asyncComponent = _this$props.asyncComponent, asyncJobs = _this$props.asyncJobs, asyncProps = _this$props.asyncProps, onError = _this$props.onError, delay = _this$props.delay; this.setStateSafe({ error: null, loading: true, progress: fromPairs(Object.keys(asyncProps || {}).map(function (k) { return [k, 0]; })) }); try { var pairs = (asyncComponent ? [[SymbolComp, asyncComponent]] : []).concat((asyncJobs || []).map(function (job) { return [SymbolJob, job]; }), toPairs(asyncProps || {})).filter(function (entry) { return entry[1]; }); if (some(pairs, function (entry) { return !isFunction(entry[1]); })) { var error = new Error('The async job or async prop must be a function.'); // noinspection JSCheckFunctionSignatures this.setState({ error: error, loading: false }); if (onError) { onError(error); } return; } var batch = this.props.batch; pairs = pairs.map(function (_ref2) { var k = _ref2[0], v = _ref2[1]; return [k, v(typeof k !== 'symbol' ? _this2.updateProgress(k) : null)]; }); if (delay > 0) { pairs.push([SymbolJob, new Promise(function (resolve) { return setTimeout(resolve, delay); })]); } if (some(pairs, function (pair) { return isPromise_1(pair[1]); })) { var promises = pairs.map(function (_ref3) { var k = _ref3[0], p = _ref3[1]; if (isPromise_1(p)) { return p.then(function (res) { if (!batch && typeof k !== 'symbol') { if (_this2.mounted) { var _AsyncComponent$updat; _this2.setState(AsyncComponent.updateResolvedProps((_AsyncComponent$updat = {}, _AsyncComponent$updat[k] = res, _AsyncComponent$updat))); } else { _this2.state.resolvedProps[k] = res; _this2.state.progress[k] = 1; } } if (!batch && k === SymbolComp) { _this2.setStateSafe({ component: res }); } return [k, res]; }); } if (!batch && typeof k !== 'symbol') { var _AsyncComponent$updat2; _this2.setState(AsyncComponent.updateResolvedProps((_AsyncComponent$updat2 = {}, _AsyncComponent$updat2[k] = p, _AsyncComponent$updat2))); } if (!batch && k === SymbolComp) { // noinspection JSCheckFunctionSignatures _this2.setState({ component: p }); } return [k, p]; }); Promise.all(promises).then(function (pairs) { _this2.loadSuccess(pairs.filter(function (_ref4) { var k = _ref4[0]; return typeof k !== 'symbol'; })); }).catch(function (e) { try { if (onError) { onError(e); } } finally { _this2.setStateSafe({ error: e }); } }).finally(function () { _this2.setStateSafe({ loading: false }); }); } else { this.loadSuccess(pairs.filter(function (_ref5) { var k = _ref5[0]; return typeof k !== 'symbol'; })); } } catch (error) { try { if (onError) { onError(error); } } finally { this.setStateSafe({ loading: false }); } } }; _proto.render = function render() { var _this$props2 = this.props, ErrorComponent = _this$props2.errorComponent, LoadingComponent = _this$props2.loadingComponent, asyncPropOpts = _this$props2.asyncPropOpts, asyncPropsMapper = _this$props2.asyncPropsMapper, asyncComponent = _this$props2.asyncComponent, children = _this$props2.children, unwrapDefault = _this$props2.unwrapDefault; var syncProps = this.props.syncProps; var Comp = this.props.component; var _this$state = this.state, error = _this$state.error, loading = _this$state.loading, resolvedProps = _this$state.resolvedProps, progress = _this$state.progress; var wrappedProps = asyncPropsMapper(Object.assign({}, mapValues(asyncPropOpts, function (opt) { return opt.defaultProp; }, function (opt) { return opt && {}.hasOwnProperty.call(opt, 'defaultProp'); }), resolvedProps)); var ref; if ({}.hasOwnProperty.call(syncProps, 'ref')) { var _syncProps = syncProps; ref = _syncProps.ref; syncProps = _objectWithoutProperties$1(_syncProps, ["ref"]); } if ({}.hasOwnProperty.call(wrappedProps, 'ref')) { var _wrappedProps = wrappedProps; ref = _wrappedProps.ref; wrappedProps = _objectWithoutProperties$1(_wrappedProps, ["ref"]); } var _wrappedProps2 = wrappedProps, ignored = _wrappedProps2.children, restResolvedProps = _objectWithoutProperties$1(_wrappedProps2, ["children"]); if (loading && LoadingComponent !== DefaultLoadingComponent) { return React.createElement(LoadingComponent, _extends$1({}, this.props, restResolvedProps, { loading: loading, progress: progress })); } if (error) { return React.createElement(ErrorComponent, _extends$1({}, this.props, restResolvedProps, { loading: loading, progress: progress, error: error })); } if (asyncComponent) { if (this.state.component) { Comp = this.state.component; } else { return null; } } if (Comp) { if (unwrapDefault) { // eslint-disable-next-line no-underscore-dangle Comp = Comp.default || Comp; } return !isStateless(Comp) && ref ? React.createElement(Comp, _extends$1({}, syncProps || {}, wrappedProps, { ref: ref, loading: loading, progress: progress })) : React.createElement(Comp, _extends$1({}, syncProps || {}, wrappedProps, { loading: loading, progress: progress })); } // noinspection JSUnresolvedFunction JSCheckFunctionSignatures var newChildren = React.Children.map(children, function (child) { return React.cloneElement(child, _objectSpread$1({}, syncProps || {}, restResolvedProps, { loading: loading, progress: progress })); }); if (!newChildren) { return null; } if (newChildren.length === 1) { return newChildren[0]; } else if (newChildren.length > 1) { return majorVersion >= 16 ? newChildren : React.createElement("div", null, " ", newChildren, " "); } return null; }; _inheritsLoose$1(AsyncComponent, _React$PureComponent); return AsyncComponent; }(React.PureComponent); AsyncComponent.updateResolvedProps = function (resolvedProps) { return function (preState) { return { resolvedProps: _objectSpread$1({}, preState.resolvedProps, resolvedProps), progress: _objectSpread$1({}, preState.progress, fromPairs(Object.keys(resolvedProps).map(function (k) { return [k, 1]; }))) }; }; }; AsyncComponent.createReloader = function (compInst) { var forceReload = false; return { reload: function reload() { forceReload = true; compInst.setState({ __reloader__3yPbia72w46: {} }); }, isReload: function isReload() { return forceReload; }, resetReload: function resetReload() { forceReload = false; } }; }; var any = PropTypes.any, bool = PropTypes.bool, number = PropTypes.number, objectOf = PropTypes.objectOf, func = PropTypes.func, oneOfType = PropTypes.oneOfType, arrayOf = PropTypes.arrayOf, element = PropTypes.element, shape = PropTypes.shape; AsyncComponent.propTypes = { /** If true, only when all async props are resolved, the wrapped component is rendered again. Otherwise, the wrapped component will be updated when any async prop is resolved. */ batch: bool, /** The async jobs. Compared to async props, they will not provide the props to the wrapped component, but they should be done before the wrapped component finally render. The word 'finally' means the wrapped component will be updated several time if 'batch' set to false. */ asyncJobs: arrayOf(func), /** All async props should be declared here.They should be functions. If the function return a promise, it will be a real async prop, otherwise it is still a sync prop. The es6 async function is supported. In fact it is just a function return promise. The async component will provide every function with a method to update the progress which is a number range from 0 to 1. */ asyncProps: objectOf(func), /** The option of the async props. At this moment, only 'defaultProp' is supported. */ asyncPropOpts: objectOf(shape({ defaultProp: any })), /** Accept the resolved async props, and return the props provide to the wrapped component. */ asyncPropsMapper: func, /** The sync props. * This is useful when providing component or asyncComponent prop * instead of children node as wrapped component. */ syncProps: objectOf(any), /** If specialized, the async wrapper will use this as the wrapped component * instead of the children components. */ component: func, /** If specialized, the async wrapper will use this as the wrapped component * when resolved instead of component prop and the children components. */ asyncComponent: func, children: oneOfType([element, arrayOf(element)]), /** This component will be used to show the error. */ errorComponent: func, /** When the async jobs and async props have not been resolved yet, this component will be rendered. However, if this prop is not specialized, the wrapped component with default and partial resolved props will be rendered instead. */ loadingComponent: func, /** The error callback. It will be called when a error is throwed during the async jobs is running or the async props is resolved. */ onError: func, /** A number greater than 0 will force the wrapped component rendering with a delay. */ delay: number, /** Useful when provide the asyncComponent with dynamic import method. * The dynamic import method return a promise resolving a module object. * However, we often need the module.default instead of the module itself. * This option make the wrapper try to use module.default when available */ unwrapDefault: bool, /** * Whether to reload the date when the AsyncComponent is updated. */ reloadOnUpdate: bool, /** * The dependents which using to decide whether to reload. Shallow equal is used to compare changed. * Only valid when reloadOnUpdate is true. * If set null or undefined, means use all props to decide. */ reloadDependents: objectOf(any), /** * An object create by `AsyncComponent.createReloader`, * The api `reloader.reload()` can be used to force a reload task. */ reloader: shape({ reload: func, isReload: func, resetReload: func }) }; AsyncComponent.defaultProps = { batch: false, asyncJobs: [], asyncProps: {}, asyncPropOpts: {}, asyncPropsMapper: function asyncPropsMapper(props) { return props; }, syncProps: {}, component: null, asyncComponent: null, children: null, errorComponent: DefaultErrorComponent, loadingComponent: DefaultLoadingComponent, onError: function onError() { return null; }, delay: 0, unwrapDefault: true, reloadOnUpdate: false, reloadDependents: null, reloader: null }; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var hoistNonReactStatics = createCommonjsModule(function (module, exports) { /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ (function (global, factory) { module.exports = factory(); }(commonjsGlobal, (function () { var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var defineProperty = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = getPrototypeOf && getPrototypeOf(Object); return function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols) { keys = keys.concat(getOwnPropertySymbols(sourceComponent)); } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!REACT_STATICS[key] && !KNOWN_STATICS[key] && (!blacklist || !blacklist[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) {} } } return targetComponent; } return targetComponent; }; }))); }); var some$1 = function some(arr, pred) { arr = arr || []; for (var i = 0; i < arr.length; ++i) { if (pred && pred(arr[i])) { return true; } } return false; }; var mapValues$1 = function mapValues(obj, mapper) { if (!obj) { return obj; } if (!mapper) { return _objectSpread({}, obj); } var parts = Object.keys(obj).map(function (k) { var _ref; return _ref = {}, _ref[k] = mapper(obj[k], k, obj), _ref; }); return Object.assign.apply(Object, [{}].concat(parts)); }; var assignWith = function assignWith(object) { for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } if (rest.length === 0 || rest.length === 1 && typeof rest[0] === 'function') { return object; } var cumstomizer = rest[rest.length - 1]; cumstomizer = typeof cumstomizer === 'function' ? cumstomizer : null; var sources = cumstomizer ? rest.slice(0, rest.length - 1) : rest; if (!cumstomizer) { return Object.assign.apply(Object, [object].concat(sources)); } else { var _loop = function _loop(i) { var source = sources[i]; var newSources = Object.keys(source).map(function (k) { var _ref2, _ref3; return {}.hasOwnProperty.call(object, k) ? (_ref2 = {}, _ref2[k] = cumstomizer(object[k], source[k], k, object, source), _ref2) : (_ref3 = {}, _ref3[k] = source[k], _ref3); }); Object.assign.apply(Object, [object].concat(newSources)); }; for (var i = 0; i < sources.length; ++i) { _loop(i); } return object; } }; var castArray = function castArray() { if (arguments.length === 0) { return []; } return Array.isArray(arguments.length <= 0 ? undefined : arguments[0]) ? arguments.length <= 0 ? undefined : arguments[0] : [arguments.length <= 0 ? undefined : arguments[0]]; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var NODE_ENV = "development"; var invariant = function(condition, format, a, b, c, d, e, f) { if (NODE_ENV !== 'production') { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; var invariant_1 = invariant; var isStateless$1 = function isStateless(Component) { return !Component.prototype || !Component.prototype.render; }; var withRouter4Compat = function withRouter4Compat(Component, _temp) { var _ref = _temp === void 0 ? {} : _temp, _ref$withRef = _ref.withRef, withRef = _ref$withRef === void 0 ? false : _ref$withRef; var C = /*#__PURE__*/ function (_React$Component) { function C() { return _React$Component.apply(this, arguments) || this; } var _proto = C.prototype; // noinspection JSUnusedGlobalSymbols _proto.getWrappedInstance = function getWrappedInstance() { invariant_1(withRef, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true}` as the second argument of the withRouter() call.'); return this.wrappedInstance; }; _proto.render = function render() { var _this = this; var _this$props = this.props, wrappedComponentRef = _this$props.wrappedComponentRef, remainingProps = _objectWithoutProperties(_this$props, ["wrappedComponentRef"]); var wrappedComponentRefCompat = wrappedComponentRef ? function (c) { _this.wrappedInstance = c; return wrappedComponentRef(c); } : function (c) { _this.wrappedInstance = c; }; return React.createElement(Route, { children: function children(routeComponentProps) { var match = routeComponentProps.match, location = routeComponentProps.location, history = routeComponentProps.history; return isStateless$1(Component) ? React.createElement(Component, _extends({}, remainingProps, routeComponentProps, { router: history, routes: _this.context.routesCompat, params: match.params, location: location })) : React.createElement(Component, _extends({}, remainingProps, routeComponentProps, { router: history, routes: _this.context.routesCompat, params: match.params, location: location, ref: wrappedComponentRefCompat })); } }); }; _inheritsLoose(C, _React$Component); return C; }(React.Component); C.displayName = "withRouter(" + (Component.displayName || Component.name) + ")"; C.WrappedComponent = Component; C.propTypes = { wrappedComponentRef: PropTypes.func }; C.contextTypes = { routesCompat: PropTypes.array }; return hoistNonReactStatics(C, Component); }; var createState = function createState(match, location, history) { return _objectSpread({ match: match, location: location, history: history }, location); }; var createPromiseFromCallback = function createPromiseFromCallback(state, callbackFunc) { return new Promise(function (resolve, reject) { callbackFunc(state, function (err, result) { if (err) { reject(err); } else { resolve(result); } }); }); }; var createRoutePropertyPromise = function createRoutePropertyPromise(state, staticValue, dynamicValue) { if (staticValue) { return staticValue; } if (dynamicValue) { return createPromiseFromCallback(state, dynamicValue); } return null; }; var createRoutePromise = function createRoutePromise(state, route) { var component = route.component, getComponent = route.getComponent, indexRoute = route.indexRoute, getIndexRoute = route.getIndexRoute, childRoutes = route.childRoutes, getChildRoutes = route.getChildRoutes; return Promise.all([createRoutePropertyPromise(state, component, getComponent), createRoutePropertyPromise(state, indexRoute, getIndexRoute), createRoutePropertyPromise(state, childRoutes, getChildRoutes)]).then(function (_ref) { var comp = _ref[0], ir = _ref[1], cr = _ref[2]; return _objectSpread({}, route, { component: comp, indexRoute: ir, childRoutes: cr }); }); }; var createRoutes = function createRoutes(routes, onError, routeStack) { if (routeStack === void 0) { routeStack = []; } return routes.map(function (_route) { var path = _route.path, component = _route.component, getComponent = _route.getComponent, indexRoute = _route.indexRoute, getIndexRoute = _route.getIndexRoute, childRoutes = _route.childRoutes, getChildRoutes = _route.getChildRoutes, onEnter = _route.onEnter, exact = _route.exact; if (!component && !getComponent && !onEnter) { return null; } return React.createElement(Route, { key: path || 0, path: path, exact: !!exact // eslint-disable-next-line react/no-children-prop , children: function children(props) { var match = props.match, location = props.location, history = props.history; var routeState = createState(match, location, history); if (component && (indexRoute || !getIndexRoute) && (childRoutes || !getChildRoutes) && !onEnter) { return React.createElement(Route4Compat, _extends({}, props, { state: routeState, route: _route, routeStack: routeStack, onError: onError })); } var asyncJobs = []; if (onEnter) { asyncJobs.push(function () { return new Promise(function (resolve, reject) { if (onEnter.length >= 3) { onEnter(routeState, history.replace, function (err) { if (err) { reject(err); } else { resolve(); } }); } else { onEnter(routeState, history.replace); resolve(); } }); }); } return React.createElement(AsyncComponent, { batch: true, onError: onError, asyncJobs: asyncJobs, asyncProps: { route: function route() { return createRoutePromise(routeState, _route); } }, loadingComponent: function loadingComponent() { return null; }, reloadOnUpdate: false }, React.createElement(Route4Compat, _extends({}, props, { routeStack: routeStack, state: routeState, onError: onError }))); } }); }).filter(function (v) { return v; }); }; var makePath = function makePath(base, path) { if (!path) { return base || '/'; } if (path.startsWith('/')) { return path; } return (base === '/' ? '' : base) + "/" + path; }; var shallowEqual$1 = function shallowEqual(obj1, obj2) { if (obj1 === obj2) { return true; } if (!obj1 || !obj2) { return false; } var keys1 = Object.keys(obj1); var keys2 = Object.keys(obj2); if (keys1.length !== keys2.length) { return false; } for (var i = 0; i < keys1.length; ++i) { var key = keys1[i]; if (obj1[key] !== obj2[key]) { return false; } } return true; }; var Route4Compat = /*#__PURE__*/ function (_React$Component) { function Route4Compat() { return _React$Component.apply(this, arguments) || this; } var _proto = Route4Compat.prototype; _proto.componentWillMount = function componentWillMount() { this.context.routesCompat = this.props.routeStack.concat([this.props.route]); this.context.routesUpdater(this.context.routesCompat); }; _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps, ignored) { var _this$props = this.props, route = _this$props.route, state = _this$props.state, history = _this$props.history, onError = _this$props.onError; var onChange = route.onChange; if (onChange) { if (onChange.length >= 4) { new Promise(function (resolve, reject) { onChange(state, nextProps.state, history.replace, function (err) { if (err) { reject(err); } else { resolve(); } }); }).catch(onError); } else { try { onChange(state, nextProps.state, history.replace); } catch (e) { onError(e); } } } }; _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState, nextContext) { // noinspection JSUnusedLocalSymbols var nextMatch = nextProps.match, nextParams = nextProps.params, nState = nextProps.state, nextRoute = nextProps.route, nextRouteStack = nextProps.routeStack, nextRest = _objectWithoutProperties(nextProps, ["match", "params", "state", "route", "routeStack"]); // noinspection JSUnusedLocalSymbols var _this$props2 = this.props, thisMatch = _this$props2.match, thisParams = _this$props2.params, tState = _this$props2.state, thisRoute = _this$props2.route, thisRouteStack = _this$props2.routeStack, thisRest = _objectWithoutProperties(_this$props2, ["match", "params", "state", "route", "routeStack"]); var _ref2 = nextMatch || {}, nextMatchParams = _ref2.params, nextMatchRest = _objectWithoutProperties(_ref2, ["params"]); var _ref3 = thisMatch || {}, thisMatchParams = _ref3.params, thisMatchRest = _objectWithoutProperties(_ref3, ["params"]); return !shallowEqual$1(this.state, nextState) || !shallowEqual$1(this.context, nextContext) || !shallowEqual$1(thisMatchParams, nextMatchParams) || !shallowEqual$1(thisMatchRest, nextMatchRest) || !shallowEqual$1(thisRoute, nextRoute) || !shallowEqual$1(thisRouteStack, nextRouteStack) || !shallowEqual$1(thisRest, nextRest); }; _proto.componentWillUnmount = function componentWillUnmount() { var _this$props3 = this.props, route = _this$props3.route, state = _this$props3.state, onError = _this$props3.onError; var onLeave = route.onLeave; if (onLeave) { try { onLeave(state); } catch (e) { onError(e); } } }; _proto.render = function render() { var _this$props4 = this.props, _route2 = _this$props4.route, routeStack = _this$props4.routeStack, state = _this$props4.state, onError = _this$props4.onError, rest = _objectWithoutProperties(_this$props4, ["route", "routeStack", "state", "onError"]); var path = _route2.path, Comp = _route2.component, indexRoute = _route2.indexRoute; if (!Comp) { return null; } var childRoutes = _route2.childRoutes; if (some$1(childRoutes, function (childRoute) { return !childRoute.components && childRoute.getComponents; })) { // noinspection RequiredAttributes return React.createElement(AsyncComponent, { batch: true, onError: onError, loadingComponent: function loadingComponent() { return null; }, asyncProps: { route: function () { var _route3 = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee() { return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", Promise.all((childRoutes || []).map(function (childRoute) { if (childRoute.components || !childRoute.getComponents) { return { childRoute: childRoute }; } else { return new Promise(function (resolve, reject) { return childRoute.getComponents(state, function (err, res) { if (err) { reject(err); } else { resolve({ childRoute: childRoute, components: res }); } }); }); } })).then(function (subComponents) { return _objectSpread({}, _route2, { childRoutes: subComponents.map(function (_ref4) { var childRoute = _ref4.childRoute, components = _ref4.components; return _objectSpread({}, childRoute, { components: components }); }) }); })); case 1: case "end": return _context.stop(); } } }, _callee, this); })); return function route() { return _route3.apply(this, arguments); }; }() }, reloadOnUpdate: false }, React.createElement(Route4Compat, _extends({ routeStack: routeStack, state: state, onError: onError }, rest))); } var components = {}; if (childRoutes) { childRoutes = childRoutes.map(function (childRoute) { var childPath = childRoute.path; if (!childPath.startsWith('/')) { return _objectSpread({}, childRoute, { path: makePath(path, childPath) }); } return childRoute; }); var _loop = function _loop(i) { var childRoute = childRoutes[i]; var childComponents = childRoute.components; if (childComponents) { assignWith(components, childComponents, function (objValue, srcValue) { if (!objValue) { return [{ path: childRoute.path, component: srcValue }]; } else { objValue.push({ path: childRoute.path, component: srcValue }); return objValue; } }); } }; for (var i = 0; i < childRoutes.length; ++i) { _loop(i); } } var routes; var routesCompat = this.context.routesCompat; if (indexRoute) { routes = [_objectSpread({}, indexRoute, { path: makePath(path, indexRoute.path), exact: true })].concat(childRoutes || []); } else { routes = (childRoutes || []).concat(); } var comps = mapValues$1(components, function (compRoutes) { return function (props) { if (compRoutes.length === 1) { return React.createElement(Route, _extends({}, props, { path: compRoutes[0].path, component: withRouter4Compat(compRoutes[0].component) })); } else { return React.createElement(Switch, null, compRoutes.map(function (compRoute) { return React.createElement(Route, _extends({}, props, { path: compRoute.path, component: withRouter4Compat(compRoute.component) })); })); } }; }); var validRoutes = routes.filter(function (r) { return !!matchPath(state.location.pathname, r, state.match); }); return validRoutes.length > 0 ? React.createElement(Comp, _extends({}, rest, { router: state.history, params: state.match.params, location: state.location, routes: routesCompat }, comps), createRoutes([validRoutes[0]], onError, routeStack.concat([_route2]))) : React.createElement(Comp, _extends({}, rest, { router: state.history, params: state.match.params, location: state.location, routes: routesCompat }, comps)); }; _inheritsLoose(Route4Compat, _React$Component); return Route4Compat; }(React.Component); Route4Compat.contextTypes = { router: PropTypes.object }; var RoutePropType = PropTypes.shape({ path: PropTypes.string, component: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), getComponent: PropTypes.func, indexRoute: PropTypes.object, getIndexRoute: PropTypes.func, childRoutes: PropTypes.arrayOf(PropTypes.object), getChildRoutes: PropTypes.func, onLeave: PropTypes.func, onChange: PropTypes.func, exact: PropTypes.bool, strict: PropTypes.bool, sensitive: PropTypes.bool }); Route4Compat.propTypes = { route: RoutePropType, routeStack: PropTypes.arrayOf(RoutePropType), onError: PropTypes.func, state: PropTypes.object }; Route4Compat.defaultProps = { route: {}, routeStack: [], onError: function onError() { return null; }, state: {} }; Route4Compat.contextTypes = { routesCompat: PropTypes.arrayOf(RoutePropType), routesUpdater: PropTypes.func }; var Router4Compat = /*#__PURE__*/ function (_React$Component) { function Router4Compat(props, context) { var _this; // noinspection JSCheckFunctionSignatures _this = _React$Component.call(this, props, context) || this; _this.routesUpdater = function (routes) { _this.setState({ routes: routes }); }; _this.state = { routes: [] }; return _this; } var _proto = Router4Compat.prototype; _proto.getChildContext = function getChildContext() { return { routesCompat: this.state.routes, routesUpdater: this.routesUpdater }; }; _proto.render = function render() { var _this$props = this.props, routes = _this$props.routes, history = _this$props.history, onError = _this$props.onError; return React.createElement(Router, { history: history }, React.createElement(Switch, null, createRoutes(castArray(routes), onError, []))); }; _inheritsLoose(Router4Compat, _