From a78795c8504c099bddcd1f5aa080da1e5c573a3b Mon Sep 17 00:00:00 2001 From: kavience <599513860@qq.com> Date: Tue, 15 Sep 2020 11:51:24 +0800 Subject: [PATCH 1/5] feat: add remove cache method --- src/components/KeepAlive.tsx | 14 ++++++++------ src/components/Provider.tsx | 29 +++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/components/KeepAlive.tsx b/src/components/KeepAlive.tsx index f407b86..578b992 100644 --- a/src/components/KeepAlive.tsx +++ b/src/components/KeepAlive.tsx @@ -133,12 +133,14 @@ class KeepAlive extends React.PureComponent { setLifecycle, }, } = this.props; - const {renderElement, ifStillActivate, reactivate} = cache[identification]; - setLifecycle(LIFECYCLE.UNMOUNTED); - this.retreatPosition(); - changePositionByComment(identification, storeElement, renderElement); - if (ifStillActivate) { - reactivate(); + if (cache[identification]) { + const {renderElement, ifStillActivate, reactivate} = cache[identification]; + setLifecycle(LIFECYCLE.UNMOUNTED); + this.retreatPosition(); + changePositionByComment(identification, storeElement, renderElement); + if (ifStillActivate) { + reactivate(); + } } } diff --git a/src/components/Provider.tsx b/src/components/Provider.tsx index 43c4d36..9bd96c8 100644 --- a/src/components/Provider.tsx +++ b/src/components/Provider.tsx @@ -37,6 +37,7 @@ export interface IKeepAliveProviderImpl { existed: boolean; providerIdentification: string; setCache: (identification: string, value: ICacheItem) => void; + removeCache: (name: string) => void; unactivate: (identification: string) => void; isExisted: () => boolean; } @@ -122,6 +123,32 @@ export default class KeepAliveProvider extends React.PureComponent { + const {cache, keys} = this; + const needDeletedCacheKeys: any = []; + for (const key in cache) { + if (Object.prototype.hasOwnProperty.call(cache, key)) { + const keepAliveObject = cache[key] as any; + // if name is array, mutiple delete caches + if (Object.prototype.toString.call(name) === '[object Array]') { + if (name.indexOf(keepAliveObject.children._owner.key) > -1 ) { + needDeletedCacheKeys.push(key); + delete cache[key as string]; + } + } else if (Object.prototype.toString.call(name) === '[object String]') { + if (name.indexOf(keepAliveObject.children._owner.key) > -1 ) { + needDeletedCacheKeys.push(key); + delete cache[key as string]; + } + } else { + throw new Error("name can be only string or string array"); + } + } + } + this.keys = keys.filter((key) => needDeletedCacheKeys.indexOf(key) === -1) + this.forceUpdate(); + } + public unactivate = (identification: string) => { const {cache} = this; this.cache[identification] = { @@ -143,6 +170,7 @@ export default class KeepAliveProvider extends React.PureComponent Date: Tue, 15 Sep 2020 12:00:10 +0800 Subject: [PATCH 2/5] fix: temp build --- .gitignore | 2 - cjs/components/AsyncComponent.d.ts | 27 ++ cjs/components/AsyncComponent.js | 107 +++++++ cjs/components/Comment.d.ts | 18 ++ cjs/components/Comment.js | 75 +++++ cjs/components/Consumer.d.ts | 20 ++ cjs/components/Consumer.js | 78 +++++ cjs/components/KeepAlive.d.ts | 9 + cjs/components/KeepAlive.js | 162 ++++++++++ cjs/components/Provider.d.ts | 66 ++++ cjs/components/Provider.js | 210 +++++++++++++ cjs/contexts/IdentificationContext.d.ts | 12 + cjs/contexts/IdentificationContext.js | 24 ++ cjs/contexts/KeepAliveContext.d.ts | 5 + cjs/contexts/KeepAliveContext.js | 24 ++ cjs/index.d.ts | 5 + cjs/index.js | 14 + cjs/utils/bindLifecycle.d.ts | 3 + cjs/utils/bindLifecycle.js | 135 +++++++++ cjs/utils/changePositionByComment.d.ts | 1 + cjs/utils/changePositionByComment.js | 55 ++++ cjs/utils/createEventEmitter.d.ts | 11 + cjs/utils/createEventEmitter.js | 100 +++++++ cjs/utils/createStoreElement.d.ts | 1 + cjs/utils/createStoreElement.js | 11 + cjs/utils/createUniqueIdentification.d.ts | 8 + cjs/utils/createUniqueIdentification.js | 20 ++ cjs/utils/debug.d.ts | 3 + cjs/utils/debug.js | 19 ++ cjs/utils/getDisplayName.d.ts | 2 + cjs/utils/getDisplayName.js | 6 + cjs/utils/getKeepAlive.d.ts | 3 + cjs/utils/getKeepAlive.js | 29 ++ cjs/utils/getKeyByFiberNode.d.ts | 1 + cjs/utils/getKeyByFiberNode.js | 14 + cjs/utils/isRegExp.d.ts | 1 + cjs/utils/isRegExp.js | 6 + cjs/utils/keepAliveDecorator.d.ts | 17 ++ cjs/utils/keepAliveDecorator.js | 281 ++++++++++++++++++ cjs/utils/md5.d.ts | 1 + cjs/utils/md5.js | 13 + cjs/utils/noop.d.ts | 2 + cjs/utils/noop.js | 4 + cjs/utils/shallowEqual.d.ts | 2 + cjs/utils/shallowEqual.js | 36 +++ cjs/utils/useKeepAliveEffect.d.ts | 2 + cjs/utils/useKeepAliveEffect.js | 52 ++++ .../withIdentificationContextConsumer.d.ts | 10 + .../withIdentificationContextConsumer.js | 46 +++ cjs/utils/withKeepAliveContextConsumer.d.ts | 10 + cjs/utils/withKeepAliveContextConsumer.js | 46 +++ es/components/AsyncComponent.d.ts | 27 ++ es/components/AsyncComponent.js | 86 ++++++ es/components/Comment.d.ts | 18 ++ es/components/Comment.js | 51 ++++ es/components/Consumer.d.ts | 20 ++ es/components/Consumer.js | 54 ++++ es/components/KeepAlive.d.ts | 9 + es/components/KeepAlive.js | 138 +++++++++ es/components/Provider.d.ts | 66 ++++ es/components/Provider.js | 185 ++++++++++++ es/contexts/IdentificationContext.d.ts | 12 + es/contexts/IdentificationContext.js | 3 + es/contexts/KeepAliveContext.d.ts | 5 + es/contexts/KeepAliveContext.js | 3 + es/index.d.ts | 5 + es/index.js | 5 + es/utils/bindLifecycle.d.ts | 3 + es/utils/bindLifecycle.js | 109 +++++++ es/utils/changePositionByComment.d.ts | 1 + es/utils/changePositionByComment.js | 52 ++++ es/utils/createEventEmitter.d.ts | 11 + es/utils/createEventEmitter.js | 97 ++++++ es/utils/createStoreElement.d.ts | 1 + es/utils/createStoreElement.js | 8 + es/utils/createUniqueIdentification.d.ts | 8 + es/utils/createUniqueIdentification.js | 16 + es/utils/debug.d.ts | 3 + es/utils/debug.js | 16 + es/utils/getDisplayName.d.ts | 2 + es/utils/getDisplayName.js | 3 + es/utils/getKeepAlive.d.ts | 3 + es/utils/getKeepAlive.js | 23 ++ es/utils/getKeyByFiberNode.d.ts | 1 + es/utils/getKeyByFiberNode.js | 11 + es/utils/isRegExp.d.ts | 1 + es/utils/isRegExp.js | 3 + es/utils/keepAliveDecorator.d.ts | 17 ++ es/utils/keepAliveDecorator.js | 255 ++++++++++++++++ es/utils/md5.d.ts | 1 + es/utils/md5.js | 7 + es/utils/noop.d.ts | 2 + es/utils/noop.js | 2 + es/utils/shallowEqual.d.ts | 2 + es/utils/shallowEqual.js | 34 +++ es/utils/useKeepAliveEffect.d.ts | 2 + es/utils/useKeepAliveEffect.js | 46 +++ .../withIdentificationContextConsumer.d.ts | 10 + es/utils/withIdentificationContextConsumer.js | 20 ++ es/utils/withKeepAliveContextConsumer.d.ts | 10 + es/utils/withKeepAliveContextConsumer.js | 20 ++ 101 files changed, 3294 insertions(+), 2 deletions(-) create mode 100644 cjs/components/AsyncComponent.d.ts create mode 100644 cjs/components/AsyncComponent.js create mode 100644 cjs/components/Comment.d.ts create mode 100644 cjs/components/Comment.js create mode 100644 cjs/components/Consumer.d.ts create mode 100644 cjs/components/Consumer.js create mode 100644 cjs/components/KeepAlive.d.ts create mode 100644 cjs/components/KeepAlive.js create mode 100644 cjs/components/Provider.d.ts create mode 100644 cjs/components/Provider.js create mode 100644 cjs/contexts/IdentificationContext.d.ts create mode 100644 cjs/contexts/IdentificationContext.js create mode 100644 cjs/contexts/KeepAliveContext.d.ts create mode 100644 cjs/contexts/KeepAliveContext.js create mode 100644 cjs/index.d.ts create mode 100644 cjs/index.js create mode 100644 cjs/utils/bindLifecycle.d.ts create mode 100644 cjs/utils/bindLifecycle.js create mode 100644 cjs/utils/changePositionByComment.d.ts create mode 100644 cjs/utils/changePositionByComment.js create mode 100644 cjs/utils/createEventEmitter.d.ts create mode 100644 cjs/utils/createEventEmitter.js create mode 100644 cjs/utils/createStoreElement.d.ts create mode 100644 cjs/utils/createStoreElement.js create mode 100644 cjs/utils/createUniqueIdentification.d.ts create mode 100644 cjs/utils/createUniqueIdentification.js create mode 100644 cjs/utils/debug.d.ts create mode 100644 cjs/utils/debug.js create mode 100644 cjs/utils/getDisplayName.d.ts create mode 100644 cjs/utils/getDisplayName.js create mode 100644 cjs/utils/getKeepAlive.d.ts create mode 100644 cjs/utils/getKeepAlive.js create mode 100644 cjs/utils/getKeyByFiberNode.d.ts create mode 100644 cjs/utils/getKeyByFiberNode.js create mode 100644 cjs/utils/isRegExp.d.ts create mode 100644 cjs/utils/isRegExp.js create mode 100644 cjs/utils/keepAliveDecorator.d.ts create mode 100644 cjs/utils/keepAliveDecorator.js create mode 100644 cjs/utils/md5.d.ts create mode 100644 cjs/utils/md5.js create mode 100644 cjs/utils/noop.d.ts create mode 100644 cjs/utils/noop.js create mode 100644 cjs/utils/shallowEqual.d.ts create mode 100644 cjs/utils/shallowEqual.js create mode 100644 cjs/utils/useKeepAliveEffect.d.ts create mode 100644 cjs/utils/useKeepAliveEffect.js create mode 100644 cjs/utils/withIdentificationContextConsumer.d.ts create mode 100644 cjs/utils/withIdentificationContextConsumer.js create mode 100644 cjs/utils/withKeepAliveContextConsumer.d.ts create mode 100644 cjs/utils/withKeepAliveContextConsumer.js create mode 100644 es/components/AsyncComponent.d.ts create mode 100644 es/components/AsyncComponent.js create mode 100644 es/components/Comment.d.ts create mode 100644 es/components/Comment.js create mode 100644 es/components/Consumer.d.ts create mode 100644 es/components/Consumer.js create mode 100644 es/components/KeepAlive.d.ts create mode 100644 es/components/KeepAlive.js create mode 100644 es/components/Provider.d.ts create mode 100644 es/components/Provider.js create mode 100644 es/contexts/IdentificationContext.d.ts create mode 100644 es/contexts/IdentificationContext.js create mode 100644 es/contexts/KeepAliveContext.d.ts create mode 100644 es/contexts/KeepAliveContext.js create mode 100644 es/index.d.ts create mode 100644 es/index.js create mode 100644 es/utils/bindLifecycle.d.ts create mode 100644 es/utils/bindLifecycle.js create mode 100644 es/utils/changePositionByComment.d.ts create mode 100644 es/utils/changePositionByComment.js create mode 100644 es/utils/createEventEmitter.d.ts create mode 100644 es/utils/createEventEmitter.js create mode 100644 es/utils/createStoreElement.d.ts create mode 100644 es/utils/createStoreElement.js create mode 100644 es/utils/createUniqueIdentification.d.ts create mode 100644 es/utils/createUniqueIdentification.js create mode 100644 es/utils/debug.d.ts create mode 100644 es/utils/debug.js create mode 100644 es/utils/getDisplayName.d.ts create mode 100644 es/utils/getDisplayName.js create mode 100644 es/utils/getKeepAlive.d.ts create mode 100644 es/utils/getKeepAlive.js create mode 100644 es/utils/getKeyByFiberNode.d.ts create mode 100644 es/utils/getKeyByFiberNode.js create mode 100644 es/utils/isRegExp.d.ts create mode 100644 es/utils/isRegExp.js create mode 100644 es/utils/keepAliveDecorator.d.ts create mode 100644 es/utils/keepAliveDecorator.js create mode 100644 es/utils/md5.d.ts create mode 100644 es/utils/md5.js create mode 100644 es/utils/noop.d.ts create mode 100644 es/utils/noop.js create mode 100644 es/utils/shallowEqual.d.ts create mode 100644 es/utils/shallowEqual.js create mode 100644 es/utils/useKeepAliveEffect.d.ts create mode 100644 es/utils/useKeepAliveEffect.js create mode 100644 es/utils/withIdentificationContextConsumer.d.ts create mode 100644 es/utils/withIdentificationContextConsumer.js create mode 100644 es/utils/withKeepAliveContextConsumer.d.ts create mode 100644 es/utils/withKeepAliveContextConsumer.js diff --git a/.gitignore b/.gitignore index 4633ae3..ba2a97b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,2 @@ node_modules coverage -es/** -cjs/** diff --git a/cjs/components/AsyncComponent.d.ts b/cjs/components/AsyncComponent.d.ts new file mode 100644 index 0000000..b0f10bf --- /dev/null +++ b/cjs/components/AsyncComponent.d.ts @@ -0,0 +1,27 @@ +import * as React from 'react'; +interface IProps { + setMounted: (value: boolean) => void; + getMounted: () => boolean; + onUpdate: () => void; +} +interface IState { + component: any; +} +export default class AsyncComponent extends React.Component { + state: { + component: null; + }; + /** + * Force update child nodes + * + * @private + * @returns + * @memberof AsyncComponent + */ + private forceUpdateChildren; + componentDidMount(): void; + componentDidUpdate(): void; + shouldComponentUpdate(): boolean; + render(): null; +} +export {}; diff --git a/cjs/components/AsyncComponent.js b/cjs/components/AsyncComponent.js new file mode 100644 index 0000000..5065c81 --- /dev/null +++ b/cjs/components/AsyncComponent.js @@ -0,0 +1,107 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var React = __importStar(require("react")); +var bindLifecycle_1 = require("../utils/bindLifecycle"); +var AsyncComponent = /** @class */ (function (_super) { + __extends(AsyncComponent, _super); + function AsyncComponent() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.state = { + component: null, + }; + return _this; + } + /** + * Force update child nodes + * + * @private + * @returns + * @memberof AsyncComponent + */ + AsyncComponent.prototype.forceUpdateChildren = function () { + if (!this.props.children) { + return; + } + var root = this._reactInternalFiber || this._reactInternalInstance; + var node = root.child; + var sibling = node; + while (sibling) { + while (true) { + if (node.type && node.type.displayName && node.type.displayName.indexOf(bindLifecycle_1.bindLifecycleTypeName) !== -1) { + return; + } + if (node.stateNode) { + break; + } + node = node.child; + } + if (typeof node.type === 'function') { + node.stateNode.forceUpdate(); + } + sibling = sibling.sibling; + } + }; + AsyncComponent.prototype.componentDidMount = function () { + var _this = this; + var children = this.props.children; + Promise.resolve().then(function () { return _this.setState({ component: children }); }); + }; + AsyncComponent.prototype.componentDidUpdate = function () { + this.props.onUpdate(); + }; + // Delayed update + // In order to be able to get real DOM data + AsyncComponent.prototype.shouldComponentUpdate = function () { + var _this = this; + if (!this.state.component) { + // If it is already mounted asynchronously, you don't need to do it again when you update it. + this.props.setMounted(false); + return true; + } + Promise.resolve().then(function () { + if (_this.props.getMounted()) { + _this.props.setMounted(false); + _this.forceUpdateChildren(); + _this.props.onUpdate(); + } + }); + return false; + }; + AsyncComponent.prototype.render = function () { + return this.state.component; + }; + return AsyncComponent; +}(React.Component)); +exports.default = AsyncComponent; diff --git a/cjs/components/Comment.d.ts b/cjs/components/Comment.d.ts new file mode 100644 index 0000000..fb86a63 --- /dev/null +++ b/cjs/components/Comment.d.ts @@ -0,0 +1,18 @@ +import * as React from 'react'; +interface IReactCommentProps { + onLoaded: () => void; +} +declare class ReactComment extends React.PureComponent { + static defaultProps: { + onLoaded: () => undefined; + }; + private parentNode; + private currentNode; + private commentNode; + private content; + componentDidMount(): void; + componentWillUnmount(): void; + private createComment; + render(): JSX.Element; +} +export default ReactComment; diff --git a/cjs/components/Comment.js b/cjs/components/Comment.js new file mode 100644 index 0000000..76351fe --- /dev/null +++ b/cjs/components/Comment.js @@ -0,0 +1,75 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var React = __importStar(require("react")); +var ReactDOM = __importStar(require("react-dom")); +var noop_1 = __importDefault(require("../utils/noop")); +var ReactComment = /** @class */ (function (_super) { + __extends(ReactComment, _super); + function ReactComment() { + return _super !== null && _super.apply(this, arguments) || this; + } + ReactComment.prototype.componentDidMount = function () { + var node = ReactDOM.findDOMNode(this); + var commentNode = this.createComment(); + this.commentNode = commentNode; + this.currentNode = node; + this.parentNode = node.parentNode; + this.parentNode.replaceChild(commentNode, node); + ReactDOM.unmountComponentAtNode(node); + this.props.onLoaded(); + }; + ReactComment.prototype.componentWillUnmount = function () { + this.parentNode.replaceChild(this.currentNode, this.commentNode); + }; + ReactComment.prototype.createComment = function () { + var content = this.props.children; + if (typeof content !== 'string') { + content = ''; + } + this.content = content.trim(); + return document.createComment(this.content); + }; + ReactComment.prototype.render = function () { + return React.createElement("div", null); + }; + ReactComment.defaultProps = { + onLoaded: noop_1.default, + }; + return ReactComment; +}(React.PureComponent)); +exports.default = ReactComment; diff --git a/cjs/components/Consumer.d.ts b/cjs/components/Consumer.d.ts new file mode 100644 index 0000000..dd7f92a --- /dev/null +++ b/cjs/components/Consumer.d.ts @@ -0,0 +1,20 @@ +import * as React from 'react'; +import { ICache, ICacheItem } from './Provider'; +interface IConsumerProps { + children: React.ReactNode; + identification: string; + keepAlive: boolean; + cache: ICache; + setCache: (identification: string, value: ICacheItem) => void; + unactivate: (identification: string) => void; +} +declare class Consumer extends React.PureComponent { + private renderElement; + private commentRef; + private identification; + componentDidMount(): void; + componentDidUpdate(): void; + componentWillUnmount(): void; + render(): JSX.Element; +} +export default Consumer; diff --git a/cjs/components/Consumer.js b/cjs/components/Consumer.js new file mode 100644 index 0000000..549b2db --- /dev/null +++ b/cjs/components/Consumer.js @@ -0,0 +1,78 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var React = __importStar(require("react")); +var Comment_1 = __importDefault(require("./Comment")); +var Provider_1 = require("./Provider"); +var Consumer = /** @class */ (function (_super) { + __extends(Consumer, _super); + function Consumer() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.identification = _this.props.identification; + return _this; + } + Consumer.prototype.componentDidMount = function () { + var _a = this.props, setCache = _a.setCache, children = _a.children, keepAlive = _a.keepAlive; + this.renderElement = this.commentRef.parentNode; + setCache(this.identification, { + children: children, + keepAlive: keepAlive, + lifecycle: Provider_1.LIFECYCLE.MOUNTED, + renderElement: this.renderElement, + activated: true, + }); + }; + Consumer.prototype.componentDidUpdate = function () { + var _a = this.props, setCache = _a.setCache, children = _a.children, keepAlive = _a.keepAlive; + setCache(this.identification, { + children: children, + keepAlive: keepAlive, + lifecycle: Provider_1.LIFECYCLE.UPDATING, + }); + }; + Consumer.prototype.componentWillUnmount = function () { + var unactivate = this.props.unactivate; + unactivate(this.identification); + }; + Consumer.prototype.render = function () { + var _this = this; + var identification = this.identification; + return React.createElement(Comment_1.default, { ref: function (ref) { return _this.commentRef = ref; } }, identification); + }; + return Consumer; +}(React.PureComponent)); +exports.default = Consumer; diff --git a/cjs/components/KeepAlive.d.ts b/cjs/components/KeepAlive.d.ts new file mode 100644 index 0000000..5089f20 --- /dev/null +++ b/cjs/components/KeepAlive.d.ts @@ -0,0 +1,9 @@ +import * as React from 'react'; +interface IKeepAliveProps { + key?: string; + name?: string; + disabled?: boolean; + extra?: any; +} +declare const _default: React.ComponentType; +export default _default; diff --git a/cjs/components/KeepAlive.js b/cjs/components/KeepAlive.js new file mode 100644 index 0000000..1777d04 --- /dev/null +++ b/cjs/components/KeepAlive.js @@ -0,0 +1,162 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var React = __importStar(require("react")); +var AsyncComponent_1 = __importDefault(require("./AsyncComponent")); +var Provider_1 = require("./Provider"); +var keepAliveDecorator_1 = __importStar(require("../utils/keepAliveDecorator")); +var changePositionByComment_1 = __importDefault(require("../utils/changePositionByComment")); +var KeepAlive = /** @class */ (function (_super) { + __extends(KeepAlive, _super); + function KeepAlive() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.bindUnmount = null; + _this.bindUnactivate = null; + _this.unmounted = false; + _this.mounted = false; + _this.ref = null; + _this.refNextSibling = null; + _this.childNodes = []; + _this.correctionPosition = function () { + if (_this.ref && _this.ref.parentNode && _this.ref.nextSibling) { + var childNodes = _this.ref.childNodes; + _this.refNextSibling = _this.ref.nextSibling; + _this.childNodes = []; + while (childNodes.length) { + var child = childNodes[0]; + _this.childNodes.push(child); + _this.ref.parentNode.insertBefore(child, _this.ref.nextSibling); + } + _this.ref.parentNode.removeChild(_this.ref); + } + }; + _this.retreatPosition = function () { + if (_this.ref && _this.refNextSibling && _this.refNextSibling.parentNode) { + for (var _i = 0, _a = _this.childNodes; _i < _a.length; _i++) { + var child = _a[_i]; + _this.ref.appendChild(child); + } + _this.refNextSibling.parentNode.insertBefore(_this.ref, _this.refNextSibling); + } + }; + _this.setMounted = function (value) { + _this.mounted = value; + }; + _this.getMounted = function () { + return _this.mounted; + }; + return _this; + } + KeepAlive.prototype.componentDidMount = function () { + var _this = this; + var _container = this.props._container; + var notNeedActivate = _container.notNeedActivate, identification = _container.identification, eventEmitter = _container.eventEmitter, keepAlive = _container.keepAlive; + notNeedActivate(); + var cb = function () { + _this.mount(); + _this.listen(); + eventEmitter.off([identification, Provider_1.START_MOUNTING_DOM], cb); + }; + eventEmitter.on([identification, Provider_1.START_MOUNTING_DOM], cb); + if (keepAlive) { + this.componentDidActivate(); + } + }; + KeepAlive.prototype.componentDidActivate = function () { + // tslint-disable + }; + KeepAlive.prototype.componentDidUpdate = function () { + var _container = this.props._container; + var notNeedActivate = _container.notNeedActivate, isNeedActivate = _container.isNeedActivate; + if (isNeedActivate()) { + notNeedActivate(); + this.mount(); + this.listen(); + this.unmounted = false; + this.componentDidActivate(); + } + }; + KeepAlive.prototype.componentWillUnactivate = function () { + this.unmount(); + this.unlisten(); + }; + KeepAlive.prototype.componentWillUnmount = function () { + if (!this.unmounted) { + this.unmounted = true; + this.unmount(); + this.unlisten(); + } + }; + KeepAlive.prototype.mount = function () { + var _a = this.props._container, cache = _a.cache, identification = _a.identification, storeElement = _a.storeElement, setLifecycle = _a.setLifecycle; + this.setMounted(true); + var renderElement = cache[identification].renderElement; + setLifecycle(Provider_1.LIFECYCLE.UPDATING); + changePositionByComment_1.default(identification, renderElement, storeElement); + }; + KeepAlive.prototype.unmount = function () { + var _a = this.props._container, identification = _a.identification, storeElement = _a.storeElement, cache = _a.cache, setLifecycle = _a.setLifecycle; + if (cache[identification]) { + var _b = cache[identification], renderElement = _b.renderElement, ifStillActivate = _b.ifStillActivate, reactivate = _b.reactivate; + setLifecycle(Provider_1.LIFECYCLE.UNMOUNTED); + this.retreatPosition(); + changePositionByComment_1.default(identification, storeElement, renderElement); + if (ifStillActivate) { + reactivate(); + } + } + }; + KeepAlive.prototype.listen = function () { + var _a = this.props._container, identification = _a.identification, eventEmitter = _a.eventEmitter; + eventEmitter.on([identification, keepAliveDecorator_1.COMMAND.CURRENT_UNMOUNT], this.bindUnmount = this.componentWillUnmount.bind(this)); + eventEmitter.on([identification, keepAliveDecorator_1.COMMAND.CURRENT_UNACTIVATE], this.bindUnactivate = this.componentWillUnactivate.bind(this)); + }; + KeepAlive.prototype.unlisten = function () { + var _a = this.props._container, identification = _a.identification, eventEmitter = _a.eventEmitter; + eventEmitter.off([identification, keepAliveDecorator_1.COMMAND.CURRENT_UNMOUNT], this.bindUnmount); + eventEmitter.off([identification, keepAliveDecorator_1.COMMAND.CURRENT_UNACTIVATE], this.bindUnactivate); + }; + KeepAlive.prototype.render = function () { + var _this = this; + // The purpose of this div is to not report an error when moving the DOM, + // so you need to remove this div later. + return (React.createElement("div", { ref: function (ref) { return _this.ref = ref; } }, + React.createElement(AsyncComponent_1.default, { setMounted: this.setMounted, getMounted: this.getMounted, onUpdate: this.correctionPosition }, this.props.children))); + }; + return KeepAlive; +}(React.PureComponent)); +exports.default = keepAliveDecorator_1.default(KeepAlive); diff --git a/cjs/components/Provider.d.ts b/cjs/components/Provider.d.ts new file mode 100644 index 0000000..7352d75 --- /dev/null +++ b/cjs/components/Provider.d.ts @@ -0,0 +1,66 @@ +import * as React from 'react'; +export declare const keepAliveProviderTypeName = "$$KeepAliveProvider"; +export declare const START_MOUNTING_DOM = "startMountingDOM"; +export declare enum LIFECYCLE { + MOUNTED = 0, + UPDATING = 1, + UNMOUNTED = 2 +} +export interface ICacheItem { + children: React.ReactNode; + keepAlive: boolean; + lifecycle: LIFECYCLE; + renderElement?: HTMLElement; + activated?: boolean; + ifStillActivate?: boolean; + reactivate?: () => void; +} +export interface ICache { + [key: string]: ICacheItem; +} +export interface IKeepAliveProviderImpl { + storeElement: HTMLElement; + cache: ICache; + keys: string[]; + eventEmitter: any; + existed: boolean; + providerIdentification: string; + setCache: (identification: string, value: ICacheItem) => void; + removeCache: (name: string) => void; + unactivate: (identification: string) => void; + isExisted: () => boolean; +} +export interface IKeepAliveProviderProps { + include?: string | string[] | RegExp; + exclude?: string | string[] | RegExp; + max?: number; +} +export default class KeepAliveProvider extends React.PureComponent implements IKeepAliveProviderImpl { + static displayName: string; + static defaultProps: { + max: number; + }; + storeElement: HTMLElement; + cache: ICache; + keys: string[]; + eventEmitter: { + on: (eventNames: string | string[], listener: (...args: any) => void, direction?: boolean) => void; + off: (eventNames: string | string[], listener: (...args: any) => void) => void; + emit: (eventNames: string | string[], ...args: any) => void; + clear: () => void; + listenerCount: (eventNames: string | string[]) => number; + removeAllListeners: (eventNames: string | string[]) => void; + }; + existed: boolean; + private needRerender; + providerIdentification: string; + componentDidMount(): void; + componentDidUpdate(): void; + componentWillUnmount(): void; + isExisted: () => boolean; + setCache: (identification: string, value: ICacheItem) => void; + removeCache: (name: string | string[]) => void; + unactivate: (identification: string) => void; + private startMountingDOM; + render(): JSX.Element | null; +} diff --git a/cjs/components/Provider.js b/cjs/components/Provider.js new file mode 100644 index 0000000..c5bb5c0 --- /dev/null +++ b/cjs/components/Provider.js @@ -0,0 +1,210 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LIFECYCLE = exports.START_MOUNTING_DOM = exports.keepAliveProviderTypeName = void 0; +var React = __importStar(require("react")); +var ReactDOM = __importStar(require("react-dom")); +var Comment_1 = __importDefault(require("./Comment")); +var KeepAliveContext_1 = __importDefault(require("../contexts/KeepAliveContext")); +var createEventEmitter_1 = __importDefault(require("../utils/createEventEmitter")); +var createUniqueIdentification_1 = __importDefault(require("../utils/createUniqueIdentification")); +var createStoreElement_1 = __importDefault(require("../utils/createStoreElement")); +exports.keepAliveProviderTypeName = '$$KeepAliveProvider'; +exports.START_MOUNTING_DOM = 'startMountingDOM'; +var LIFECYCLE; +(function (LIFECYCLE) { + LIFECYCLE[LIFECYCLE["MOUNTED"] = 0] = "MOUNTED"; + LIFECYCLE[LIFECYCLE["UPDATING"] = 1] = "UPDATING"; + LIFECYCLE[LIFECYCLE["UNMOUNTED"] = 2] = "UNMOUNTED"; +})(LIFECYCLE = exports.LIFECYCLE || (exports.LIFECYCLE = {})); +var KeepAliveProvider = /** @class */ (function (_super) { + __extends(KeepAliveProvider, _super); + function KeepAliveProvider() { + var _this = _super !== null && _super.apply(this, arguments) || this; + // Sometimes data that changes with setState cannot be synchronized, so force refresh + _this.cache = Object.create(null); + _this.keys = []; + _this.eventEmitter = createEventEmitter_1.default(); + _this.existed = true; + _this.needRerender = false; + _this.providerIdentification = createUniqueIdentification_1.default(); + _this.isExisted = function () { + return _this.existed; + }; + _this.setCache = function (identification, value) { + var _a = _this, cache = _a.cache, keys = _a.keys; + var max = _this.props.max; + var currentCache = cache[identification]; + if (!currentCache) { + keys.push(identification); + } + _this.cache[identification] = __assign(__assign({}, currentCache), value); + _this.forceUpdate(function () { + // If the maximum value is set, the value in the cache is deleted after it goes out. + if (currentCache) { + return; + } + if (!max) { + return; + } + var difference = keys.length - max; + if (difference <= 0) { + return; + } + var spliceKeys = keys.splice(0, difference); + _this.forceUpdate(function () { + spliceKeys.forEach(function (key) { + delete cache[key]; + }); + }); + }); + }; + _this.removeCache = function (name) { + var _a = _this, cache = _a.cache, keys = _a.keys; + var needDeletedCacheKeys = []; + for (var key in cache) { + if (Object.prototype.hasOwnProperty.call(cache, key)) { + var keepAliveObject = cache[key]; + // if name is array, mutiple delete caches + if (Object.prototype.toString.call(name) === '[object Array]') { + if (name.indexOf(keepAliveObject.children._owner.key) > -1) { + needDeletedCacheKeys.push(key); + delete cache[key]; + } + } + else if (Object.prototype.toString.call(name) === '[object String]') { + if (name.indexOf(keepAliveObject.children._owner.key) > -1) { + needDeletedCacheKeys.push(key); + delete cache[key]; + } + } + else { + throw new Error("name can be only string or string array"); + } + } + } + _this.keys = keys.filter(function (key) { return needDeletedCacheKeys.indexOf(key) === -1; }); + _this.forceUpdate(); + }; + _this.unactivate = function (identification) { + var cache = _this.cache; + _this.cache[identification] = __assign(__assign({}, cache[identification]), { activated: false, lifecycle: LIFECYCLE.UNMOUNTED }); + _this.forceUpdate(); + }; + _this.startMountingDOM = function (identification) { + _this.eventEmitter.emit([identification, exports.START_MOUNTING_DOM]); + }; + return _this; + } + KeepAliveProvider.prototype.componentDidMount = function () { + this.storeElement = createStoreElement_1.default(); + this.forceUpdate(); + }; + KeepAliveProvider.prototype.componentDidUpdate = function () { + if (this.needRerender) { + this.needRerender = false; + this.forceUpdate(); + } + }; + KeepAliveProvider.prototype.componentWillUnmount = function () { + this.existed = false; + document.body.removeChild(this.storeElement); + }; + KeepAliveProvider.prototype.render = function () { + var _this = this; + var _a = this, cache = _a.cache, keys = _a.keys, providerIdentification = _a.providerIdentification, isExisted = _a.isExisted, setCache = _a.setCache, removeCache = _a.removeCache, existed = _a.existed, unactivate = _a.unactivate, storeElement = _a.storeElement, eventEmitter = _a.eventEmitter; + var _b = this.props, innerChildren = _b.children, include = _b.include, exclude = _b.exclude; + if (!storeElement) { + return null; + } + return (React.createElement(KeepAliveContext_1.default.Provider, { value: { + cache: cache, + keys: keys, + existed: existed, + providerIdentification: providerIdentification, + isExisted: isExisted, + setCache: setCache, + removeCache: removeCache, + unactivate: unactivate, + storeElement: storeElement, + eventEmitter: eventEmitter, + include: include, + exclude: exclude, + } }, + React.createElement(React.Fragment, null, + innerChildren, + ReactDOM.createPortal(keys.map(function (identification) { + var currentCache = cache[identification]; + var keepAlive = currentCache.keepAlive, children = currentCache.children, lifecycle = currentCache.lifecycle; + var cacheChildren = children; + if (lifecycle === LIFECYCLE.MOUNTED && !keepAlive) { + // If the cache was last enabled, then the components of this keepAlive package are used, + // and the cache is not enabled, the UI needs to be reset. + cacheChildren = null; + _this.needRerender = true; + currentCache.lifecycle = LIFECYCLE.UPDATING; + } + // current true, previous true | undefined, keepAlive false, not cache + // current true, previous true | undefined, keepAlive true, cache + // current true, previous false, keepAlive true, cache + // current true, previous false, keepAlive false, not cache + return (cacheChildren + ? (React.createElement(React.Fragment, { key: identification }, + React.createElement(Comment_1.default, null, identification), + cacheChildren, + React.createElement(Comment_1.default, { onLoaded: function () { return _this.startMountingDOM(identification); } }, identification))) + : null); + }), storeElement)))); + }; + KeepAliveProvider.displayName = exports.keepAliveProviderTypeName; + KeepAliveProvider.defaultProps = { + max: 10, + }; + return KeepAliveProvider; +}(React.PureComponent)); +exports.default = KeepAliveProvider; diff --git a/cjs/contexts/IdentificationContext.d.ts b/cjs/contexts/IdentificationContext.d.ts new file mode 100644 index 0000000..b9bc7ed --- /dev/null +++ b/cjs/contexts/IdentificationContext.d.ts @@ -0,0 +1,12 @@ +import * as React from 'react'; +export interface IIdentificationContextProps { + identification: string; + eventEmitter: any; + keepAlive: boolean; + getLifecycle: () => number; + isExisted: () => boolean; + activated: boolean; + extra: any; +} +declare const WithKeepAliveContext: React.Context; +export default WithKeepAliveContext; diff --git a/cjs/contexts/IdentificationContext.js b/cjs/contexts/IdentificationContext.js new file mode 100644 index 0000000..6548196 --- /dev/null +++ b/cjs/contexts/IdentificationContext.js @@ -0,0 +1,24 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var React = __importStar(require("react")); +var WithKeepAliveContext = React.createContext({}); +exports.default = WithKeepAliveContext; diff --git a/cjs/contexts/KeepAliveContext.d.ts b/cjs/contexts/KeepAliveContext.d.ts new file mode 100644 index 0000000..86782fa --- /dev/null +++ b/cjs/contexts/KeepAliveContext.d.ts @@ -0,0 +1,5 @@ +import * as React from 'react'; +import { IKeepAliveProviderImpl, IKeepAliveProviderProps } from '../components/Provider'; +export declare type IKeepAliveContextProps = IKeepAliveProviderImpl & IKeepAliveProviderProps; +declare const KeepAliveContext: React.Context; +export default KeepAliveContext; diff --git a/cjs/contexts/KeepAliveContext.js b/cjs/contexts/KeepAliveContext.js new file mode 100644 index 0000000..c9b1ab2 --- /dev/null +++ b/cjs/contexts/KeepAliveContext.js @@ -0,0 +1,24 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var React = __importStar(require("react")); +var KeepAliveContext = React.createContext({}); +exports.default = KeepAliveContext; diff --git a/cjs/index.d.ts b/cjs/index.d.ts new file mode 100644 index 0000000..281fce8 --- /dev/null +++ b/cjs/index.d.ts @@ -0,0 +1,5 @@ +import Provider from './components/Provider'; +import KeepAlive from './components/KeepAlive'; +import bindLifecycle from './utils/bindLifecycle'; +import useKeepAliveEffect from './utils/useKeepAliveEffect'; +export { Provider, KeepAlive, bindLifecycle, useKeepAliveEffect, }; diff --git a/cjs/index.js b/cjs/index.js new file mode 100644 index 0000000..e27cd41 --- /dev/null +++ b/cjs/index.js @@ -0,0 +1,14 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.useKeepAliveEffect = exports.bindLifecycle = exports.KeepAlive = exports.Provider = void 0; +var Provider_1 = __importDefault(require("./components/Provider")); +exports.Provider = Provider_1.default; +var KeepAlive_1 = __importDefault(require("./components/KeepAlive")); +exports.KeepAlive = KeepAlive_1.default; +var bindLifecycle_1 = __importDefault(require("./utils/bindLifecycle")); +exports.bindLifecycle = bindLifecycle_1.default; +var useKeepAliveEffect_1 = __importDefault(require("./utils/useKeepAliveEffect")); +exports.useKeepAliveEffect = useKeepAliveEffect_1.default; diff --git a/cjs/utils/bindLifecycle.d.ts b/cjs/utils/bindLifecycle.d.ts new file mode 100644 index 0000000..ce84025 --- /dev/null +++ b/cjs/utils/bindLifecycle.d.ts @@ -0,0 +1,3 @@ +import * as React from 'react'; +export declare const bindLifecycleTypeName = "$$bindLifecycle"; +export default function bindLifecycle

(Component: React.ComponentClass

): any; diff --git a/cjs/utils/bindLifecycle.js b/cjs/utils/bindLifecycle.js new file mode 100644 index 0000000..35f85e1 --- /dev/null +++ b/cjs/utils/bindLifecycle.js @@ -0,0 +1,135 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +var __spreadArrays = (this && this.__spreadArrays) || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.bindLifecycleTypeName = void 0; +var React = __importStar(require("react")); +var hoist_non_react_statics_1 = __importDefault(require("hoist-non-react-statics")); +var noop_1 = __importDefault(require("./noop")); +var debug_1 = require("./debug"); +var keepAliveDecorator_1 = require("./keepAliveDecorator"); +var withIdentificationContextConsumer_1 = __importDefault(require("./withIdentificationContextConsumer")); +var getDisplayName_1 = __importDefault(require("./getDisplayName")); +exports.bindLifecycleTypeName = '$$bindLifecycle'; +function bindLifecycle(Component) { + var WrappedComponent = Component.WrappedComponent || Component.wrappedComponent || Component; + var _a = WrappedComponent.prototype, _b = _a.componentDidMount, componentDidMount = _b === void 0 ? noop_1.default : _b, _c = _a.componentDidUpdate, componentDidUpdate = _c === void 0 ? noop_1.default : _c, _d = _a.componentDidActivate, componentDidActivate = _d === void 0 ? noop_1.default : _d, _e = _a.componentWillUnactivate, componentWillUnactivate = _e === void 0 ? noop_1.default : _e, _f = _a.componentWillUnmount, componentWillUnmount = _f === void 0 ? noop_1.default : _f, _g = _a.shouldComponentUpdate, shouldComponentUpdate = _g === void 0 ? noop_1.default : _g; + WrappedComponent.prototype.componentDidMount = function () { + var _this = this; + componentDidMount.call(this); + this._needActivate = false; + var _a = this.props, _b = _a._container, identification = _b.identification, eventEmitter = _b.eventEmitter, activated = _b.activated, keepAlive = _a.keepAlive; + // Determine whether to execute the componentDidActivate life cycle of the current component based on the activation state of the KeepAlive components + if (!activated && keepAlive !== false) { + componentDidActivate.call(this); + } + eventEmitter.on([identification, keepAliveDecorator_1.COMMAND.ACTIVATE], this._bindActivate = function () { return _this._needActivate = true; }, true); + eventEmitter.on([identification, keepAliveDecorator_1.COMMAND.UNACTIVATE], this._bindUnactivate = function () { + componentWillUnactivate.call(_this); + _this._unmounted = false; + }, true); + eventEmitter.on([identification, keepAliveDecorator_1.COMMAND.UNMOUNT], this._bindUnmount = function () { + componentWillUnmount.call(_this); + _this._unmounted = true; + }, true); + }; + // In order to be able to re-update after transferring the DOM, we need to block the first update. + WrappedComponent.prototype.shouldComponentUpdate = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (this._needActivate) { + this.forceUpdate(); + return false; + } + return shouldComponentUpdate.call.apply(shouldComponentUpdate, __spreadArrays([this], args)) || true; + }; + WrappedComponent.prototype.componentDidUpdate = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + componentDidUpdate.call.apply(componentDidUpdate, __spreadArrays([this], args)); + if (this._needActivate) { + this._needActivate = false; + componentDidActivate.call(this); + } + }; + WrappedComponent.prototype.componentWillUnmount = function () { + if (!this._unmounted) { + componentWillUnmount.call(this); + } + var _a = this.props._container, identification = _a.identification, eventEmitter = _a.eventEmitter; + eventEmitter.off([identification, keepAliveDecorator_1.COMMAND.ACTIVATE], this._bindActivate); + eventEmitter.off([identification, keepAliveDecorator_1.COMMAND.UNACTIVATE], this._bindUnactivate); + eventEmitter.off([identification, keepAliveDecorator_1.COMMAND.UNMOUNT], this._bindUnmount); + }; + var BindLifecycleHOC = withIdentificationContextConsumer_1.default(function (_a) { + var forwardRef = _a.forwardRef, _b = _a._identificationContextProps, identification = _b.identification, eventEmitter = _b.eventEmitter, activated = _b.activated, keepAlive = _b.keepAlive, extra = _b.extra, wrapperProps = __rest(_a, ["forwardRef", "_identificationContextProps"]); + if (!identification) { + debug_1.warn('[React Keep Alive] You should not use bindLifecycle outside a .'); + return null; + } + return (React.createElement(Component, __assign({}, extra, wrapperProps, { ref: forwardRef || noop_1.default, _container: { + identification: identification, + eventEmitter: eventEmitter, + activated: activated, + keepAlive: keepAlive, + } }))); + }); + var BindLifecycle = React.forwardRef(function (props, ref) { return (React.createElement(BindLifecycleHOC, __assign({}, props, { forwardRef: ref }))); }); + BindLifecycle.WrappedComponent = WrappedComponent; + BindLifecycle.displayName = exports.bindLifecycleTypeName + "(" + getDisplayName_1.default(Component) + ")"; + return hoist_non_react_statics_1.default(BindLifecycle, Component); +} +exports.default = bindLifecycle; diff --git a/cjs/utils/changePositionByComment.d.ts b/cjs/utils/changePositionByComment.d.ts new file mode 100644 index 0000000..2168288 --- /dev/null +++ b/cjs/utils/changePositionByComment.d.ts @@ -0,0 +1 @@ +export default function changePositionByComment(identification: string, presentParentNode: Node, originalParentNode: Node): void; diff --git a/cjs/utils/changePositionByComment.js b/cjs/utils/changePositionByComment.js new file mode 100644 index 0000000..ecf1e7c --- /dev/null +++ b/cjs/utils/changePositionByComment.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var NODE_TYPES; +(function (NODE_TYPES) { + NODE_TYPES[NODE_TYPES["ELEMENT"] = 1] = "ELEMENT"; + NODE_TYPES[NODE_TYPES["COMMENT"] = 8] = "COMMENT"; +})(NODE_TYPES || (NODE_TYPES = {})); +function findElementsBetweenComments(node, identification) { + var elements = []; + var childNodes = node.childNodes; + var startCommentExist = false; + for (var _i = 0, childNodes_1 = childNodes; _i < childNodes_1.length; _i++) { + var child = childNodes_1[_i]; + if (child.nodeType === NODE_TYPES.COMMENT && + child.nodeValue.trim() === identification && + !startCommentExist) { + startCommentExist = true; + } + else if (startCommentExist && child.nodeType === NODE_TYPES.ELEMENT) { + elements.push(child); + } + else if (child.nodeType === NODE_TYPES.COMMENT && startCommentExist) { + return elements; + } + } + return elements; +} +function findComment(node, identification) { + var childNodes = node.childNodes; + for (var _i = 0, childNodes_2 = childNodes; _i < childNodes_2.length; _i++) { + var child = childNodes_2[_i]; + if (child.nodeType === NODE_TYPES.COMMENT && + child.nodeValue.trim() === identification) { + return child; + } + } +} +function changePositionByComment(identification, presentParentNode, originalParentNode) { + if (!presentParentNode || !originalParentNode) { + return; + } + var elementNodes = findElementsBetweenComments(originalParentNode, identification); + var commentNode = findComment(presentParentNode, identification); + if (!elementNodes.length || !commentNode) { + return; + } + elementNodes.push(elementNodes[elementNodes.length - 1].nextSibling); + elementNodes.unshift(elementNodes[0].previousSibling); + // Deleting comment elements when using commet components will result in component uninstallation errors + for (var i = elementNodes.length - 1; i >= 0; i--) { + presentParentNode.insertBefore(elementNodes[i], commentNode); + } + originalParentNode.appendChild(commentNode); +} +exports.default = changePositionByComment; diff --git a/cjs/utils/createEventEmitter.d.ts b/cjs/utils/createEventEmitter.d.ts new file mode 100644 index 0000000..48b8a0c --- /dev/null +++ b/cjs/utils/createEventEmitter.d.ts @@ -0,0 +1,11 @@ +declare type EventNames = string | string[]; +declare type Listener = (...args: any) => void; +export default function createEventEmitter(): { + on: (eventNames: EventNames, listener: Listener, direction?: boolean) => void; + off: (eventNames: EventNames, listener: Listener) => void; + emit: (eventNames: EventNames, ...args: any) => void; + clear: () => void; + listenerCount: (eventNames: EventNames) => number; + removeAllListeners: (eventNames: EventNames) => void; +}; +export {}; diff --git a/cjs/utils/createEventEmitter.js b/cjs/utils/createEventEmitter.js new file mode 100644 index 0000000..d957774 --- /dev/null +++ b/cjs/utils/createEventEmitter.js @@ -0,0 +1,100 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var debug_1 = require("./debug"); +function createEventEmitter() { + var events = Object.create(null); + function on(eventNames, listener, direction) { + if (direction === void 0) { direction = false; } + eventNames = getEventNames(eventNames); + var current = events; + var maxIndex = eventNames.length - 1; + for (var i = 0; i < eventNames.length; i++) { + var key = eventNames[i]; + if (!current[key]) { + current[key] = i === maxIndex ? [] : {}; + } + current = current[key]; + } + if (!Array.isArray(current)) { + debug_1.warn('[React Keep Alive] Access path error.'); + } + if (direction) { + current.unshift(listener); + } + else { + current.push(listener); + } + } + function off(eventNames, listener) { + var listeners = getListeners(eventNames); + if (!listeners) { + return; + } + var matchIndex = listeners.findIndex(function (v) { return v === listener; }); + if (matchIndex !== -1) { + listeners.splice(matchIndex, 1); + } + } + function removeAllListeners(eventNames) { + var listeners = getListeners(eventNames); + if (!listeners) { + return; + } + eventNames = getEventNames(eventNames); + var lastEventName = eventNames.pop(); + if (lastEventName) { + var event_1 = eventNames.reduce(function (obj, key) { return obj[key]; }, events); + event_1[lastEventName] = []; + } + } + function emit(eventNames) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var listeners = getListeners(eventNames); + if (!listeners) { + return; + } + for (var _a = 0, listeners_1 = listeners; _a < listeners_1.length; _a++) { + var listener = listeners_1[_a]; + if (listener) { + listener.apply(void 0, args); + } + } + } + function listenerCount(eventNames) { + var listeners = getListeners(eventNames); + return listeners ? listeners.length : 0; + } + function clear() { + events = Object.create(null); + } + function getListeners(eventNames) { + eventNames = getEventNames(eventNames); + try { + return eventNames.reduce(function (obj, key) { return obj[key]; }, events); + } + catch (e) { + return; + } + } + function getEventNames(eventNames) { + if (!eventNames) { + debug_1.warn('[React Keep Alive] Must exist event name.'); + } + if (typeof eventNames === 'string') { + eventNames = [eventNames]; + } + return eventNames; + } + return { + on: on, + off: off, + emit: emit, + clear: clear, + listenerCount: listenerCount, + removeAllListeners: removeAllListeners, + }; +} +exports.default = createEventEmitter; diff --git a/cjs/utils/createStoreElement.d.ts b/cjs/utils/createStoreElement.d.ts new file mode 100644 index 0000000..1586ec3 --- /dev/null +++ b/cjs/utils/createStoreElement.d.ts @@ -0,0 +1 @@ +export default function createStoreElement(): HTMLElement; diff --git a/cjs/utils/createStoreElement.js b/cjs/utils/createStoreElement.js new file mode 100644 index 0000000..eb21478 --- /dev/null +++ b/cjs/utils/createStoreElement.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var createUniqueIdentification_1 = require("./createUniqueIdentification"); +function createStoreElement() { + var keepAliveDOM = document.createElement('div'); + keepAliveDOM.dataset.type = createUniqueIdentification_1.prefix; + keepAliveDOM.style.display = 'none'; + document.body.appendChild(keepAliveDOM); + return keepAliveDOM; +} +exports.default = createStoreElement; diff --git a/cjs/utils/createUniqueIdentification.d.ts b/cjs/utils/createUniqueIdentification.d.ts new file mode 100644 index 0000000..1b9035c --- /dev/null +++ b/cjs/utils/createUniqueIdentification.d.ts @@ -0,0 +1,8 @@ +export declare const prefix = "keep-alive"; +/** + * Create UUID + * Reference: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript + * @export + * @returns + */ +export default function createUniqueIdentification(length?: number): string; diff --git a/cjs/utils/createUniqueIdentification.js b/cjs/utils/createUniqueIdentification.js new file mode 100644 index 0000000..f632a70 --- /dev/null +++ b/cjs/utils/createUniqueIdentification.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.prefix = void 0; +var hexDigits = '0123456789abcdef'; +exports.prefix = 'keep-alive'; +/** + * Create UUID + * Reference: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript + * @export + * @returns + */ +function createUniqueIdentification(length) { + if (length === void 0) { length = 6; } + var strings = []; + for (var i = 0; i < length; i++) { + strings[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); + } + return exports.prefix + "-" + strings.join(''); +} +exports.default = createUniqueIdentification; diff --git a/cjs/utils/debug.d.ts b/cjs/utils/debug.d.ts new file mode 100644 index 0000000..19bfe26 --- /dev/null +++ b/cjs/utils/debug.d.ts @@ -0,0 +1,3 @@ +declare type Warn = (message?: string) => void; +export declare let warn: Warn; +export {}; diff --git a/cjs/utils/debug.js b/cjs/utils/debug.js new file mode 100644 index 0000000..262066e --- /dev/null +++ b/cjs/utils/debug.js @@ -0,0 +1,19 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.warn = void 0; +exports.warn = function () { return undefined; }; +if (process.env.NODE_ENV !== 'production') { + /** + * Prints a warning in the console if it exists. + * + * @param {*} message + */ + exports.warn = function (message) { + if (typeof console !== undefined && typeof console.error === 'function') { + console.error(message); + } + else { + throw new Error(message); + } + }; +} diff --git a/cjs/utils/getDisplayName.d.ts b/cjs/utils/getDisplayName.d.ts new file mode 100644 index 0000000..1bfafad --- /dev/null +++ b/cjs/utils/getDisplayName.d.ts @@ -0,0 +1,2 @@ +import * as React from 'react'; +export default function getDisplayName(Component: React.ComponentType): string; diff --git a/cjs/utils/getDisplayName.js b/cjs/utils/getDisplayName.js new file mode 100644 index 0000000..12bd7b3 --- /dev/null +++ b/cjs/utils/getDisplayName.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function getDisplayName(Component) { + return Component.displayName || Component.name || 'Component'; +} +exports.default = getDisplayName; diff --git a/cjs/utils/getKeepAlive.d.ts b/cjs/utils/getKeepAlive.d.ts new file mode 100644 index 0000000..94d9505 --- /dev/null +++ b/cjs/utils/getKeepAlive.d.ts @@ -0,0 +1,3 @@ +declare type Pattern = string | string[] | RegExp; +export default function getKeepAlive(name: string, include?: Pattern, exclude?: Pattern, disabled?: boolean): boolean; +export {}; diff --git a/cjs/utils/getKeepAlive.js b/cjs/utils/getKeepAlive.js new file mode 100644 index 0000000..3676e7e --- /dev/null +++ b/cjs/utils/getKeepAlive.js @@ -0,0 +1,29 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var isRegExp_1 = __importDefault(require("./isRegExp")); +function matches(pattern, name) { + if (Array.isArray(pattern)) { + return pattern.indexOf(name) > -1; + } + else if (typeof pattern === 'string') { + return pattern.split(',').indexOf(name) > -1; + } + else if (isRegExp_1.default(pattern)) { + return pattern.test(name); + } + return false; +} +function getKeepAlive(name, include, exclude, disabled) { + if (disabled !== undefined) { + return !disabled; + } + if ((include && (!name || !matches(include, name))) || + (exclude && name && matches(exclude, name))) { + return false; + } + return true; +} +exports.default = getKeepAlive; diff --git a/cjs/utils/getKeyByFiberNode.d.ts b/cjs/utils/getKeyByFiberNode.d.ts new file mode 100644 index 0000000..8ddecb0 --- /dev/null +++ b/cjs/utils/getKeyByFiberNode.d.ts @@ -0,0 +1 @@ +export default function getKeyByFiberNode(fiberNode: any): string | null; diff --git a/cjs/utils/getKeyByFiberNode.js b/cjs/utils/getKeyByFiberNode.js new file mode 100644 index 0000000..22fc5fb --- /dev/null +++ b/cjs/utils/getKeyByFiberNode.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var withKeepAliveContextConsumer_1 = require("./withKeepAliveContextConsumer"); +function getKeyByFiberNode(fiberNode) { + if (!fiberNode) { + return null; + } + var key = fiberNode.key, type = fiberNode.type; + if (type.displayName && type.displayName.indexOf(withKeepAliveContextConsumer_1.WithKeepAliveContextConsumerDisplayName) !== -1) { + return key; + } + return getKeyByFiberNode(fiberNode.return); +} +exports.default = getKeyByFiberNode; diff --git a/cjs/utils/isRegExp.d.ts b/cjs/utils/isRegExp.d.ts new file mode 100644 index 0000000..a9efce0 --- /dev/null +++ b/cjs/utils/isRegExp.d.ts @@ -0,0 +1 @@ +export default function isRegExp(value: RegExp): boolean; diff --git a/cjs/utils/isRegExp.js b/cjs/utils/isRegExp.js new file mode 100644 index 0000000..f4efedb --- /dev/null +++ b/cjs/utils/isRegExp.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function isRegExp(value) { + return value && Object.prototype.toString.call(value) === '[object RegExp]'; +} +exports.default = isRegExp; diff --git a/cjs/utils/keepAliveDecorator.d.ts b/cjs/utils/keepAliveDecorator.d.ts new file mode 100644 index 0000000..d5af014 --- /dev/null +++ b/cjs/utils/keepAliveDecorator.d.ts @@ -0,0 +1,17 @@ +import * as React from 'react'; +export declare enum COMMAND { + UNACTIVATE = "unactivate", + UNMOUNT = "unmount", + ACTIVATE = "activate", + CURRENT_UNMOUNT = "current_unmount", + CURRENT_UNACTIVATE = "current_unactivate" +} +/** + * Decorating the component, the main function is to listen to events emitted by the upper component, triggering events of the current component. + * + * @export + * @template P + * @param {React.ComponentType} Component + * @returns {React.ComponentType

} + */ +export default function keepAliveDecorator

(Component: React.ComponentType): React.ComponentType

; diff --git a/cjs/utils/keepAliveDecorator.js b/cjs/utils/keepAliveDecorator.js new file mode 100644 index 0000000..7a60a12 --- /dev/null +++ b/cjs/utils/keepAliveDecorator.js @@ -0,0 +1,281 @@ +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +var __spreadArrays = (this && this.__spreadArrays) || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.COMMAND = void 0; +var React = __importStar(require("react")); +var hoist_non_react_statics_1 = __importDefault(require("hoist-non-react-statics")); +var IdentificationContext_1 = __importDefault(require("../contexts/IdentificationContext")); +var Consumer_1 = __importDefault(require("../components/Consumer")); +var Provider_1 = require("../components/Provider"); +var md5_1 = __importDefault(require("./md5")); +var debug_1 = require("./debug"); +var getKeyByFiberNode_1 = __importDefault(require("./getKeyByFiberNode")); +var withIdentificationContextConsumer_1 = __importDefault(require("./withIdentificationContextConsumer")); +var withKeepAliveContextConsumer_1 = __importDefault(require("./withKeepAliveContextConsumer")); +var shallowEqual_1 = __importDefault(require("./shallowEqual")); +var getKeepAlive_1 = __importDefault(require("./getKeepAlive")); +var COMMAND; +(function (COMMAND) { + COMMAND["UNACTIVATE"] = "unactivate"; + COMMAND["UNMOUNT"] = "unmount"; + COMMAND["ACTIVATE"] = "activate"; + COMMAND["CURRENT_UNMOUNT"] = "current_unmount"; + COMMAND["CURRENT_UNACTIVATE"] = "current_unactivate"; +})(COMMAND = exports.COMMAND || (exports.COMMAND = {})); +/** + * Decorating the component, the main function is to listen to events emitted by the upper component, triggering events of the current component. + * + * @export + * @template P + * @param {React.ComponentType} Component + * @returns {React.ComponentType

} + */ +function keepAliveDecorator(Component) { + var TriggerLifecycleContainer = /** @class */ (function (_super) { + __extends(TriggerLifecycleContainer, _super); + function TriggerLifecycleContainer(props) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var _this = _super.apply(this, __spreadArrays([props], args)) || this; + _this.activated = false; + _this.ifStillActivate = false; + // Let the lifecycle of the cached component be called normally. + _this.needActivate = true; + _this.lifecycle = Provider_1.LIFECYCLE.MOUNTED; + _this.activate = function () { + _this.activated = true; + }; + _this.reactivate = function () { + _this.ifStillActivate = false; + _this.forceUpdate(); + }; + _this.isNeedActivate = function () { + return _this.needActivate; + }; + _this.notNeedActivate = function () { + _this.needActivate = false; + }; + _this.getLifecycle = function () { + return _this.lifecycle; + }; + _this.setLifecycle = function (lifecycle) { + _this.lifecycle = lifecycle; + }; + var cache = props._keepAliveContextProps.cache; + if (!cache) { + debug_1.warn('[React Keep Alive] You should not use outside a .'); + } + return _this; + } + TriggerLifecycleContainer.prototype.componentDidMount = function () { + if (!this.ifStillActivate) { + this.activate(); + } + var _a = this.props, keepAlive = _a.keepAlive, eventEmitter = _a._keepAliveContextProps.eventEmitter; + if (keepAlive) { + this.needActivate = true; + eventEmitter.emit([this.identification, COMMAND.ACTIVATE]); + } + }; + TriggerLifecycleContainer.prototype.componentDidCatch = function () { + if (!this.activated) { + this.activate(); + } + }; + TriggerLifecycleContainer.prototype.componentWillUnmount = function () { + var _a = this.props, getCombinedKeepAlive = _a.getCombinedKeepAlive, _b = _a._keepAliveContextProps, eventEmitter = _b.eventEmitter, isExisted = _b.isExisted; + var keepAlive = getCombinedKeepAlive(); + if (!keepAlive || !isExisted()) { + eventEmitter.emit([this.identification, COMMAND.CURRENT_UNMOUNT]); + eventEmitter.emit([this.identification, COMMAND.UNMOUNT]); + } + // When the Provider components are unmounted, the cache is not needed, + // so you don't have to execute the componentWillUnactivate lifecycle. + if (keepAlive && isExisted()) { + eventEmitter.emit([this.identification, COMMAND.CURRENT_UNACTIVATE]); + eventEmitter.emit([this.identification, COMMAND.UNACTIVATE]); + } + }; + TriggerLifecycleContainer.prototype.render = function () { + var _a = this.props, propKey = _a.propKey, keepAlive = _a.keepAlive, extra = _a.extra, getCombinedKeepAlive = _a.getCombinedKeepAlive, _b = _a._keepAliveContextProps, isExisted = _b.isExisted, storeElement = _b.storeElement, cache = _b.cache, eventEmitter = _b.eventEmitter, setCache = _b.setCache, unactivate = _b.unactivate, providerIdentification = _b.providerIdentification, wrapperProps = __rest(_a, ["propKey", "keepAlive", "extra", "getCombinedKeepAlive", "_keepAliveContextProps"]); + if (!this.identification) { + // We need to generate a corresponding unique identifier based on the information of the component. + this.identification = md5_1.default("" + providerIdentification + propKey); + // The last activated component must be unactivated before it can be activated again. + var currentCache = cache[this.identification]; + if (currentCache) { + this.ifStillActivate = currentCache.activated; + currentCache.ifStillActivate = this.ifStillActivate; + currentCache.reactivate = this.reactivate; + } + } + var _c = this, isNeedActivate = _c.isNeedActivate, notNeedActivate = _c.notNeedActivate, activated = _c.activated, getLifecycle = _c.getLifecycle, setLifecycle = _c.setLifecycle, identification = _c.identification, ifStillActivate = _c.ifStillActivate; + return !ifStillActivate + ? (React.createElement(Consumer_1.default, { identification: identification, keepAlive: keepAlive, cache: cache, setCache: setCache, unactivate: unactivate }, + React.createElement(IdentificationContext_1.default.Provider, { value: { + identification: identification, + eventEmitter: eventEmitter, + keepAlive: keepAlive, + activated: activated, + getLifecycle: getLifecycle, + isExisted: isExisted, + extra: extra, + } }, + React.createElement(Component, __assign({}, wrapperProps, { _container: { + isNeedActivate: isNeedActivate, + notNeedActivate: notNeedActivate, + setLifecycle: setLifecycle, + eventEmitter: eventEmitter, + identification: identification, + storeElement: storeElement, + keepAlive: keepAlive, + cache: cache, + } }))))) + : null; + }; + return TriggerLifecycleContainer; + }(React.PureComponent)); + var ListenUpperKeepAliveContainer = /** @class */ (function (_super) { + __extends(ListenUpperKeepAliveContainer, _super); + function ListenUpperKeepAliveContainer() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.state = { + activated: true, + }; + _this.getCombinedKeepAlive = function () { + return _this.combinedKeepAlive; + }; + return _this; + } + ListenUpperKeepAliveContainer.prototype.shouldComponentUpdate = function (nextProps, nextState) { + if (this.state.activated !== nextState.activated) { + return true; + } + var _a = this.props, _keepAliveContextProps = _a._keepAliveContextProps, _identificationContextProps = _a._identificationContextProps, rest = __rest(_a, ["_keepAliveContextProps", "_identificationContextProps"]); + var nextKeepAliveContextProps = nextProps._keepAliveContextProps, nextIdentificationContextProps = nextProps._identificationContextProps, nextRest = __rest(nextProps, ["_keepAliveContextProps", "_identificationContextProps"]); + if (!shallowEqual_1.default(rest, nextRest)) { + return true; + } + if (!shallowEqual_1.default(_keepAliveContextProps, nextKeepAliveContextProps) || + !shallowEqual_1.default(_identificationContextProps, nextIdentificationContextProps)) { + return true; + } + return false; + }; + ListenUpperKeepAliveContainer.prototype.componentDidMount = function () { + this.listenUpperKeepAlive(); + }; + ListenUpperKeepAliveContainer.prototype.componentWillUnmount = function () { + this.unlistenUpperKeepAlive(); + }; + ListenUpperKeepAliveContainer.prototype.listenUpperKeepAlive = function () { + var _this = this; + var _a = this.props._identificationContextProps, identification = _a.identification, eventEmitter = _a.eventEmitter; + if (!identification) { + return; + } + eventEmitter.on([identification, COMMAND.ACTIVATE], this.activate = function () { return _this.setState({ activated: true }); }, true); + eventEmitter.on([identification, COMMAND.UNACTIVATE], this.unactivate = function () { return _this.setState({ activated: false }); }, true); + eventEmitter.on([identification, COMMAND.UNMOUNT], this.unmount = function () { return _this.setState({ activated: false }); }, true); + }; + ListenUpperKeepAliveContainer.prototype.unlistenUpperKeepAlive = function () { + var _a = this.props._identificationContextProps, identification = _a.identification, eventEmitter = _a.eventEmitter; + if (!identification) { + return; + } + eventEmitter.off([identification, COMMAND.ACTIVATE], this.activate); + eventEmitter.off([identification, COMMAND.UNACTIVATE], this.unactivate); + eventEmitter.off([identification, COMMAND.UNMOUNT], this.unmount); + }; + ListenUpperKeepAliveContainer.prototype.render = function () { + var _a = this.props, _b = _a._identificationContextProps, identification = _b.identification, upperKeepAlive = _b.keepAlive, getLifecycle = _b.getLifecycle, disabled = _a.disabled, name = _a.name, wrapperProps = __rest(_a, ["_identificationContextProps", "disabled", "name"]); + var activated = this.state.activated; + var _c = wrapperProps._keepAliveContextProps, include = _c.include, exclude = _c.exclude; + // When the parent KeepAlive component is mounted or unmounted, + // use the keepAlive prop of the parent KeepAlive component. + var propKey = name || getKeyByFiberNode_1.default(this._reactInternalFiber); + if (!propKey) { + debug_1.warn('[React Keep Alive] components must have key or name.'); + return null; + } + var newKeepAlive = getKeepAlive_1.default(propKey, include, exclude, disabled); + this.combinedKeepAlive = getLifecycle === undefined || getLifecycle() === Provider_1.LIFECYCLE.UPDATING + ? newKeepAlive + : identification + ? upperKeepAlive && newKeepAlive + : newKeepAlive; + return activated + ? (React.createElement(TriggerLifecycleContainer, __assign({}, wrapperProps, { key: propKey, propKey: propKey, keepAlive: this.combinedKeepAlive, getCombinedKeepAlive: this.getCombinedKeepAlive }))) + : null; + }; + return ListenUpperKeepAliveContainer; + }(React.Component)); + var KeepAlive = withKeepAliveContextConsumer_1.default(withIdentificationContextConsumer_1.default(ListenUpperKeepAliveContainer)); + return hoist_non_react_statics_1.default(KeepAlive, Component); +} +exports.default = keepAliveDecorator; diff --git a/cjs/utils/md5.d.ts b/cjs/utils/md5.d.ts new file mode 100644 index 0000000..2bc3f1f --- /dev/null +++ b/cjs/utils/md5.d.ts @@ -0,0 +1 @@ +export default function createMD5(value?: string, length?: number): string; diff --git a/cjs/utils/md5.js b/cjs/utils/md5.js new file mode 100644 index 0000000..07b9830 --- /dev/null +++ b/cjs/utils/md5.js @@ -0,0 +1,13 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var js_md5_1 = __importDefault(require("js-md5")); +var createUniqueIdentification_1 = require("./createUniqueIdentification"); +function createMD5(value, length) { + if (value === void 0) { value = ''; } + if (length === void 0) { length = 6; } + return createUniqueIdentification_1.prefix + "-" + js_md5_1.default(value).substr(0, length); +} +exports.default = createMD5; diff --git a/cjs/utils/noop.d.ts b/cjs/utils/noop.d.ts new file mode 100644 index 0000000..235cf5f --- /dev/null +++ b/cjs/utils/noop.d.ts @@ -0,0 +1,2 @@ +declare const noop: () => undefined; +export default noop; diff --git a/cjs/utils/noop.js b/cjs/utils/noop.js new file mode 100644 index 0000000..414046e --- /dev/null +++ b/cjs/utils/noop.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var noop = function () { return undefined; }; +exports.default = noop; diff --git a/cjs/utils/shallowEqual.d.ts b/cjs/utils/shallowEqual.d.ts new file mode 100644 index 0000000..7b448a3 --- /dev/null +++ b/cjs/utils/shallowEqual.d.ts @@ -0,0 +1,2 @@ +declare function shallowEqual(objA: object, objB: object): boolean; +export default shallowEqual; diff --git a/cjs/utils/shallowEqual.js b/cjs/utils/shallowEqual.js new file mode 100644 index 0000000..08ef250 --- /dev/null +++ b/cjs/utils/shallowEqual.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * From react + */ +function is(x, y) { + return ((x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare + ); +} +var hasOwnProperty = Object.prototype.hasOwnProperty; +function shallowEqual(objA, objB) { + if (is(objA, objB)) { + return true; + } + if (typeof objA !== 'object' || + objA === null || + typeof objB !== 'object' || + objB === null) { + return false; + } + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + if (keysA.length !== keysB.length) { + return false; + } + // Test for A's keys different from B. + for (var _i = 0, keysA_1 = keysA; _i < keysA_1.length; _i++) { + var key = keysA_1[_i]; + if (!hasOwnProperty.call(objB, key) || + !is(objA[key], objB[key])) { + return false; + } + } + return true; +} +exports.default = shallowEqual; diff --git a/cjs/utils/useKeepAliveEffect.d.ts b/cjs/utils/useKeepAliveEffect.d.ts new file mode 100644 index 0000000..9b203d3 --- /dev/null +++ b/cjs/utils/useKeepAliveEffect.d.ts @@ -0,0 +1,2 @@ +import React from 'react'; +export default function useKeepAliveEffect(effect: React.EffectCallback): void; diff --git a/cjs/utils/useKeepAliveEffect.js b/cjs/utils/useKeepAliveEffect.js new file mode 100644 index 0000000..18c4c09 --- /dev/null +++ b/cjs/utils/useKeepAliveEffect.js @@ -0,0 +1,52 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +var react_1 = require("react"); +var debug_1 = require("./debug"); +var keepAliveDecorator_1 = require("./keepAliveDecorator"); +var IdentificationContext_1 = __importDefault(require("../contexts/IdentificationContext")); +function useKeepAliveEffect(effect) { + if (!react_1.useEffect) { + debug_1.warn('[React Keep Alive] useKeepAliveEffect API requires react 16.8 or later.'); + } + var _a = react_1.useContext(IdentificationContext_1.default), eventEmitter = _a.eventEmitter, identification = _a.identification; + var effectRef = react_1.useRef(effect); + effectRef.current = effect; + react_1.useEffect(function () { + var bindActivate = null; + var bindUnactivate = null; + var bindUnmount = null; + var effectResult = effectRef.current(); + var unmounted = false; + eventEmitter.on([identification, keepAliveDecorator_1.COMMAND.ACTIVATE], bindActivate = function () { + // Delayed update + Promise.resolve().then(function () { + effectResult = effectRef.current(); + }); + unmounted = false; + }, true); + eventEmitter.on([identification, keepAliveDecorator_1.COMMAND.UNACTIVATE], bindUnactivate = function () { + if (effectResult) { + effectResult(); + unmounted = true; + } + }, true); + eventEmitter.on([identification, keepAliveDecorator_1.COMMAND.UNMOUNT], bindUnmount = function () { + if (effectResult) { + effectResult(); + unmounted = true; + } + }, true); + return function () { + if (effectResult && !unmounted) { + effectResult(); + } + eventEmitter.off([identification, keepAliveDecorator_1.COMMAND.ACTIVATE], bindActivate); + eventEmitter.off([identification, keepAliveDecorator_1.COMMAND.UNACTIVATE], bindUnactivate); + eventEmitter.off([identification, keepAliveDecorator_1.COMMAND.UNMOUNT], bindUnmount); + }; + }, []); +} +exports.default = useKeepAliveEffect; diff --git a/cjs/utils/withIdentificationContextConsumer.d.ts b/cjs/utils/withIdentificationContextConsumer.d.ts new file mode 100644 index 0000000..5fd31a6 --- /dev/null +++ b/cjs/utils/withIdentificationContextConsumer.d.ts @@ -0,0 +1,10 @@ +import * as React from 'react'; +import { IIdentificationContextProps } from '../contexts/IdentificationContext'; +export interface IIdentificationContextConsumerComponentProps { + _identificationContextProps: IIdentificationContextProps; +} +export declare const withIdentificationContextConsumerDisplayName = "withIdentificationContextConsumer"; +export default function withIdentificationContextConsumer

(Component: React.ComponentType): { + (props: P): JSX.Element; + displayName: string; +}; diff --git a/cjs/utils/withIdentificationContextConsumer.js b/cjs/utils/withIdentificationContextConsumer.js new file mode 100644 index 0000000..912a33a --- /dev/null +++ b/cjs/utils/withIdentificationContextConsumer.js @@ -0,0 +1,46 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.withIdentificationContextConsumerDisplayName = void 0; +var React = __importStar(require("react")); +var IdentificationContext_1 = __importDefault(require("../contexts/IdentificationContext")); +var getDisplayName_1 = __importDefault(require("./getDisplayName")); +exports.withIdentificationContextConsumerDisplayName = 'withIdentificationContextConsumer'; +function withIdentificationContextConsumer(Component) { + var WithIdentificationContextConsumer = function (props) { return (React.createElement(IdentificationContext_1.default.Consumer, null, function (contextProps) { return React.createElement(Component, __assign({ _identificationContextProps: contextProps }, props)); })); }; + WithIdentificationContextConsumer.displayName = exports.withIdentificationContextConsumerDisplayName + "(" + getDisplayName_1.default(Component) + ")"; + return WithIdentificationContextConsumer; +} +exports.default = withIdentificationContextConsumer; diff --git a/cjs/utils/withKeepAliveContextConsumer.d.ts b/cjs/utils/withKeepAliveContextConsumer.d.ts new file mode 100644 index 0000000..ade1441 --- /dev/null +++ b/cjs/utils/withKeepAliveContextConsumer.d.ts @@ -0,0 +1,10 @@ +import * as React from 'react'; +import { IKeepAliveContextProps } from '../contexts/KeepAliveContext'; +export interface IKeepAliveContextConsumerComponentProps { + _keepAliveContextProps: IKeepAliveContextProps; +} +export declare const WithKeepAliveContextConsumerDisplayName = "withKeepAliveContextConsumer"; +export default function withKeepAliveContextConsumer

(Component: React.ComponentType): { + (props: P): JSX.Element; + displayName: string; +}; diff --git a/cjs/utils/withKeepAliveContextConsumer.js b/cjs/utils/withKeepAliveContextConsumer.js new file mode 100644 index 0000000..b3aa24a --- /dev/null +++ b/cjs/utils/withKeepAliveContextConsumer.js @@ -0,0 +1,46 @@ +"use strict"; +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WithKeepAliveContextConsumerDisplayName = void 0; +var React = __importStar(require("react")); +var KeepAliveContext_1 = __importDefault(require("../contexts/KeepAliveContext")); +var getDisplayName_1 = __importDefault(require("./getDisplayName")); +exports.WithKeepAliveContextConsumerDisplayName = 'withKeepAliveContextConsumer'; +function withKeepAliveContextConsumer(Component) { + var WithKeepAliveContextConsumer = function (props) { return (React.createElement(KeepAliveContext_1.default.Consumer, null, function (contextProps) { return React.createElement(Component, __assign({ _keepAliveContextProps: contextProps }, props)); })); }; + WithKeepAliveContextConsumer.displayName = exports.WithKeepAliveContextConsumerDisplayName + "(" + getDisplayName_1.default(Component) + ")"; + return WithKeepAliveContextConsumer; +} +exports.default = withKeepAliveContextConsumer; diff --git a/es/components/AsyncComponent.d.ts b/es/components/AsyncComponent.d.ts new file mode 100644 index 0000000..b0f10bf --- /dev/null +++ b/es/components/AsyncComponent.d.ts @@ -0,0 +1,27 @@ +import * as React from 'react'; +interface IProps { + setMounted: (value: boolean) => void; + getMounted: () => boolean; + onUpdate: () => void; +} +interface IState { + component: any; +} +export default class AsyncComponent extends React.Component { + state: { + component: null; + }; + /** + * Force update child nodes + * + * @private + * @returns + * @memberof AsyncComponent + */ + private forceUpdateChildren; + componentDidMount(): void; + componentDidUpdate(): void; + shouldComponentUpdate(): boolean; + render(): null; +} +export {}; diff --git a/es/components/AsyncComponent.js b/es/components/AsyncComponent.js new file mode 100644 index 0000000..ed876f9 --- /dev/null +++ b/es/components/AsyncComponent.js @@ -0,0 +1,86 @@ +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +import * as React from 'react'; +import { bindLifecycleTypeName } from '../utils/bindLifecycle'; +var AsyncComponent = /** @class */ (function (_super) { + __extends(AsyncComponent, _super); + function AsyncComponent() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.state = { + component: null, + }; + return _this; + } + /** + * Force update child nodes + * + * @private + * @returns + * @memberof AsyncComponent + */ + AsyncComponent.prototype.forceUpdateChildren = function () { + if (!this.props.children) { + return; + } + var root = this._reactInternalFiber || this._reactInternalInstance; + var node = root.child; + var sibling = node; + while (sibling) { + while (true) { + if (node.type && node.type.displayName && node.type.displayName.indexOf(bindLifecycleTypeName) !== -1) { + return; + } + if (node.stateNode) { + break; + } + node = node.child; + } + if (typeof node.type === 'function') { + node.stateNode.forceUpdate(); + } + sibling = sibling.sibling; + } + }; + AsyncComponent.prototype.componentDidMount = function () { + var _this = this; + var children = this.props.children; + Promise.resolve().then(function () { return _this.setState({ component: children }); }); + }; + AsyncComponent.prototype.componentDidUpdate = function () { + this.props.onUpdate(); + }; + // Delayed update + // In order to be able to get real DOM data + AsyncComponent.prototype.shouldComponentUpdate = function () { + var _this = this; + if (!this.state.component) { + // If it is already mounted asynchronously, you don't need to do it again when you update it. + this.props.setMounted(false); + return true; + } + Promise.resolve().then(function () { + if (_this.props.getMounted()) { + _this.props.setMounted(false); + _this.forceUpdateChildren(); + _this.props.onUpdate(); + } + }); + return false; + }; + AsyncComponent.prototype.render = function () { + return this.state.component; + }; + return AsyncComponent; +}(React.Component)); +export default AsyncComponent; diff --git a/es/components/Comment.d.ts b/es/components/Comment.d.ts new file mode 100644 index 0000000..fb86a63 --- /dev/null +++ b/es/components/Comment.d.ts @@ -0,0 +1,18 @@ +import * as React from 'react'; +interface IReactCommentProps { + onLoaded: () => void; +} +declare class ReactComment extends React.PureComponent { + static defaultProps: { + onLoaded: () => undefined; + }; + private parentNode; + private currentNode; + private commentNode; + private content; + componentDidMount(): void; + componentWillUnmount(): void; + private createComment; + render(): JSX.Element; +} +export default ReactComment; diff --git a/es/components/Comment.js b/es/components/Comment.js new file mode 100644 index 0000000..f1b97ff --- /dev/null +++ b/es/components/Comment.js @@ -0,0 +1,51 @@ +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import noop from '../utils/noop'; +var ReactComment = /** @class */ (function (_super) { + __extends(ReactComment, _super); + function ReactComment() { + return _super !== null && _super.apply(this, arguments) || this; + } + ReactComment.prototype.componentDidMount = function () { + var node = ReactDOM.findDOMNode(this); + var commentNode = this.createComment(); + this.commentNode = commentNode; + this.currentNode = node; + this.parentNode = node.parentNode; + this.parentNode.replaceChild(commentNode, node); + ReactDOM.unmountComponentAtNode(node); + this.props.onLoaded(); + }; + ReactComment.prototype.componentWillUnmount = function () { + this.parentNode.replaceChild(this.currentNode, this.commentNode); + }; + ReactComment.prototype.createComment = function () { + var content = this.props.children; + if (typeof content !== 'string') { + content = ''; + } + this.content = content.trim(); + return document.createComment(this.content); + }; + ReactComment.prototype.render = function () { + return React.createElement("div", null); + }; + ReactComment.defaultProps = { + onLoaded: noop, + }; + return ReactComment; +}(React.PureComponent)); +export default ReactComment; diff --git a/es/components/Consumer.d.ts b/es/components/Consumer.d.ts new file mode 100644 index 0000000..dd7f92a --- /dev/null +++ b/es/components/Consumer.d.ts @@ -0,0 +1,20 @@ +import * as React from 'react'; +import { ICache, ICacheItem } from './Provider'; +interface IConsumerProps { + children: React.ReactNode; + identification: string; + keepAlive: boolean; + cache: ICache; + setCache: (identification: string, value: ICacheItem) => void; + unactivate: (identification: string) => void; +} +declare class Consumer extends React.PureComponent { + private renderElement; + private commentRef; + private identification; + componentDidMount(): void; + componentDidUpdate(): void; + componentWillUnmount(): void; + render(): JSX.Element; +} +export default Consumer; diff --git a/es/components/Consumer.js b/es/components/Consumer.js new file mode 100644 index 0000000..7ad54fc --- /dev/null +++ b/es/components/Consumer.js @@ -0,0 +1,54 @@ +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +import * as React from 'react'; +import Comment from './Comment'; +import { LIFECYCLE } from './Provider'; +var Consumer = /** @class */ (function (_super) { + __extends(Consumer, _super); + function Consumer() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.identification = _this.props.identification; + return _this; + } + Consumer.prototype.componentDidMount = function () { + var _a = this.props, setCache = _a.setCache, children = _a.children, keepAlive = _a.keepAlive; + this.renderElement = this.commentRef.parentNode; + setCache(this.identification, { + children: children, + keepAlive: keepAlive, + lifecycle: LIFECYCLE.MOUNTED, + renderElement: this.renderElement, + activated: true, + }); + }; + Consumer.prototype.componentDidUpdate = function () { + var _a = this.props, setCache = _a.setCache, children = _a.children, keepAlive = _a.keepAlive; + setCache(this.identification, { + children: children, + keepAlive: keepAlive, + lifecycle: LIFECYCLE.UPDATING, + }); + }; + Consumer.prototype.componentWillUnmount = function () { + var unactivate = this.props.unactivate; + unactivate(this.identification); + }; + Consumer.prototype.render = function () { + var _this = this; + var identification = this.identification; + return React.createElement(Comment, { ref: function (ref) { return _this.commentRef = ref; } }, identification); + }; + return Consumer; +}(React.PureComponent)); +export default Consumer; diff --git a/es/components/KeepAlive.d.ts b/es/components/KeepAlive.d.ts new file mode 100644 index 0000000..5089f20 --- /dev/null +++ b/es/components/KeepAlive.d.ts @@ -0,0 +1,9 @@ +import * as React from 'react'; +interface IKeepAliveProps { + key?: string; + name?: string; + disabled?: boolean; + extra?: any; +} +declare const _default: React.ComponentType; +export default _default; diff --git a/es/components/KeepAlive.js b/es/components/KeepAlive.js new file mode 100644 index 0000000..b25b364 --- /dev/null +++ b/es/components/KeepAlive.js @@ -0,0 +1,138 @@ +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +import * as React from 'react'; +import AsyncComponent from './AsyncComponent'; +import { START_MOUNTING_DOM, LIFECYCLE } from './Provider'; +import keepAlive, { COMMAND } from '../utils/keepAliveDecorator'; +import changePositionByComment from '../utils/changePositionByComment'; +var KeepAlive = /** @class */ (function (_super) { + __extends(KeepAlive, _super); + function KeepAlive() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.bindUnmount = null; + _this.bindUnactivate = null; + _this.unmounted = false; + _this.mounted = false; + _this.ref = null; + _this.refNextSibling = null; + _this.childNodes = []; + _this.correctionPosition = function () { + if (_this.ref && _this.ref.parentNode && _this.ref.nextSibling) { + var childNodes = _this.ref.childNodes; + _this.refNextSibling = _this.ref.nextSibling; + _this.childNodes = []; + while (childNodes.length) { + var child = childNodes[0]; + _this.childNodes.push(child); + _this.ref.parentNode.insertBefore(child, _this.ref.nextSibling); + } + _this.ref.parentNode.removeChild(_this.ref); + } + }; + _this.retreatPosition = function () { + if (_this.ref && _this.refNextSibling && _this.refNextSibling.parentNode) { + for (var _i = 0, _a = _this.childNodes; _i < _a.length; _i++) { + var child = _a[_i]; + _this.ref.appendChild(child); + } + _this.refNextSibling.parentNode.insertBefore(_this.ref, _this.refNextSibling); + } + }; + _this.setMounted = function (value) { + _this.mounted = value; + }; + _this.getMounted = function () { + return _this.mounted; + }; + return _this; + } + KeepAlive.prototype.componentDidMount = function () { + var _this = this; + var _container = this.props._container; + var notNeedActivate = _container.notNeedActivate, identification = _container.identification, eventEmitter = _container.eventEmitter, keepAlive = _container.keepAlive; + notNeedActivate(); + var cb = function () { + _this.mount(); + _this.listen(); + eventEmitter.off([identification, START_MOUNTING_DOM], cb); + }; + eventEmitter.on([identification, START_MOUNTING_DOM], cb); + if (keepAlive) { + this.componentDidActivate(); + } + }; + KeepAlive.prototype.componentDidActivate = function () { + // tslint-disable + }; + KeepAlive.prototype.componentDidUpdate = function () { + var _container = this.props._container; + var notNeedActivate = _container.notNeedActivate, isNeedActivate = _container.isNeedActivate; + if (isNeedActivate()) { + notNeedActivate(); + this.mount(); + this.listen(); + this.unmounted = false; + this.componentDidActivate(); + } + }; + KeepAlive.prototype.componentWillUnactivate = function () { + this.unmount(); + this.unlisten(); + }; + KeepAlive.prototype.componentWillUnmount = function () { + if (!this.unmounted) { + this.unmounted = true; + this.unmount(); + this.unlisten(); + } + }; + KeepAlive.prototype.mount = function () { + var _a = this.props._container, cache = _a.cache, identification = _a.identification, storeElement = _a.storeElement, setLifecycle = _a.setLifecycle; + this.setMounted(true); + var renderElement = cache[identification].renderElement; + setLifecycle(LIFECYCLE.UPDATING); + changePositionByComment(identification, renderElement, storeElement); + }; + KeepAlive.prototype.unmount = function () { + var _a = this.props._container, identification = _a.identification, storeElement = _a.storeElement, cache = _a.cache, setLifecycle = _a.setLifecycle; + if (cache[identification]) { + var _b = cache[identification], renderElement = _b.renderElement, ifStillActivate = _b.ifStillActivate, reactivate = _b.reactivate; + setLifecycle(LIFECYCLE.UNMOUNTED); + this.retreatPosition(); + changePositionByComment(identification, storeElement, renderElement); + if (ifStillActivate) { + reactivate(); + } + } + }; + KeepAlive.prototype.listen = function () { + var _a = this.props._container, identification = _a.identification, eventEmitter = _a.eventEmitter; + eventEmitter.on([identification, COMMAND.CURRENT_UNMOUNT], this.bindUnmount = this.componentWillUnmount.bind(this)); + eventEmitter.on([identification, COMMAND.CURRENT_UNACTIVATE], this.bindUnactivate = this.componentWillUnactivate.bind(this)); + }; + KeepAlive.prototype.unlisten = function () { + var _a = this.props._container, identification = _a.identification, eventEmitter = _a.eventEmitter; + eventEmitter.off([identification, COMMAND.CURRENT_UNMOUNT], this.bindUnmount); + eventEmitter.off([identification, COMMAND.CURRENT_UNACTIVATE], this.bindUnactivate); + }; + KeepAlive.prototype.render = function () { + var _this = this; + // The purpose of this div is to not report an error when moving the DOM, + // so you need to remove this div later. + return (React.createElement("div", { ref: function (ref) { return _this.ref = ref; } }, + React.createElement(AsyncComponent, { setMounted: this.setMounted, getMounted: this.getMounted, onUpdate: this.correctionPosition }, this.props.children))); + }; + return KeepAlive; +}(React.PureComponent)); +export default keepAlive(KeepAlive); diff --git a/es/components/Provider.d.ts b/es/components/Provider.d.ts new file mode 100644 index 0000000..7352d75 --- /dev/null +++ b/es/components/Provider.d.ts @@ -0,0 +1,66 @@ +import * as React from 'react'; +export declare const keepAliveProviderTypeName = "$$KeepAliveProvider"; +export declare const START_MOUNTING_DOM = "startMountingDOM"; +export declare enum LIFECYCLE { + MOUNTED = 0, + UPDATING = 1, + UNMOUNTED = 2 +} +export interface ICacheItem { + children: React.ReactNode; + keepAlive: boolean; + lifecycle: LIFECYCLE; + renderElement?: HTMLElement; + activated?: boolean; + ifStillActivate?: boolean; + reactivate?: () => void; +} +export interface ICache { + [key: string]: ICacheItem; +} +export interface IKeepAliveProviderImpl { + storeElement: HTMLElement; + cache: ICache; + keys: string[]; + eventEmitter: any; + existed: boolean; + providerIdentification: string; + setCache: (identification: string, value: ICacheItem) => void; + removeCache: (name: string) => void; + unactivate: (identification: string) => void; + isExisted: () => boolean; +} +export interface IKeepAliveProviderProps { + include?: string | string[] | RegExp; + exclude?: string | string[] | RegExp; + max?: number; +} +export default class KeepAliveProvider extends React.PureComponent implements IKeepAliveProviderImpl { + static displayName: string; + static defaultProps: { + max: number; + }; + storeElement: HTMLElement; + cache: ICache; + keys: string[]; + eventEmitter: { + on: (eventNames: string | string[], listener: (...args: any) => void, direction?: boolean) => void; + off: (eventNames: string | string[], listener: (...args: any) => void) => void; + emit: (eventNames: string | string[], ...args: any) => void; + clear: () => void; + listenerCount: (eventNames: string | string[]) => number; + removeAllListeners: (eventNames: string | string[]) => void; + }; + existed: boolean; + private needRerender; + providerIdentification: string; + componentDidMount(): void; + componentDidUpdate(): void; + componentWillUnmount(): void; + isExisted: () => boolean; + setCache: (identification: string, value: ICacheItem) => void; + removeCache: (name: string | string[]) => void; + unactivate: (identification: string) => void; + private startMountingDOM; + render(): JSX.Element | null; +} diff --git a/es/components/Provider.js b/es/components/Provider.js new file mode 100644 index 0000000..21a89a5 --- /dev/null +++ b/es/components/Provider.js @@ -0,0 +1,185 @@ +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import Comment from './Comment'; +import KeepAliveContext from '../contexts/KeepAliveContext'; +import createEventEmitter from '../utils/createEventEmitter'; +import createUniqueIdentification from '../utils/createUniqueIdentification'; +import createStoreElement from '../utils/createStoreElement'; +export var keepAliveProviderTypeName = '$$KeepAliveProvider'; +export var START_MOUNTING_DOM = 'startMountingDOM'; +export var LIFECYCLE; +(function (LIFECYCLE) { + LIFECYCLE[LIFECYCLE["MOUNTED"] = 0] = "MOUNTED"; + LIFECYCLE[LIFECYCLE["UPDATING"] = 1] = "UPDATING"; + LIFECYCLE[LIFECYCLE["UNMOUNTED"] = 2] = "UNMOUNTED"; +})(LIFECYCLE || (LIFECYCLE = {})); +var KeepAliveProvider = /** @class */ (function (_super) { + __extends(KeepAliveProvider, _super); + function KeepAliveProvider() { + var _this = _super !== null && _super.apply(this, arguments) || this; + // Sometimes data that changes with setState cannot be synchronized, so force refresh + _this.cache = Object.create(null); + _this.keys = []; + _this.eventEmitter = createEventEmitter(); + _this.existed = true; + _this.needRerender = false; + _this.providerIdentification = createUniqueIdentification(); + _this.isExisted = function () { + return _this.existed; + }; + _this.setCache = function (identification, value) { + var _a = _this, cache = _a.cache, keys = _a.keys; + var max = _this.props.max; + var currentCache = cache[identification]; + if (!currentCache) { + keys.push(identification); + } + _this.cache[identification] = __assign(__assign({}, currentCache), value); + _this.forceUpdate(function () { + // If the maximum value is set, the value in the cache is deleted after it goes out. + if (currentCache) { + return; + } + if (!max) { + return; + } + var difference = keys.length - max; + if (difference <= 0) { + return; + } + var spliceKeys = keys.splice(0, difference); + _this.forceUpdate(function () { + spliceKeys.forEach(function (key) { + delete cache[key]; + }); + }); + }); + }; + _this.removeCache = function (name) { + var _a = _this, cache = _a.cache, keys = _a.keys; + var needDeletedCacheKeys = []; + for (var key in cache) { + if (Object.prototype.hasOwnProperty.call(cache, key)) { + var keepAliveObject = cache[key]; + // if name is array, mutiple delete caches + if (Object.prototype.toString.call(name) === '[object Array]') { + if (name.indexOf(keepAliveObject.children._owner.key) > -1) { + needDeletedCacheKeys.push(key); + delete cache[key]; + } + } + else if (Object.prototype.toString.call(name) === '[object String]') { + if (name.indexOf(keepAliveObject.children._owner.key) > -1) { + needDeletedCacheKeys.push(key); + delete cache[key]; + } + } + else { + throw new Error("name can be only string or string array"); + } + } + } + _this.keys = keys.filter(function (key) { return needDeletedCacheKeys.indexOf(key) === -1; }); + _this.forceUpdate(); + }; + _this.unactivate = function (identification) { + var cache = _this.cache; + _this.cache[identification] = __assign(__assign({}, cache[identification]), { activated: false, lifecycle: LIFECYCLE.UNMOUNTED }); + _this.forceUpdate(); + }; + _this.startMountingDOM = function (identification) { + _this.eventEmitter.emit([identification, START_MOUNTING_DOM]); + }; + return _this; + } + KeepAliveProvider.prototype.componentDidMount = function () { + this.storeElement = createStoreElement(); + this.forceUpdate(); + }; + KeepAliveProvider.prototype.componentDidUpdate = function () { + if (this.needRerender) { + this.needRerender = false; + this.forceUpdate(); + } + }; + KeepAliveProvider.prototype.componentWillUnmount = function () { + this.existed = false; + document.body.removeChild(this.storeElement); + }; + KeepAliveProvider.prototype.render = function () { + var _this = this; + var _a = this, cache = _a.cache, keys = _a.keys, providerIdentification = _a.providerIdentification, isExisted = _a.isExisted, setCache = _a.setCache, removeCache = _a.removeCache, existed = _a.existed, unactivate = _a.unactivate, storeElement = _a.storeElement, eventEmitter = _a.eventEmitter; + var _b = this.props, innerChildren = _b.children, include = _b.include, exclude = _b.exclude; + if (!storeElement) { + return null; + } + return (React.createElement(KeepAliveContext.Provider, { value: { + cache: cache, + keys: keys, + existed: existed, + providerIdentification: providerIdentification, + isExisted: isExisted, + setCache: setCache, + removeCache: removeCache, + unactivate: unactivate, + storeElement: storeElement, + eventEmitter: eventEmitter, + include: include, + exclude: exclude, + } }, + React.createElement(React.Fragment, null, + innerChildren, + ReactDOM.createPortal(keys.map(function (identification) { + var currentCache = cache[identification]; + var keepAlive = currentCache.keepAlive, children = currentCache.children, lifecycle = currentCache.lifecycle; + var cacheChildren = children; + if (lifecycle === LIFECYCLE.MOUNTED && !keepAlive) { + // If the cache was last enabled, then the components of this keepAlive package are used, + // and the cache is not enabled, the UI needs to be reset. + cacheChildren = null; + _this.needRerender = true; + currentCache.lifecycle = LIFECYCLE.UPDATING; + } + // current true, previous true | undefined, keepAlive false, not cache + // current true, previous true | undefined, keepAlive true, cache + // current true, previous false, keepAlive true, cache + // current true, previous false, keepAlive false, not cache + return (cacheChildren + ? (React.createElement(React.Fragment, { key: identification }, + React.createElement(Comment, null, identification), + cacheChildren, + React.createElement(Comment, { onLoaded: function () { return _this.startMountingDOM(identification); } }, identification))) + : null); + }), storeElement)))); + }; + KeepAliveProvider.displayName = keepAliveProviderTypeName; + KeepAliveProvider.defaultProps = { + max: 10, + }; + return KeepAliveProvider; +}(React.PureComponent)); +export default KeepAliveProvider; diff --git a/es/contexts/IdentificationContext.d.ts b/es/contexts/IdentificationContext.d.ts new file mode 100644 index 0000000..b9bc7ed --- /dev/null +++ b/es/contexts/IdentificationContext.d.ts @@ -0,0 +1,12 @@ +import * as React from 'react'; +export interface IIdentificationContextProps { + identification: string; + eventEmitter: any; + keepAlive: boolean; + getLifecycle: () => number; + isExisted: () => boolean; + activated: boolean; + extra: any; +} +declare const WithKeepAliveContext: React.Context; +export default WithKeepAliveContext; diff --git a/es/contexts/IdentificationContext.js b/es/contexts/IdentificationContext.js new file mode 100644 index 0000000..322450a --- /dev/null +++ b/es/contexts/IdentificationContext.js @@ -0,0 +1,3 @@ +import * as React from 'react'; +var WithKeepAliveContext = React.createContext({}); +export default WithKeepAliveContext; diff --git a/es/contexts/KeepAliveContext.d.ts b/es/contexts/KeepAliveContext.d.ts new file mode 100644 index 0000000..86782fa --- /dev/null +++ b/es/contexts/KeepAliveContext.d.ts @@ -0,0 +1,5 @@ +import * as React from 'react'; +import { IKeepAliveProviderImpl, IKeepAliveProviderProps } from '../components/Provider'; +export declare type IKeepAliveContextProps = IKeepAliveProviderImpl & IKeepAliveProviderProps; +declare const KeepAliveContext: React.Context; +export default KeepAliveContext; diff --git a/es/contexts/KeepAliveContext.js b/es/contexts/KeepAliveContext.js new file mode 100644 index 0000000..68f94d9 --- /dev/null +++ b/es/contexts/KeepAliveContext.js @@ -0,0 +1,3 @@ +import * as React from 'react'; +var KeepAliveContext = React.createContext({}); +export default KeepAliveContext; diff --git a/es/index.d.ts b/es/index.d.ts new file mode 100644 index 0000000..281fce8 --- /dev/null +++ b/es/index.d.ts @@ -0,0 +1,5 @@ +import Provider from './components/Provider'; +import KeepAlive from './components/KeepAlive'; +import bindLifecycle from './utils/bindLifecycle'; +import useKeepAliveEffect from './utils/useKeepAliveEffect'; +export { Provider, KeepAlive, bindLifecycle, useKeepAliveEffect, }; diff --git a/es/index.js b/es/index.js new file mode 100644 index 0000000..281fce8 --- /dev/null +++ b/es/index.js @@ -0,0 +1,5 @@ +import Provider from './components/Provider'; +import KeepAlive from './components/KeepAlive'; +import bindLifecycle from './utils/bindLifecycle'; +import useKeepAliveEffect from './utils/useKeepAliveEffect'; +export { Provider, KeepAlive, bindLifecycle, useKeepAliveEffect, }; diff --git a/es/utils/bindLifecycle.d.ts b/es/utils/bindLifecycle.d.ts new file mode 100644 index 0000000..ce84025 --- /dev/null +++ b/es/utils/bindLifecycle.d.ts @@ -0,0 +1,3 @@ +import * as React from 'react'; +export declare const bindLifecycleTypeName = "$$bindLifecycle"; +export default function bindLifecycle

(Component: React.ComponentClass

): any; diff --git a/es/utils/bindLifecycle.js b/es/utils/bindLifecycle.js new file mode 100644 index 0000000..fdac12a --- /dev/null +++ b/es/utils/bindLifecycle.js @@ -0,0 +1,109 @@ +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +var __spreadArrays = (this && this.__spreadArrays) || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +}; +import * as React from 'react'; +import hoistNonReactStatics from 'hoist-non-react-statics'; +import noop from './noop'; +import { warn } from './debug'; +import { COMMAND } from './keepAliveDecorator'; +import withIdentificationContextConsumer from './withIdentificationContextConsumer'; +import getDisplayName from './getDisplayName'; +export var bindLifecycleTypeName = '$$bindLifecycle'; +export default function bindLifecycle(Component) { + var WrappedComponent = Component.WrappedComponent || Component.wrappedComponent || Component; + var _a = WrappedComponent.prototype, _b = _a.componentDidMount, componentDidMount = _b === void 0 ? noop : _b, _c = _a.componentDidUpdate, componentDidUpdate = _c === void 0 ? noop : _c, _d = _a.componentDidActivate, componentDidActivate = _d === void 0 ? noop : _d, _e = _a.componentWillUnactivate, componentWillUnactivate = _e === void 0 ? noop : _e, _f = _a.componentWillUnmount, componentWillUnmount = _f === void 0 ? noop : _f, _g = _a.shouldComponentUpdate, shouldComponentUpdate = _g === void 0 ? noop : _g; + WrappedComponent.prototype.componentDidMount = function () { + var _this = this; + componentDidMount.call(this); + this._needActivate = false; + var _a = this.props, _b = _a._container, identification = _b.identification, eventEmitter = _b.eventEmitter, activated = _b.activated, keepAlive = _a.keepAlive; + // Determine whether to execute the componentDidActivate life cycle of the current component based on the activation state of the KeepAlive components + if (!activated && keepAlive !== false) { + componentDidActivate.call(this); + } + eventEmitter.on([identification, COMMAND.ACTIVATE], this._bindActivate = function () { return _this._needActivate = true; }, true); + eventEmitter.on([identification, COMMAND.UNACTIVATE], this._bindUnactivate = function () { + componentWillUnactivate.call(_this); + _this._unmounted = false; + }, true); + eventEmitter.on([identification, COMMAND.UNMOUNT], this._bindUnmount = function () { + componentWillUnmount.call(_this); + _this._unmounted = true; + }, true); + }; + // In order to be able to re-update after transferring the DOM, we need to block the first update. + WrappedComponent.prototype.shouldComponentUpdate = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (this._needActivate) { + this.forceUpdate(); + return false; + } + return shouldComponentUpdate.call.apply(shouldComponentUpdate, __spreadArrays([this], args)) || true; + }; + WrappedComponent.prototype.componentDidUpdate = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + componentDidUpdate.call.apply(componentDidUpdate, __spreadArrays([this], args)); + if (this._needActivate) { + this._needActivate = false; + componentDidActivate.call(this); + } + }; + WrappedComponent.prototype.componentWillUnmount = function () { + if (!this._unmounted) { + componentWillUnmount.call(this); + } + var _a = this.props._container, identification = _a.identification, eventEmitter = _a.eventEmitter; + eventEmitter.off([identification, COMMAND.ACTIVATE], this._bindActivate); + eventEmitter.off([identification, COMMAND.UNACTIVATE], this._bindUnactivate); + eventEmitter.off([identification, COMMAND.UNMOUNT], this._bindUnmount); + }; + var BindLifecycleHOC = withIdentificationContextConsumer(function (_a) { + var forwardRef = _a.forwardRef, _b = _a._identificationContextProps, identification = _b.identification, eventEmitter = _b.eventEmitter, activated = _b.activated, keepAlive = _b.keepAlive, extra = _b.extra, wrapperProps = __rest(_a, ["forwardRef", "_identificationContextProps"]); + if (!identification) { + warn('[React Keep Alive] You should not use bindLifecycle outside a .'); + return null; + } + return (React.createElement(Component, __assign({}, extra, wrapperProps, { ref: forwardRef || noop, _container: { + identification: identification, + eventEmitter: eventEmitter, + activated: activated, + keepAlive: keepAlive, + } }))); + }); + var BindLifecycle = React.forwardRef(function (props, ref) { return (React.createElement(BindLifecycleHOC, __assign({}, props, { forwardRef: ref }))); }); + BindLifecycle.WrappedComponent = WrappedComponent; + BindLifecycle.displayName = bindLifecycleTypeName + "(" + getDisplayName(Component) + ")"; + return hoistNonReactStatics(BindLifecycle, Component); +} diff --git a/es/utils/changePositionByComment.d.ts b/es/utils/changePositionByComment.d.ts new file mode 100644 index 0000000..2168288 --- /dev/null +++ b/es/utils/changePositionByComment.d.ts @@ -0,0 +1 @@ +export default function changePositionByComment(identification: string, presentParentNode: Node, originalParentNode: Node): void; diff --git a/es/utils/changePositionByComment.js b/es/utils/changePositionByComment.js new file mode 100644 index 0000000..95f16fd --- /dev/null +++ b/es/utils/changePositionByComment.js @@ -0,0 +1,52 @@ +var NODE_TYPES; +(function (NODE_TYPES) { + NODE_TYPES[NODE_TYPES["ELEMENT"] = 1] = "ELEMENT"; + NODE_TYPES[NODE_TYPES["COMMENT"] = 8] = "COMMENT"; +})(NODE_TYPES || (NODE_TYPES = {})); +function findElementsBetweenComments(node, identification) { + var elements = []; + var childNodes = node.childNodes; + var startCommentExist = false; + for (var _i = 0, childNodes_1 = childNodes; _i < childNodes_1.length; _i++) { + var child = childNodes_1[_i]; + if (child.nodeType === NODE_TYPES.COMMENT && + child.nodeValue.trim() === identification && + !startCommentExist) { + startCommentExist = true; + } + else if (startCommentExist && child.nodeType === NODE_TYPES.ELEMENT) { + elements.push(child); + } + else if (child.nodeType === NODE_TYPES.COMMENT && startCommentExist) { + return elements; + } + } + return elements; +} +function findComment(node, identification) { + var childNodes = node.childNodes; + for (var _i = 0, childNodes_2 = childNodes; _i < childNodes_2.length; _i++) { + var child = childNodes_2[_i]; + if (child.nodeType === NODE_TYPES.COMMENT && + child.nodeValue.trim() === identification) { + return child; + } + } +} +export default function changePositionByComment(identification, presentParentNode, originalParentNode) { + if (!presentParentNode || !originalParentNode) { + return; + } + var elementNodes = findElementsBetweenComments(originalParentNode, identification); + var commentNode = findComment(presentParentNode, identification); + if (!elementNodes.length || !commentNode) { + return; + } + elementNodes.push(elementNodes[elementNodes.length - 1].nextSibling); + elementNodes.unshift(elementNodes[0].previousSibling); + // Deleting comment elements when using commet components will result in component uninstallation errors + for (var i = elementNodes.length - 1; i >= 0; i--) { + presentParentNode.insertBefore(elementNodes[i], commentNode); + } + originalParentNode.appendChild(commentNode); +} diff --git a/es/utils/createEventEmitter.d.ts b/es/utils/createEventEmitter.d.ts new file mode 100644 index 0000000..48b8a0c --- /dev/null +++ b/es/utils/createEventEmitter.d.ts @@ -0,0 +1,11 @@ +declare type EventNames = string | string[]; +declare type Listener = (...args: any) => void; +export default function createEventEmitter(): { + on: (eventNames: EventNames, listener: Listener, direction?: boolean) => void; + off: (eventNames: EventNames, listener: Listener) => void; + emit: (eventNames: EventNames, ...args: any) => void; + clear: () => void; + listenerCount: (eventNames: EventNames) => number; + removeAllListeners: (eventNames: EventNames) => void; +}; +export {}; diff --git a/es/utils/createEventEmitter.js b/es/utils/createEventEmitter.js new file mode 100644 index 0000000..09409a0 --- /dev/null +++ b/es/utils/createEventEmitter.js @@ -0,0 +1,97 @@ +import { warn } from './debug'; +export default function createEventEmitter() { + var events = Object.create(null); + function on(eventNames, listener, direction) { + if (direction === void 0) { direction = false; } + eventNames = getEventNames(eventNames); + var current = events; + var maxIndex = eventNames.length - 1; + for (var i = 0; i < eventNames.length; i++) { + var key = eventNames[i]; + if (!current[key]) { + current[key] = i === maxIndex ? [] : {}; + } + current = current[key]; + } + if (!Array.isArray(current)) { + warn('[React Keep Alive] Access path error.'); + } + if (direction) { + current.unshift(listener); + } + else { + current.push(listener); + } + } + function off(eventNames, listener) { + var listeners = getListeners(eventNames); + if (!listeners) { + return; + } + var matchIndex = listeners.findIndex(function (v) { return v === listener; }); + if (matchIndex !== -1) { + listeners.splice(matchIndex, 1); + } + } + function removeAllListeners(eventNames) { + var listeners = getListeners(eventNames); + if (!listeners) { + return; + } + eventNames = getEventNames(eventNames); + var lastEventName = eventNames.pop(); + if (lastEventName) { + var event_1 = eventNames.reduce(function (obj, key) { return obj[key]; }, events); + event_1[lastEventName] = []; + } + } + function emit(eventNames) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var listeners = getListeners(eventNames); + if (!listeners) { + return; + } + for (var _a = 0, listeners_1 = listeners; _a < listeners_1.length; _a++) { + var listener = listeners_1[_a]; + if (listener) { + listener.apply(void 0, args); + } + } + } + function listenerCount(eventNames) { + var listeners = getListeners(eventNames); + return listeners ? listeners.length : 0; + } + function clear() { + events = Object.create(null); + } + function getListeners(eventNames) { + eventNames = getEventNames(eventNames); + try { + return eventNames.reduce(function (obj, key) { return obj[key]; }, events); + } + catch (e) { + return; + } + } + function getEventNames(eventNames) { + if (!eventNames) { + warn('[React Keep Alive] Must exist event name.'); + } + if (typeof eventNames === 'string') { + eventNames = [eventNames]; + } + return eventNames; + } + return { + on: on, + off: off, + emit: emit, + clear: clear, + listenerCount: listenerCount, + removeAllListeners: removeAllListeners, + }; +} diff --git a/es/utils/createStoreElement.d.ts b/es/utils/createStoreElement.d.ts new file mode 100644 index 0000000..1586ec3 --- /dev/null +++ b/es/utils/createStoreElement.d.ts @@ -0,0 +1 @@ +export default function createStoreElement(): HTMLElement; diff --git a/es/utils/createStoreElement.js b/es/utils/createStoreElement.js new file mode 100644 index 0000000..9f4a8ce --- /dev/null +++ b/es/utils/createStoreElement.js @@ -0,0 +1,8 @@ +import { prefix } from './createUniqueIdentification'; +export default function createStoreElement() { + var keepAliveDOM = document.createElement('div'); + keepAliveDOM.dataset.type = prefix; + keepAliveDOM.style.display = 'none'; + document.body.appendChild(keepAliveDOM); + return keepAliveDOM; +} diff --git a/es/utils/createUniqueIdentification.d.ts b/es/utils/createUniqueIdentification.d.ts new file mode 100644 index 0000000..1b9035c --- /dev/null +++ b/es/utils/createUniqueIdentification.d.ts @@ -0,0 +1,8 @@ +export declare const prefix = "keep-alive"; +/** + * Create UUID + * Reference: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript + * @export + * @returns + */ +export default function createUniqueIdentification(length?: number): string; diff --git a/es/utils/createUniqueIdentification.js b/es/utils/createUniqueIdentification.js new file mode 100644 index 0000000..10d0907 --- /dev/null +++ b/es/utils/createUniqueIdentification.js @@ -0,0 +1,16 @@ +var hexDigits = '0123456789abcdef'; +export var prefix = 'keep-alive'; +/** + * Create UUID + * Reference: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript + * @export + * @returns + */ +export default function createUniqueIdentification(length) { + if (length === void 0) { length = 6; } + var strings = []; + for (var i = 0; i < length; i++) { + strings[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); + } + return prefix + "-" + strings.join(''); +} diff --git a/es/utils/debug.d.ts b/es/utils/debug.d.ts new file mode 100644 index 0000000..19bfe26 --- /dev/null +++ b/es/utils/debug.d.ts @@ -0,0 +1,3 @@ +declare type Warn = (message?: string) => void; +export declare let warn: Warn; +export {}; diff --git a/es/utils/debug.js b/es/utils/debug.js new file mode 100644 index 0000000..618adf7 --- /dev/null +++ b/es/utils/debug.js @@ -0,0 +1,16 @@ +export var warn = function () { return undefined; }; +if (process.env.NODE_ENV !== 'production') { + /** + * Prints a warning in the console if it exists. + * + * @param {*} message + */ + warn = function (message) { + if (typeof console !== undefined && typeof console.error === 'function') { + console.error(message); + } + else { + throw new Error(message); + } + }; +} diff --git a/es/utils/getDisplayName.d.ts b/es/utils/getDisplayName.d.ts new file mode 100644 index 0000000..1bfafad --- /dev/null +++ b/es/utils/getDisplayName.d.ts @@ -0,0 +1,2 @@ +import * as React from 'react'; +export default function getDisplayName(Component: React.ComponentType): string; diff --git a/es/utils/getDisplayName.js b/es/utils/getDisplayName.js new file mode 100644 index 0000000..c526a57 --- /dev/null +++ b/es/utils/getDisplayName.js @@ -0,0 +1,3 @@ +export default function getDisplayName(Component) { + return Component.displayName || Component.name || 'Component'; +} diff --git a/es/utils/getKeepAlive.d.ts b/es/utils/getKeepAlive.d.ts new file mode 100644 index 0000000..94d9505 --- /dev/null +++ b/es/utils/getKeepAlive.d.ts @@ -0,0 +1,3 @@ +declare type Pattern = string | string[] | RegExp; +export default function getKeepAlive(name: string, include?: Pattern, exclude?: Pattern, disabled?: boolean): boolean; +export {}; diff --git a/es/utils/getKeepAlive.js b/es/utils/getKeepAlive.js new file mode 100644 index 0000000..db24a28 --- /dev/null +++ b/es/utils/getKeepAlive.js @@ -0,0 +1,23 @@ +import isRegExp from './isRegExp'; +function matches(pattern, name) { + if (Array.isArray(pattern)) { + return pattern.indexOf(name) > -1; + } + else if (typeof pattern === 'string') { + return pattern.split(',').indexOf(name) > -1; + } + else if (isRegExp(pattern)) { + return pattern.test(name); + } + return false; +} +export default function getKeepAlive(name, include, exclude, disabled) { + if (disabled !== undefined) { + return !disabled; + } + if ((include && (!name || !matches(include, name))) || + (exclude && name && matches(exclude, name))) { + return false; + } + return true; +} diff --git a/es/utils/getKeyByFiberNode.d.ts b/es/utils/getKeyByFiberNode.d.ts new file mode 100644 index 0000000..8ddecb0 --- /dev/null +++ b/es/utils/getKeyByFiberNode.d.ts @@ -0,0 +1 @@ +export default function getKeyByFiberNode(fiberNode: any): string | null; diff --git a/es/utils/getKeyByFiberNode.js b/es/utils/getKeyByFiberNode.js new file mode 100644 index 0000000..7960bba --- /dev/null +++ b/es/utils/getKeyByFiberNode.js @@ -0,0 +1,11 @@ +import { WithKeepAliveContextConsumerDisplayName } from './withKeepAliveContextConsumer'; +export default function getKeyByFiberNode(fiberNode) { + if (!fiberNode) { + return null; + } + var key = fiberNode.key, type = fiberNode.type; + if (type.displayName && type.displayName.indexOf(WithKeepAliveContextConsumerDisplayName) !== -1) { + return key; + } + return getKeyByFiberNode(fiberNode.return); +} diff --git a/es/utils/isRegExp.d.ts b/es/utils/isRegExp.d.ts new file mode 100644 index 0000000..a9efce0 --- /dev/null +++ b/es/utils/isRegExp.d.ts @@ -0,0 +1 @@ +export default function isRegExp(value: RegExp): boolean; diff --git a/es/utils/isRegExp.js b/es/utils/isRegExp.js new file mode 100644 index 0000000..dcb3949 --- /dev/null +++ b/es/utils/isRegExp.js @@ -0,0 +1,3 @@ +export default function isRegExp(value) { + return value && Object.prototype.toString.call(value) === '[object RegExp]'; +} diff --git a/es/utils/keepAliveDecorator.d.ts b/es/utils/keepAliveDecorator.d.ts new file mode 100644 index 0000000..d5af014 --- /dev/null +++ b/es/utils/keepAliveDecorator.d.ts @@ -0,0 +1,17 @@ +import * as React from 'react'; +export declare enum COMMAND { + UNACTIVATE = "unactivate", + UNMOUNT = "unmount", + ACTIVATE = "activate", + CURRENT_UNMOUNT = "current_unmount", + CURRENT_UNACTIVATE = "current_unactivate" +} +/** + * Decorating the component, the main function is to listen to events emitted by the upper component, triggering events of the current component. + * + * @export + * @template P + * @param {React.ComponentType} Component + * @returns {React.ComponentType

} + */ +export default function keepAliveDecorator

(Component: React.ComponentType): React.ComponentType

; diff --git a/es/utils/keepAliveDecorator.js b/es/utils/keepAliveDecorator.js new file mode 100644 index 0000000..305f5ba --- /dev/null +++ b/es/utils/keepAliveDecorator.js @@ -0,0 +1,255 @@ +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +var __spreadArrays = (this && this.__spreadArrays) || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +}; +import * as React from 'react'; +import hoistNonReactStatics from 'hoist-non-react-statics'; +import IdentificationContext from '../contexts/IdentificationContext'; +import Consumer from '../components/Consumer'; +import { LIFECYCLE } from '../components/Provider'; +import md5 from './md5'; +import { warn } from './debug'; +import getKeyByFiberNode from './getKeyByFiberNode'; +import withIdentificationContextConsumer from './withIdentificationContextConsumer'; +import withKeepAliveContextConsumer from './withKeepAliveContextConsumer'; +import shallowEqual from './shallowEqual'; +import getKeepAlive from './getKeepAlive'; +export var COMMAND; +(function (COMMAND) { + COMMAND["UNACTIVATE"] = "unactivate"; + COMMAND["UNMOUNT"] = "unmount"; + COMMAND["ACTIVATE"] = "activate"; + COMMAND["CURRENT_UNMOUNT"] = "current_unmount"; + COMMAND["CURRENT_UNACTIVATE"] = "current_unactivate"; +})(COMMAND || (COMMAND = {})); +/** + * Decorating the component, the main function is to listen to events emitted by the upper component, triggering events of the current component. + * + * @export + * @template P + * @param {React.ComponentType} Component + * @returns {React.ComponentType

} + */ +export default function keepAliveDecorator(Component) { + var TriggerLifecycleContainer = /** @class */ (function (_super) { + __extends(TriggerLifecycleContainer, _super); + function TriggerLifecycleContainer(props) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var _this = _super.apply(this, __spreadArrays([props], args)) || this; + _this.activated = false; + _this.ifStillActivate = false; + // Let the lifecycle of the cached component be called normally. + _this.needActivate = true; + _this.lifecycle = LIFECYCLE.MOUNTED; + _this.activate = function () { + _this.activated = true; + }; + _this.reactivate = function () { + _this.ifStillActivate = false; + _this.forceUpdate(); + }; + _this.isNeedActivate = function () { + return _this.needActivate; + }; + _this.notNeedActivate = function () { + _this.needActivate = false; + }; + _this.getLifecycle = function () { + return _this.lifecycle; + }; + _this.setLifecycle = function (lifecycle) { + _this.lifecycle = lifecycle; + }; + var cache = props._keepAliveContextProps.cache; + if (!cache) { + warn('[React Keep Alive] You should not use outside a .'); + } + return _this; + } + TriggerLifecycleContainer.prototype.componentDidMount = function () { + if (!this.ifStillActivate) { + this.activate(); + } + var _a = this.props, keepAlive = _a.keepAlive, eventEmitter = _a._keepAliveContextProps.eventEmitter; + if (keepAlive) { + this.needActivate = true; + eventEmitter.emit([this.identification, COMMAND.ACTIVATE]); + } + }; + TriggerLifecycleContainer.prototype.componentDidCatch = function () { + if (!this.activated) { + this.activate(); + } + }; + TriggerLifecycleContainer.prototype.componentWillUnmount = function () { + var _a = this.props, getCombinedKeepAlive = _a.getCombinedKeepAlive, _b = _a._keepAliveContextProps, eventEmitter = _b.eventEmitter, isExisted = _b.isExisted; + var keepAlive = getCombinedKeepAlive(); + if (!keepAlive || !isExisted()) { + eventEmitter.emit([this.identification, COMMAND.CURRENT_UNMOUNT]); + eventEmitter.emit([this.identification, COMMAND.UNMOUNT]); + } + // When the Provider components are unmounted, the cache is not needed, + // so you don't have to execute the componentWillUnactivate lifecycle. + if (keepAlive && isExisted()) { + eventEmitter.emit([this.identification, COMMAND.CURRENT_UNACTIVATE]); + eventEmitter.emit([this.identification, COMMAND.UNACTIVATE]); + } + }; + TriggerLifecycleContainer.prototype.render = function () { + var _a = this.props, propKey = _a.propKey, keepAlive = _a.keepAlive, extra = _a.extra, getCombinedKeepAlive = _a.getCombinedKeepAlive, _b = _a._keepAliveContextProps, isExisted = _b.isExisted, storeElement = _b.storeElement, cache = _b.cache, eventEmitter = _b.eventEmitter, setCache = _b.setCache, unactivate = _b.unactivate, providerIdentification = _b.providerIdentification, wrapperProps = __rest(_a, ["propKey", "keepAlive", "extra", "getCombinedKeepAlive", "_keepAliveContextProps"]); + if (!this.identification) { + // We need to generate a corresponding unique identifier based on the information of the component. + this.identification = md5("" + providerIdentification + propKey); + // The last activated component must be unactivated before it can be activated again. + var currentCache = cache[this.identification]; + if (currentCache) { + this.ifStillActivate = currentCache.activated; + currentCache.ifStillActivate = this.ifStillActivate; + currentCache.reactivate = this.reactivate; + } + } + var _c = this, isNeedActivate = _c.isNeedActivate, notNeedActivate = _c.notNeedActivate, activated = _c.activated, getLifecycle = _c.getLifecycle, setLifecycle = _c.setLifecycle, identification = _c.identification, ifStillActivate = _c.ifStillActivate; + return !ifStillActivate + ? (React.createElement(Consumer, { identification: identification, keepAlive: keepAlive, cache: cache, setCache: setCache, unactivate: unactivate }, + React.createElement(IdentificationContext.Provider, { value: { + identification: identification, + eventEmitter: eventEmitter, + keepAlive: keepAlive, + activated: activated, + getLifecycle: getLifecycle, + isExisted: isExisted, + extra: extra, + } }, + React.createElement(Component, __assign({}, wrapperProps, { _container: { + isNeedActivate: isNeedActivate, + notNeedActivate: notNeedActivate, + setLifecycle: setLifecycle, + eventEmitter: eventEmitter, + identification: identification, + storeElement: storeElement, + keepAlive: keepAlive, + cache: cache, + } }))))) + : null; + }; + return TriggerLifecycleContainer; + }(React.PureComponent)); + var ListenUpperKeepAliveContainer = /** @class */ (function (_super) { + __extends(ListenUpperKeepAliveContainer, _super); + function ListenUpperKeepAliveContainer() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.state = { + activated: true, + }; + _this.getCombinedKeepAlive = function () { + return _this.combinedKeepAlive; + }; + return _this; + } + ListenUpperKeepAliveContainer.prototype.shouldComponentUpdate = function (nextProps, nextState) { + if (this.state.activated !== nextState.activated) { + return true; + } + var _a = this.props, _keepAliveContextProps = _a._keepAliveContextProps, _identificationContextProps = _a._identificationContextProps, rest = __rest(_a, ["_keepAliveContextProps", "_identificationContextProps"]); + var nextKeepAliveContextProps = nextProps._keepAliveContextProps, nextIdentificationContextProps = nextProps._identificationContextProps, nextRest = __rest(nextProps, ["_keepAliveContextProps", "_identificationContextProps"]); + if (!shallowEqual(rest, nextRest)) { + return true; + } + if (!shallowEqual(_keepAliveContextProps, nextKeepAliveContextProps) || + !shallowEqual(_identificationContextProps, nextIdentificationContextProps)) { + return true; + } + return false; + }; + ListenUpperKeepAliveContainer.prototype.componentDidMount = function () { + this.listenUpperKeepAlive(); + }; + ListenUpperKeepAliveContainer.prototype.componentWillUnmount = function () { + this.unlistenUpperKeepAlive(); + }; + ListenUpperKeepAliveContainer.prototype.listenUpperKeepAlive = function () { + var _this = this; + var _a = this.props._identificationContextProps, identification = _a.identification, eventEmitter = _a.eventEmitter; + if (!identification) { + return; + } + eventEmitter.on([identification, COMMAND.ACTIVATE], this.activate = function () { return _this.setState({ activated: true }); }, true); + eventEmitter.on([identification, COMMAND.UNACTIVATE], this.unactivate = function () { return _this.setState({ activated: false }); }, true); + eventEmitter.on([identification, COMMAND.UNMOUNT], this.unmount = function () { return _this.setState({ activated: false }); }, true); + }; + ListenUpperKeepAliveContainer.prototype.unlistenUpperKeepAlive = function () { + var _a = this.props._identificationContextProps, identification = _a.identification, eventEmitter = _a.eventEmitter; + if (!identification) { + return; + } + eventEmitter.off([identification, COMMAND.ACTIVATE], this.activate); + eventEmitter.off([identification, COMMAND.UNACTIVATE], this.unactivate); + eventEmitter.off([identification, COMMAND.UNMOUNT], this.unmount); + }; + ListenUpperKeepAliveContainer.prototype.render = function () { + var _a = this.props, _b = _a._identificationContextProps, identification = _b.identification, upperKeepAlive = _b.keepAlive, getLifecycle = _b.getLifecycle, disabled = _a.disabled, name = _a.name, wrapperProps = __rest(_a, ["_identificationContextProps", "disabled", "name"]); + var activated = this.state.activated; + var _c = wrapperProps._keepAliveContextProps, include = _c.include, exclude = _c.exclude; + // When the parent KeepAlive component is mounted or unmounted, + // use the keepAlive prop of the parent KeepAlive component. + var propKey = name || getKeyByFiberNode(this._reactInternalFiber); + if (!propKey) { + warn('[React Keep Alive] components must have key or name.'); + return null; + } + var newKeepAlive = getKeepAlive(propKey, include, exclude, disabled); + this.combinedKeepAlive = getLifecycle === undefined || getLifecycle() === LIFECYCLE.UPDATING + ? newKeepAlive + : identification + ? upperKeepAlive && newKeepAlive + : newKeepAlive; + return activated + ? (React.createElement(TriggerLifecycleContainer, __assign({}, wrapperProps, { key: propKey, propKey: propKey, keepAlive: this.combinedKeepAlive, getCombinedKeepAlive: this.getCombinedKeepAlive }))) + : null; + }; + return ListenUpperKeepAliveContainer; + }(React.Component)); + var KeepAlive = withKeepAliveContextConsumer(withIdentificationContextConsumer(ListenUpperKeepAliveContainer)); + return hoistNonReactStatics(KeepAlive, Component); +} diff --git a/es/utils/md5.d.ts b/es/utils/md5.d.ts new file mode 100644 index 0000000..2bc3f1f --- /dev/null +++ b/es/utils/md5.d.ts @@ -0,0 +1 @@ +export default function createMD5(value?: string, length?: number): string; diff --git a/es/utils/md5.js b/es/utils/md5.js new file mode 100644 index 0000000..1660d13 --- /dev/null +++ b/es/utils/md5.js @@ -0,0 +1,7 @@ +import md5 from 'js-md5'; +import { prefix } from './createUniqueIdentification'; +export default function createMD5(value, length) { + if (value === void 0) { value = ''; } + if (length === void 0) { length = 6; } + return prefix + "-" + md5(value).substr(0, length); +} diff --git a/es/utils/noop.d.ts b/es/utils/noop.d.ts new file mode 100644 index 0000000..235cf5f --- /dev/null +++ b/es/utils/noop.d.ts @@ -0,0 +1,2 @@ +declare const noop: () => undefined; +export default noop; diff --git a/es/utils/noop.js b/es/utils/noop.js new file mode 100644 index 0000000..7282f2e --- /dev/null +++ b/es/utils/noop.js @@ -0,0 +1,2 @@ +var noop = function () { return undefined; }; +export default noop; diff --git a/es/utils/shallowEqual.d.ts b/es/utils/shallowEqual.d.ts new file mode 100644 index 0000000..7b448a3 --- /dev/null +++ b/es/utils/shallowEqual.d.ts @@ -0,0 +1,2 @@ +declare function shallowEqual(objA: object, objB: object): boolean; +export default shallowEqual; diff --git a/es/utils/shallowEqual.js b/es/utils/shallowEqual.js new file mode 100644 index 0000000..7063731 --- /dev/null +++ b/es/utils/shallowEqual.js @@ -0,0 +1,34 @@ +/** + * From react + */ +function is(x, y) { + return ((x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare + ); +} +var hasOwnProperty = Object.prototype.hasOwnProperty; +function shallowEqual(objA, objB) { + if (is(objA, objB)) { + return true; + } + if (typeof objA !== 'object' || + objA === null || + typeof objB !== 'object' || + objB === null) { + return false; + } + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + if (keysA.length !== keysB.length) { + return false; + } + // Test for A's keys different from B. + for (var _i = 0, keysA_1 = keysA; _i < keysA_1.length; _i++) { + var key = keysA_1[_i]; + if (!hasOwnProperty.call(objB, key) || + !is(objA[key], objB[key])) { + return false; + } + } + return true; +} +export default shallowEqual; diff --git a/es/utils/useKeepAliveEffect.d.ts b/es/utils/useKeepAliveEffect.d.ts new file mode 100644 index 0000000..9b203d3 --- /dev/null +++ b/es/utils/useKeepAliveEffect.d.ts @@ -0,0 +1,2 @@ +import React from 'react'; +export default function useKeepAliveEffect(effect: React.EffectCallback): void; diff --git a/es/utils/useKeepAliveEffect.js b/es/utils/useKeepAliveEffect.js new file mode 100644 index 0000000..1418a01 --- /dev/null +++ b/es/utils/useKeepAliveEffect.js @@ -0,0 +1,46 @@ +import { useEffect, useContext, useRef } from 'react'; +import { warn } from './debug'; +import { COMMAND } from './keepAliveDecorator'; +import IdentificationContext from '../contexts/IdentificationContext'; +export default function useKeepAliveEffect(effect) { + if (!useEffect) { + warn('[React Keep Alive] useKeepAliveEffect API requires react 16.8 or later.'); + } + var _a = useContext(IdentificationContext), eventEmitter = _a.eventEmitter, identification = _a.identification; + var effectRef = useRef(effect); + effectRef.current = effect; + useEffect(function () { + var bindActivate = null; + var bindUnactivate = null; + var bindUnmount = null; + var effectResult = effectRef.current(); + var unmounted = false; + eventEmitter.on([identification, COMMAND.ACTIVATE], bindActivate = function () { + // Delayed update + Promise.resolve().then(function () { + effectResult = effectRef.current(); + }); + unmounted = false; + }, true); + eventEmitter.on([identification, COMMAND.UNACTIVATE], bindUnactivate = function () { + if (effectResult) { + effectResult(); + unmounted = true; + } + }, true); + eventEmitter.on([identification, COMMAND.UNMOUNT], bindUnmount = function () { + if (effectResult) { + effectResult(); + unmounted = true; + } + }, true); + return function () { + if (effectResult && !unmounted) { + effectResult(); + } + eventEmitter.off([identification, COMMAND.ACTIVATE], bindActivate); + eventEmitter.off([identification, COMMAND.UNACTIVATE], bindUnactivate); + eventEmitter.off([identification, COMMAND.UNMOUNT], bindUnmount); + }; + }, []); +} diff --git a/es/utils/withIdentificationContextConsumer.d.ts b/es/utils/withIdentificationContextConsumer.d.ts new file mode 100644 index 0000000..5fd31a6 --- /dev/null +++ b/es/utils/withIdentificationContextConsumer.d.ts @@ -0,0 +1,10 @@ +import * as React from 'react'; +import { IIdentificationContextProps } from '../contexts/IdentificationContext'; +export interface IIdentificationContextConsumerComponentProps { + _identificationContextProps: IIdentificationContextProps; +} +export declare const withIdentificationContextConsumerDisplayName = "withIdentificationContextConsumer"; +export default function withIdentificationContextConsumer

(Component: React.ComponentType): { + (props: P): JSX.Element; + displayName: string; +}; diff --git a/es/utils/withIdentificationContextConsumer.js b/es/utils/withIdentificationContextConsumer.js new file mode 100644 index 0000000..5de05cb --- /dev/null +++ b/es/utils/withIdentificationContextConsumer.js @@ -0,0 +1,20 @@ +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +import * as React from 'react'; +import IdentificationContext from '../contexts/IdentificationContext'; +import getDisplayName from './getDisplayName'; +export var withIdentificationContextConsumerDisplayName = 'withIdentificationContextConsumer'; +export default function withIdentificationContextConsumer(Component) { + var WithIdentificationContextConsumer = function (props) { return (React.createElement(IdentificationContext.Consumer, null, function (contextProps) { return React.createElement(Component, __assign({ _identificationContextProps: contextProps }, props)); })); }; + WithIdentificationContextConsumer.displayName = withIdentificationContextConsumerDisplayName + "(" + getDisplayName(Component) + ")"; + return WithIdentificationContextConsumer; +} diff --git a/es/utils/withKeepAliveContextConsumer.d.ts b/es/utils/withKeepAliveContextConsumer.d.ts new file mode 100644 index 0000000..ade1441 --- /dev/null +++ b/es/utils/withKeepAliveContextConsumer.d.ts @@ -0,0 +1,10 @@ +import * as React from 'react'; +import { IKeepAliveContextProps } from '../contexts/KeepAliveContext'; +export interface IKeepAliveContextConsumerComponentProps { + _keepAliveContextProps: IKeepAliveContextProps; +} +export declare const WithKeepAliveContextConsumerDisplayName = "withKeepAliveContextConsumer"; +export default function withKeepAliveContextConsumer

(Component: React.ComponentType): { + (props: P): JSX.Element; + displayName: string; +}; diff --git a/es/utils/withKeepAliveContextConsumer.js b/es/utils/withKeepAliveContextConsumer.js new file mode 100644 index 0000000..a075070 --- /dev/null +++ b/es/utils/withKeepAliveContextConsumer.js @@ -0,0 +1,20 @@ +var __assign = (this && this.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +import * as React from 'react'; +import KeepAliveContext from '../contexts/KeepAliveContext'; +import getDisplayName from './getDisplayName'; +export var WithKeepAliveContextConsumerDisplayName = 'withKeepAliveContextConsumer'; +export default function withKeepAliveContextConsumer(Component) { + var WithKeepAliveContextConsumer = function (props) { return (React.createElement(KeepAliveContext.Consumer, null, function (contextProps) { return React.createElement(Component, __assign({ _keepAliveContextProps: contextProps }, props)); })); }; + WithKeepAliveContextConsumer.displayName = WithKeepAliveContextConsumerDisplayName + "(" + getDisplayName(Component) + ")"; + return WithKeepAliveContextConsumer; +} From 5a22f2a052eddeb5c834cdf8c5b95cb0817232d0 Mon Sep 17 00:00:00 2001 From: kavience <599513860@qq.com> Date: Mon, 12 Oct 2020 10:50:11 +0800 Subject: [PATCH 3/5] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E7=BC=93=E5=AD=98=E4=B8=8D=E5=B9=B2=E5=87=80=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cjs/components/Provider.js | 7 + demo/build/index.html | 11 + demo/build/static/index.js | 38051 +++++++++++++++++++++++++++++++ demo/build/static/index.js.map | 1 + es/components/Provider.js | 7 + src/components/Provider.tsx | 7 + 6 files changed, 38084 insertions(+) create mode 100644 demo/build/index.html create mode 100644 demo/build/static/index.js create mode 100644 demo/build/static/index.js.map diff --git a/cjs/components/Provider.js b/cjs/components/Provider.js index c5bb5c0..66ae96a 100644 --- a/cjs/components/Provider.js +++ b/cjs/components/Provider.js @@ -84,6 +84,13 @@ var KeepAliveProvider = /** @class */ (function (_super) { keys.push(identification); } _this.cache[identification] = __assign(__assign({}, currentCache), value); + for (var key in cache) { + if (Object.prototype.hasOwnProperty.call(cache, key)) { + if (keys.indexOf(key) === -1) { + delete cache[key]; + } + } + } _this.forceUpdate(function () { // If the maximum value is set, the value in the cache is deleted after it goes out. if (currentCache) { diff --git a/demo/build/index.html b/demo/build/index.html new file mode 100644 index 0000000..7d21261 --- /dev/null +++ b/demo/build/index.html @@ -0,0 +1,11 @@ + + + + react-keep-alive + + + + +

+ + diff --git a/demo/build/static/index.js b/demo/build/static/index.js new file mode 100644 index 0000000..aa56e23 --- /dev/null +++ b/demo/build/static/index.js @@ -0,0 +1,38051 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./demo/src/index.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./demo/src/index.js": +/*!***************************!*\ + !*** ./demo/src/index.js ***! + \***************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js"); +/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var react_router_dom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react-router-dom */ "./node_modules/react-router-dom/esm/react-router-dom.js"); +/* harmony import */ var _es__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../es */ "./es/index.js"); +/* harmony import */ var _views_A__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./views/A */ "./demo/src/views/A.js"); +/* harmony import */ var _views_B__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./views/B */ "./demo/src/views/B.js"); +/* harmony import */ var _views_C__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./views/C */ "./demo/src/views/C.js"); +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) 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; } + + + + + + + + + +function App() { + var _useState = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(true), + _useState2 = _slicedToArray(_useState, 2), + toggle = _useState2[0], + setToggle = _useState2[1]; + + return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("ul", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__["Link"], { + to: "/a" + }, "a")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", { + onClick: function onClick() { + return setToggle(true); + } + }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__["Link"], { + to: "/b" + }, "b")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("li", { + onClick: function onClick() { + return setToggle(false); + } + }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__["Link"], { + to: "/c" + }, "c"))), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", { + onClick: function onClick() { + return setToggle(!toggle); + } + }, "toggle(", toggle.toString(), ")")), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__["Switch"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__["Route"], { + path: "/a", + render: function render() { + return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_es__WEBPACK_IMPORTED_MODULE_3__["KeepAlive"], { + name: "A" + }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_views_A__WEBPACK_IMPORTED_MODULE_4__["default"], null)); + } + }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__["Route"], { + path: "/b", + render: function render() { + return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_es__WEBPACK_IMPORTED_MODULE_3__["KeepAlive"], { + name: "B" + }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_views_B__WEBPACK_IMPORTED_MODULE_5__["default"], null), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_views_B__WEBPACK_IMPORTED_MODULE_5__["default"], null)); + } + }), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__["Route"], { + path: "/c", + render: function render() { + return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_es__WEBPACK_IMPORTED_MODULE_3__["KeepAlive"], { + name: "C" + }, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_views_C__WEBPACK_IMPORTED_MODULE_6__["default"], null)); + } + }))); +} + +react_dom__WEBPACK_IMPORTED_MODULE_1___default.a.render( /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(_es__WEBPACK_IMPORTED_MODULE_3__["Provider"], { + max: 2 +}, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(react_router_dom__WEBPACK_IMPORTED_MODULE_2__["BrowserRouter"], null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(App, null))), document.getElementById('root')); + +/***/ }), + +/***/ "./demo/src/views/A.js": +/*!*****************************!*\ + !*** ./demo/src/views/A.js ***! + \*****************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _es__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../es */ "./es/index.js"); +/* harmony import */ var _B__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./B */ "./demo/src/views/B.js"); +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) 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; } + + + + + +function Test() { + var _useState = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(0), + _useState2 = _slicedToArray(_useState, 2), + index = _useState2[0], + setIndex = _useState2[1]; + + var divRef = Object(react__WEBPACK_IMPORTED_MODULE_0__["useRef"])(); + Object(_es__WEBPACK_IMPORTED_MODULE_1__["useKeepAliveEffect"])(function () { + console.log('activated', index); + console.log(divRef.current.offsetWidth); + var i = 0; + return function () { + console.log('unactivated', index, i); + }; + }); + return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { + ref: divRef + }, "This is a."), /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("button", { + onClick: function onClick() { + return setIndex(index + 1); + } + }, "click me(", index, ")")); +} + +/* harmony default export */ __webpack_exports__["default"] = (Test); + +/***/ }), + +/***/ "./demo/src/views/B.js": +/*!*****************************!*\ + !*** ./demo/src/views/B.js ***! + \*****************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var react_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-redux */ "./node_modules/react-redux/es/index.js"); +/* harmony import */ var _es__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../es */ "./es/index.js"); +var _class; + +function _typeof(obj) { "@babel/helpers - typeof"; 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 _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 _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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +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 _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + + + + + +var B = Object(_es__WEBPACK_IMPORTED_MODULE_2__["bindLifecycle"])(_class = /*#__PURE__*/function (_React$Component) { + _inherits(B, _React$Component); + + var _super = _createSuper(B); + + function B() { + _classCallCheck(this, B); + + return _super.apply(this, arguments); + } + + _createClass(B, [{ + key: "componentWillMount", + value: function componentWillMount() { + console.log('B componentWillMount'); + } + }, { + key: "componentDidMount", + value: function componentDidMount() { + console.log(this.ref.offsetWidth); + console.log('B componentDidMount'); + } + }, { + key: "componentDidActivate", + value: function componentDidActivate() { + console.log('B componentDidActivate'); + } + }, { + key: "componentWillUpdate", + value: function componentWillUpdate() { + console.log('B componentWillUpdate'); + } + }, { + key: "componentDidUpdate", + value: function componentDidUpdate() { + console.log(this.ref.offsetWidth); + console.log('B componentDidUpdate'); + } + }, { + key: "componentWillUnactivate", + value: function componentWillUnactivate() { + console.log('B componentWillUnactivate'); + } + }, { + key: "componentWillUnmount", + value: function componentWillUnmount() { + console.log('B componentWillUnmount'); + } + }, { + key: "render", + value: function render() { + var _this = this; + + console.log(this); + console.log('B render'); + return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", { + ref: function ref(_ref) { + return _this.ref = _ref; + } + }, "This is b."); + } + }]); + + return B; +}(react__WEBPACK_IMPORTED_MODULE_0___default.a.Component)) || _class; + +/* harmony default export */ __webpack_exports__["default"] = (B); + +/***/ }), + +/***/ "./demo/src/views/C.js": +/*!*****************************!*\ + !*** ./demo/src/views/C.js ***! + \*****************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _es__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../es */ "./es/index.js"); +var _class, _temp; + +function _typeof(obj) { "@babel/helpers - typeof"; 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 _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 _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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +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 _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +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; } + + + + +var C = Object(_es__WEBPACK_IMPORTED_MODULE_1__["bindLifecycle"])(_class = (_temp = /*#__PURE__*/function (_React$Component) { + _inherits(C, _React$Component); + + var _super = _createSuper(C); + + function C() { + var _this; + + _classCallCheck(this, C); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + _this = _super.call.apply(_super, [this].concat(args)); + + _defineProperty(_assertThisInitialized(_this), "state", { + value: false + }); + + return _this; + } + + _createClass(C, [{ + key: "componentWillMount", + value: function componentWillMount() { + console.log('C componentWillMount'); + } + }, { + key: "componentDidMount", + value: function componentDidMount() { + var _this2 = this; + + setTimeout(function () { + _this2.setState({ + value: true + }); + }, 1000); + console.log('C componentDidMount'); + } + }, { + key: "componentDidActivate", + value: function componentDidActivate() { + console.log('C componentDidActivate'); + } + }, { + key: "componentWillUpdate", + value: function componentWillUpdate() { + console.log('C componentWillUpdate'); + } + }, { + key: "componentDidUpdate", + value: function componentDidUpdate() { + console.log('C componentDidUpdate'); + } + }, { + key: "componentWillUnactivate", + value: function componentWillUnactivate() { + console.log('C componentWillUnactivate'); + } + }, { + key: "componentWillUnmount", + value: function componentWillUnmount() { + console.log('C componentWillUnmount'); + } + }, { + key: "render", + value: function render() { + console.log('C render'); + return /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, this.state.value ? /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", null, "This is c.") : null); + } + }]); + + return C; +}(react__WEBPACK_IMPORTED_MODULE_0___default.a.Component), _temp)) || _class; + +/* harmony default export */ __webpack_exports__["default"] = (C); + +/***/ }), + +/***/ "./es/components/AsyncComponent.js": +/*!*****************************************!*\ + !*** ./es/components/AsyncComponent.js ***! + \*****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _utils_bindLifecycle__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/bindLifecycle */ "./es/utils/bindLifecycle.js"); +var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); + + +var AsyncComponent = /** @class */ (function (_super) { + __extends(AsyncComponent, _super); + function AsyncComponent() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.state = { + component: null, + }; + return _this; + } + /** + * Force update child nodes + * + * @private + * @returns + * @memberof AsyncComponent + */ + AsyncComponent.prototype.forceUpdateChildren = function () { + if (!this.props.children) { + return; + } + var root = this._reactInternalFiber || this._reactInternalInstance; + var node = root.child; + var sibling = node; + while (sibling) { + while (true) { + if (node.type && node.type.displayName && node.type.displayName.indexOf(_utils_bindLifecycle__WEBPACK_IMPORTED_MODULE_1__["bindLifecycleTypeName"]) !== -1) { + return; + } + if (node.stateNode) { + break; + } + node = node.child; + } + if (typeof node.type === 'function') { + node.stateNode.forceUpdate(); + } + sibling = sibling.sibling; + } + }; + AsyncComponent.prototype.componentDidMount = function () { + var _this = this; + var children = this.props.children; + Promise.resolve().then(function () { return _this.setState({ component: children }); }); + }; + AsyncComponent.prototype.componentDidUpdate = function () { + this.props.onUpdate(); + }; + // Delayed update + // In order to be able to get real DOM data + AsyncComponent.prototype.shouldComponentUpdate = function () { + var _this = this; + if (!this.state.component) { + // If it is already mounted asynchronously, you don't need to do it again when you update it. + this.props.setMounted(false); + return true; + } + Promise.resolve().then(function () { + if (_this.props.getMounted()) { + _this.props.setMounted(false); + _this.forceUpdateChildren(); + _this.props.onUpdate(); + } + }); + return false; + }; + AsyncComponent.prototype.render = function () { + return this.state.component; + }; + return AsyncComponent; +}(react__WEBPACK_IMPORTED_MODULE_0__["Component"])); +/* harmony default export */ __webpack_exports__["default"] = (AsyncComponent); + + +/***/ }), + +/***/ "./es/components/Comment.js": +/*!**********************************!*\ + !*** ./es/components/Comment.js ***! + \**********************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js"); +/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _utils_noop__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../utils/noop */ "./es/utils/noop.js"); +var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); + + + +var ReactComment = /** @class */ (function (_super) { + __extends(ReactComment, _super); + function ReactComment() { + return _super !== null && _super.apply(this, arguments) || this; + } + ReactComment.prototype.componentDidMount = function () { + var node = react_dom__WEBPACK_IMPORTED_MODULE_1__["findDOMNode"](this); + var commentNode = this.createComment(); + this.commentNode = commentNode; + this.currentNode = node; + this.parentNode = node.parentNode; + this.parentNode.replaceChild(commentNode, node); + react_dom__WEBPACK_IMPORTED_MODULE_1__["unmountComponentAtNode"](node); + this.props.onLoaded(); + }; + ReactComment.prototype.componentWillUnmount = function () { + this.parentNode.replaceChild(this.currentNode, this.commentNode); + }; + ReactComment.prototype.createComment = function () { + var content = this.props.children; + if (typeof content !== 'string') { + content = ''; + } + this.content = content.trim(); + return document.createComment(this.content); + }; + ReactComment.prototype.render = function () { + return react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("div", null); + }; + ReactComment.defaultProps = { + onLoaded: _utils_noop__WEBPACK_IMPORTED_MODULE_2__["default"], + }; + return ReactComment; +}(react__WEBPACK_IMPORTED_MODULE_0__["PureComponent"])); +/* harmony default export */ __webpack_exports__["default"] = (ReactComment); + + +/***/ }), + +/***/ "./es/components/Consumer.js": +/*!***********************************!*\ + !*** ./es/components/Consumer.js ***! + \***********************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _Comment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Comment */ "./es/components/Comment.js"); +/* harmony import */ var _Provider__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Provider */ "./es/components/Provider.js"); +var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); + + + +var Consumer = /** @class */ (function (_super) { + __extends(Consumer, _super); + function Consumer() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.identification = _this.props.identification; + return _this; + } + Consumer.prototype.componentDidMount = function () { + var _a = this.props, setCache = _a.setCache, children = _a.children, keepAlive = _a.keepAlive; + this.renderElement = this.commentRef.parentNode; + setCache(this.identification, { + children: children, + keepAlive: keepAlive, + lifecycle: _Provider__WEBPACK_IMPORTED_MODULE_2__["LIFECYCLE"].MOUNTED, + renderElement: this.renderElement, + activated: true, + }); + }; + Consumer.prototype.componentDidUpdate = function () { + var _a = this.props, setCache = _a.setCache, children = _a.children, keepAlive = _a.keepAlive; + setCache(this.identification, { + children: children, + keepAlive: keepAlive, + lifecycle: _Provider__WEBPACK_IMPORTED_MODULE_2__["LIFECYCLE"].UPDATING, + }); + }; + Consumer.prototype.componentWillUnmount = function () { + var unactivate = this.props.unactivate; + unactivate(this.identification); + }; + Consumer.prototype.render = function () { + var _this = this; + var identification = this.identification; + return react__WEBPACK_IMPORTED_MODULE_0__["createElement"](_Comment__WEBPACK_IMPORTED_MODULE_1__["default"], { ref: function (ref) { return _this.commentRef = ref; } }, identification); + }; + return Consumer; +}(react__WEBPACK_IMPORTED_MODULE_0__["PureComponent"])); +/* harmony default export */ __webpack_exports__["default"] = (Consumer); + + +/***/ }), + +/***/ "./es/components/KeepAlive.js": +/*!************************************!*\ + !*** ./es/components/KeepAlive.js ***! + \************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _AsyncComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AsyncComponent */ "./es/components/AsyncComponent.js"); +/* harmony import */ var _Provider__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Provider */ "./es/components/Provider.js"); +/* harmony import */ var _utils_keepAliveDecorator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../utils/keepAliveDecorator */ "./es/utils/keepAliveDecorator.js"); +/* harmony import */ var _utils_changePositionByComment__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/changePositionByComment */ "./es/utils/changePositionByComment.js"); +var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); + + + + + +var KeepAlive = /** @class */ (function (_super) { + __extends(KeepAlive, _super); + function KeepAlive() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.bindUnmount = null; + _this.bindUnactivate = null; + _this.unmounted = false; + _this.mounted = false; + _this.ref = null; + _this.refNextSibling = null; + _this.childNodes = []; + _this.correctionPosition = function () { + if (_this.ref && _this.ref.parentNode && _this.ref.nextSibling) { + var childNodes = _this.ref.childNodes; + _this.refNextSibling = _this.ref.nextSibling; + _this.childNodes = []; + while (childNodes.length) { + var child = childNodes[0]; + _this.childNodes.push(child); + _this.ref.parentNode.insertBefore(child, _this.ref.nextSibling); + } + _this.ref.parentNode.removeChild(_this.ref); + } + }; + _this.retreatPosition = function () { + if (_this.ref && _this.refNextSibling && _this.refNextSibling.parentNode) { + for (var _i = 0, _a = _this.childNodes; _i < _a.length; _i++) { + var child = _a[_i]; + _this.ref.appendChild(child); + } + _this.refNextSibling.parentNode.insertBefore(_this.ref, _this.refNextSibling); + } + }; + _this.setMounted = function (value) { + _this.mounted = value; + }; + _this.getMounted = function () { + return _this.mounted; + }; + return _this; + } + KeepAlive.prototype.componentDidMount = function () { + var _this = this; + var _container = this.props._container; + var notNeedActivate = _container.notNeedActivate, identification = _container.identification, eventEmitter = _container.eventEmitter, keepAlive = _container.keepAlive; + notNeedActivate(); + var cb = function () { + _this.mount(); + _this.listen(); + eventEmitter.off([identification, _Provider__WEBPACK_IMPORTED_MODULE_2__["START_MOUNTING_DOM"]], cb); + }; + eventEmitter.on([identification, _Provider__WEBPACK_IMPORTED_MODULE_2__["START_MOUNTING_DOM"]], cb); + if (keepAlive) { + this.componentDidActivate(); + } + }; + KeepAlive.prototype.componentDidActivate = function () { + // tslint-disable + }; + KeepAlive.prototype.componentDidUpdate = function () { + var _container = this.props._container; + var notNeedActivate = _container.notNeedActivate, isNeedActivate = _container.isNeedActivate; + if (isNeedActivate()) { + notNeedActivate(); + this.mount(); + this.listen(); + this.unmounted = false; + this.componentDidActivate(); + } + }; + KeepAlive.prototype.componentWillUnactivate = function () { + this.unmount(); + this.unlisten(); + }; + KeepAlive.prototype.componentWillUnmount = function () { + if (!this.unmounted) { + this.unmounted = true; + this.unmount(); + this.unlisten(); + } + }; + KeepAlive.prototype.mount = function () { + var _a = this.props._container, cache = _a.cache, identification = _a.identification, storeElement = _a.storeElement, setLifecycle = _a.setLifecycle; + this.setMounted(true); + var renderElement = cache[identification].renderElement; + setLifecycle(_Provider__WEBPACK_IMPORTED_MODULE_2__["LIFECYCLE"].UPDATING); + Object(_utils_changePositionByComment__WEBPACK_IMPORTED_MODULE_4__["default"])(identification, renderElement, storeElement); + }; + KeepAlive.prototype.unmount = function () { + var _a = this.props._container, identification = _a.identification, storeElement = _a.storeElement, cache = _a.cache, setLifecycle = _a.setLifecycle; + if (cache[identification]) { + var _b = cache[identification], renderElement = _b.renderElement, ifStillActivate = _b.ifStillActivate, reactivate = _b.reactivate; + setLifecycle(_Provider__WEBPACK_IMPORTED_MODULE_2__["LIFECYCLE"].UNMOUNTED); + this.retreatPosition(); + Object(_utils_changePositionByComment__WEBPACK_IMPORTED_MODULE_4__["default"])(identification, storeElement, renderElement); + if (ifStillActivate) { + reactivate(); + } + } + }; + KeepAlive.prototype.listen = function () { + var _a = this.props._container, identification = _a.identification, eventEmitter = _a.eventEmitter; + eventEmitter.on([identification, _utils_keepAliveDecorator__WEBPACK_IMPORTED_MODULE_3__["COMMAND"].CURRENT_UNMOUNT], this.bindUnmount = this.componentWillUnmount.bind(this)); + eventEmitter.on([identification, _utils_keepAliveDecorator__WEBPACK_IMPORTED_MODULE_3__["COMMAND"].CURRENT_UNACTIVATE], this.bindUnactivate = this.componentWillUnactivate.bind(this)); + }; + KeepAlive.prototype.unlisten = function () { + var _a = this.props._container, identification = _a.identification, eventEmitter = _a.eventEmitter; + eventEmitter.off([identification, _utils_keepAliveDecorator__WEBPACK_IMPORTED_MODULE_3__["COMMAND"].CURRENT_UNMOUNT], this.bindUnmount); + eventEmitter.off([identification, _utils_keepAliveDecorator__WEBPACK_IMPORTED_MODULE_3__["COMMAND"].CURRENT_UNACTIVATE], this.bindUnactivate); + }; + KeepAlive.prototype.render = function () { + var _this = this; + // The purpose of this div is to not report an error when moving the DOM, + // so you need to remove this div later. + return (react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("div", { ref: function (ref) { return _this.ref = ref; } }, + react__WEBPACK_IMPORTED_MODULE_0__["createElement"](_AsyncComponent__WEBPACK_IMPORTED_MODULE_1__["default"], { setMounted: this.setMounted, getMounted: this.getMounted, onUpdate: this.correctionPosition }, this.props.children))); + }; + return KeepAlive; +}(react__WEBPACK_IMPORTED_MODULE_0__["PureComponent"])); +/* harmony default export */ __webpack_exports__["default"] = (Object(_utils_keepAliveDecorator__WEBPACK_IMPORTED_MODULE_3__["default"])(KeepAlive)); + + +/***/ }), + +/***/ "./es/components/Provider.js": +/*!***********************************!*\ + !*** ./es/components/Provider.js ***! + \***********************************/ +/*! exports provided: keepAliveProviderTypeName, START_MOUNTING_DOM, LIFECYCLE, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "keepAliveProviderTypeName", function() { return keepAliveProviderTypeName; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "START_MOUNTING_DOM", function() { return START_MOUNTING_DOM; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LIFECYCLE", function() { return LIFECYCLE; }); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react-dom */ "./node_modules/react-dom/index.js"); +/* harmony import */ var react_dom__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react_dom__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _Comment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Comment */ "./es/components/Comment.js"); +/* harmony import */ var _contexts_KeepAliveContext__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../contexts/KeepAliveContext */ "./es/contexts/KeepAliveContext.js"); +/* harmony import */ var _utils_createEventEmitter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/createEventEmitter */ "./es/utils/createEventEmitter.js"); +/* harmony import */ var _utils_createUniqueIdentification__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/createUniqueIdentification */ "./es/utils/createUniqueIdentification.js"); +/* harmony import */ var _utils_createStoreElement__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../utils/createStoreElement */ "./es/utils/createStoreElement.js"); +var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + + + + + + + +var keepAliveProviderTypeName = '$$KeepAliveProvider'; +var START_MOUNTING_DOM = 'startMountingDOM'; +var LIFECYCLE; +(function (LIFECYCLE) { + LIFECYCLE[LIFECYCLE["MOUNTED"] = 0] = "MOUNTED"; + LIFECYCLE[LIFECYCLE["UPDATING"] = 1] = "UPDATING"; + LIFECYCLE[LIFECYCLE["UNMOUNTED"] = 2] = "UNMOUNTED"; +})(LIFECYCLE || (LIFECYCLE = {})); +var KeepAliveProvider = /** @class */ (function (_super) { + __extends(KeepAliveProvider, _super); + function KeepAliveProvider() { + var _this = _super !== null && _super.apply(this, arguments) || this; + // Sometimes data that changes with setState cannot be synchronized, so force refresh + _this.cache = Object.create(null); + _this.keys = []; + _this.eventEmitter = Object(_utils_createEventEmitter__WEBPACK_IMPORTED_MODULE_4__["default"])(); + _this.existed = true; + _this.needRerender = false; + _this.providerIdentification = Object(_utils_createUniqueIdentification__WEBPACK_IMPORTED_MODULE_5__["default"])(); + _this.isExisted = function () { + return _this.existed; + }; + _this.setCache = function (identification, value) { + var _a = _this, cache = _a.cache, keys = _a.keys; + var max = _this.props.max; + var currentCache = cache[identification]; + if (!currentCache) { + keys.push(identification); + } + _this.cache[identification] = __assign(__assign({}, currentCache), value); + for (var key in cache) { + if (Object.prototype.hasOwnProperty.call(cache, key)) { + if (keys.indexOf(key) === -1) { + delete cache[key]; + } + } + } + _this.forceUpdate(function () { + // If the maximum value is set, the value in the cache is deleted after it goes out. + if (currentCache) { + return; + } + if (!max) { + return; + } + var difference = keys.length - max; + if (difference <= 0) { + return; + } + var spliceKeys = keys.splice(0, difference); + _this.forceUpdate(function () { + spliceKeys.forEach(function (key) { + delete cache[key]; + }); + }); + }); + }; + _this.removeCache = function (name) { + var _a = _this, cache = _a.cache, keys = _a.keys; + var needDeletedCacheKeys = []; + for (var key in cache) { + if (Object.prototype.hasOwnProperty.call(cache, key)) { + var keepAliveObject = cache[key]; + // if name is array, mutiple delete caches + if (Object.prototype.toString.call(name) === '[object Array]') { + if (name.indexOf(keepAliveObject.children._owner.key) > -1) { + needDeletedCacheKeys.push(key); + delete cache[key]; + } + } + else if (Object.prototype.toString.call(name) === '[object String]') { + if (name.indexOf(keepAliveObject.children._owner.key) > -1) { + needDeletedCacheKeys.push(key); + delete cache[key]; + } + } + else { + throw new Error("name can be only string or string array"); + } + } + } + _this.keys = keys.filter(function (key) { return needDeletedCacheKeys.indexOf(key) === -1; }); + _this.forceUpdate(); + }; + _this.unactivate = function (identification) { + var cache = _this.cache; + _this.cache[identification] = __assign(__assign({}, cache[identification]), { activated: false, lifecycle: LIFECYCLE.UNMOUNTED }); + _this.forceUpdate(); + }; + _this.startMountingDOM = function (identification) { + _this.eventEmitter.emit([identification, START_MOUNTING_DOM]); + }; + return _this; + } + KeepAliveProvider.prototype.componentDidMount = function () { + this.storeElement = Object(_utils_createStoreElement__WEBPACK_IMPORTED_MODULE_6__["default"])(); + this.forceUpdate(); + }; + KeepAliveProvider.prototype.componentDidUpdate = function () { + if (this.needRerender) { + this.needRerender = false; + this.forceUpdate(); + } + }; + KeepAliveProvider.prototype.componentWillUnmount = function () { + this.existed = false; + document.body.removeChild(this.storeElement); + }; + KeepAliveProvider.prototype.render = function () { + var _this = this; + var _a = this, cache = _a.cache, keys = _a.keys, providerIdentification = _a.providerIdentification, isExisted = _a.isExisted, setCache = _a.setCache, removeCache = _a.removeCache, existed = _a.existed, unactivate = _a.unactivate, storeElement = _a.storeElement, eventEmitter = _a.eventEmitter; + var _b = this.props, innerChildren = _b.children, include = _b.include, exclude = _b.exclude; + if (!storeElement) { + return null; + } + return (react__WEBPACK_IMPORTED_MODULE_0__["createElement"](_contexts_KeepAliveContext__WEBPACK_IMPORTED_MODULE_3__["default"].Provider, { value: { + cache: cache, + keys: keys, + existed: existed, + providerIdentification: providerIdentification, + isExisted: isExisted, + setCache: setCache, + removeCache: removeCache, + unactivate: unactivate, + storeElement: storeElement, + eventEmitter: eventEmitter, + include: include, + exclude: exclude, + } }, + react__WEBPACK_IMPORTED_MODULE_0__["createElement"](react__WEBPACK_IMPORTED_MODULE_0__["Fragment"], null, + innerChildren, + react_dom__WEBPACK_IMPORTED_MODULE_1__["createPortal"](keys.map(function (identification) { + var currentCache = cache[identification]; + var keepAlive = currentCache.keepAlive, children = currentCache.children, lifecycle = currentCache.lifecycle; + var cacheChildren = children; + if (lifecycle === LIFECYCLE.MOUNTED && !keepAlive) { + // If the cache was last enabled, then the components of this keepAlive package are used, + // and the cache is not enabled, the UI needs to be reset. + cacheChildren = null; + _this.needRerender = true; + currentCache.lifecycle = LIFECYCLE.UPDATING; + } + // current true, previous true | undefined, keepAlive false, not cache + // current true, previous true | undefined, keepAlive true, cache + // current true, previous false, keepAlive true, cache + // current true, previous false, keepAlive false, not cache + return (cacheChildren + ? (react__WEBPACK_IMPORTED_MODULE_0__["createElement"](react__WEBPACK_IMPORTED_MODULE_0__["Fragment"], { key: identification }, + react__WEBPACK_IMPORTED_MODULE_0__["createElement"](_Comment__WEBPACK_IMPORTED_MODULE_2__["default"], null, identification), + cacheChildren, + react__WEBPACK_IMPORTED_MODULE_0__["createElement"](_Comment__WEBPACK_IMPORTED_MODULE_2__["default"], { onLoaded: function () { return _this.startMountingDOM(identification); } }, identification))) + : null); + }), storeElement)))); + }; + KeepAliveProvider.displayName = keepAliveProviderTypeName; + KeepAliveProvider.defaultProps = { + max: 10, + }; + return KeepAliveProvider; +}(react__WEBPACK_IMPORTED_MODULE_0__["PureComponent"])); +/* harmony default export */ __webpack_exports__["default"] = (KeepAliveProvider); + + +/***/ }), + +/***/ "./es/contexts/IdentificationContext.js": +/*!**********************************************!*\ + !*** ./es/contexts/IdentificationContext.js ***! + \**********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); + +var WithKeepAliveContext = react__WEBPACK_IMPORTED_MODULE_0__["createContext"]({}); +/* harmony default export */ __webpack_exports__["default"] = (WithKeepAliveContext); + + +/***/ }), + +/***/ "./es/contexts/KeepAliveContext.js": +/*!*****************************************!*\ + !*** ./es/contexts/KeepAliveContext.js ***! + \*****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); + +var KeepAliveContext = react__WEBPACK_IMPORTED_MODULE_0__["createContext"]({}); +/* harmony default export */ __webpack_exports__["default"] = (KeepAliveContext); + + +/***/ }), + +/***/ "./es/index.js": +/*!*********************!*\ + !*** ./es/index.js ***! + \*********************/ +/*! exports provided: Provider, KeepAlive, bindLifecycle, useKeepAliveEffect */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _components_Provider__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/Provider */ "./es/components/Provider.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Provider", function() { return _components_Provider__WEBPACK_IMPORTED_MODULE_0__["default"]; }); + +/* harmony import */ var _components_KeepAlive__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./components/KeepAlive */ "./es/components/KeepAlive.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeepAlive", function() { return _components_KeepAlive__WEBPACK_IMPORTED_MODULE_1__["default"]; }); + +/* harmony import */ var _utils_bindLifecycle__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/bindLifecycle */ "./es/utils/bindLifecycle.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "bindLifecycle", function() { return _utils_bindLifecycle__WEBPACK_IMPORTED_MODULE_2__["default"]; }); + +/* harmony import */ var _utils_useKeepAliveEffect__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/useKeepAliveEffect */ "./es/utils/useKeepAliveEffect.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "useKeepAliveEffect", function() { return _utils_useKeepAliveEffect__WEBPACK_IMPORTED_MODULE_3__["default"]; }); + + + + + + + + +/***/ }), + +/***/ "./es/utils/bindLifecycle.js": +/*!***********************************!*\ + !*** ./es/utils/bindLifecycle.js ***! + \***********************************/ +/*! exports provided: bindLifecycleTypeName, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bindLifecycleTypeName", function() { return bindLifecycleTypeName; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return bindLifecycle; }); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! hoist-non-react-statics */ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js"); +/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _noop__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./noop */ "./es/utils/noop.js"); +/* harmony import */ var _debug__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./debug */ "./es/utils/debug.js"); +/* harmony import */ var _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./keepAliveDecorator */ "./es/utils/keepAliveDecorator.js"); +/* harmony import */ var _withIdentificationContextConsumer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./withIdentificationContextConsumer */ "./es/utils/withIdentificationContextConsumer.js"); +/* harmony import */ var _getDisplayName__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./getDisplayName */ "./es/utils/getDisplayName.js"); +var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __rest = (undefined && undefined.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +var __spreadArrays = (undefined && undefined.__spreadArrays) || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +}; + + + + + + + +var bindLifecycleTypeName = '$$bindLifecycle'; +function bindLifecycle(Component) { + var WrappedComponent = Component.WrappedComponent || Component.wrappedComponent || Component; + var _a = WrappedComponent.prototype, _b = _a.componentDidMount, componentDidMount = _b === void 0 ? _noop__WEBPACK_IMPORTED_MODULE_2__["default"] : _b, _c = _a.componentDidUpdate, componentDidUpdate = _c === void 0 ? _noop__WEBPACK_IMPORTED_MODULE_2__["default"] : _c, _d = _a.componentDidActivate, componentDidActivate = _d === void 0 ? _noop__WEBPACK_IMPORTED_MODULE_2__["default"] : _d, _e = _a.componentWillUnactivate, componentWillUnactivate = _e === void 0 ? _noop__WEBPACK_IMPORTED_MODULE_2__["default"] : _e, _f = _a.componentWillUnmount, componentWillUnmount = _f === void 0 ? _noop__WEBPACK_IMPORTED_MODULE_2__["default"] : _f, _g = _a.shouldComponentUpdate, shouldComponentUpdate = _g === void 0 ? _noop__WEBPACK_IMPORTED_MODULE_2__["default"] : _g; + WrappedComponent.prototype.componentDidMount = function () { + var _this = this; + componentDidMount.call(this); + this._needActivate = false; + var _a = this.props, _b = _a._container, identification = _b.identification, eventEmitter = _b.eventEmitter, activated = _b.activated, keepAlive = _a.keepAlive; + // Determine whether to execute the componentDidActivate life cycle of the current component based on the activation state of the KeepAlive components + if (!activated && keepAlive !== false) { + componentDidActivate.call(this); + } + eventEmitter.on([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_4__["COMMAND"].ACTIVATE], this._bindActivate = function () { return _this._needActivate = true; }, true); + eventEmitter.on([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_4__["COMMAND"].UNACTIVATE], this._bindUnactivate = function () { + componentWillUnactivate.call(_this); + _this._unmounted = false; + }, true); + eventEmitter.on([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_4__["COMMAND"].UNMOUNT], this._bindUnmount = function () { + componentWillUnmount.call(_this); + _this._unmounted = true; + }, true); + }; + // In order to be able to re-update after transferring the DOM, we need to block the first update. + WrappedComponent.prototype.shouldComponentUpdate = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (this._needActivate) { + this.forceUpdate(); + return false; + } + return shouldComponentUpdate.call.apply(shouldComponentUpdate, __spreadArrays([this], args)) || true; + }; + WrappedComponent.prototype.componentDidUpdate = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + componentDidUpdate.call.apply(componentDidUpdate, __spreadArrays([this], args)); + if (this._needActivate) { + this._needActivate = false; + componentDidActivate.call(this); + } + }; + WrappedComponent.prototype.componentWillUnmount = function () { + if (!this._unmounted) { + componentWillUnmount.call(this); + } + var _a = this.props._container, identification = _a.identification, eventEmitter = _a.eventEmitter; + eventEmitter.off([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_4__["COMMAND"].ACTIVATE], this._bindActivate); + eventEmitter.off([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_4__["COMMAND"].UNACTIVATE], this._bindUnactivate); + eventEmitter.off([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_4__["COMMAND"].UNMOUNT], this._bindUnmount); + }; + var BindLifecycleHOC = Object(_withIdentificationContextConsumer__WEBPACK_IMPORTED_MODULE_5__["default"])(function (_a) { + var forwardRef = _a.forwardRef, _b = _a._identificationContextProps, identification = _b.identification, eventEmitter = _b.eventEmitter, activated = _b.activated, keepAlive = _b.keepAlive, extra = _b.extra, wrapperProps = __rest(_a, ["forwardRef", "_identificationContextProps"]); + if (!identification) { + Object(_debug__WEBPACK_IMPORTED_MODULE_3__["warn"])('[React Keep Alive] You should not use bindLifecycle outside a .'); + return null; + } + return (react__WEBPACK_IMPORTED_MODULE_0__["createElement"](Component, __assign({}, extra, wrapperProps, { ref: forwardRef || _noop__WEBPACK_IMPORTED_MODULE_2__["default"], _container: { + identification: identification, + eventEmitter: eventEmitter, + activated: activated, + keepAlive: keepAlive, + } }))); + }); + var BindLifecycle = react__WEBPACK_IMPORTED_MODULE_0__["forwardRef"](function (props, ref) { return (react__WEBPACK_IMPORTED_MODULE_0__["createElement"](BindLifecycleHOC, __assign({}, props, { forwardRef: ref }))); }); + BindLifecycle.WrappedComponent = WrappedComponent; + BindLifecycle.displayName = bindLifecycleTypeName + "(" + Object(_getDisplayName__WEBPACK_IMPORTED_MODULE_6__["default"])(Component) + ")"; + return hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_1___default()(BindLifecycle, Component); +} + + +/***/ }), + +/***/ "./es/utils/changePositionByComment.js": +/*!*********************************************!*\ + !*** ./es/utils/changePositionByComment.js ***! + \*********************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return changePositionByComment; }); +var NODE_TYPES; +(function (NODE_TYPES) { + NODE_TYPES[NODE_TYPES["ELEMENT"] = 1] = "ELEMENT"; + NODE_TYPES[NODE_TYPES["COMMENT"] = 8] = "COMMENT"; +})(NODE_TYPES || (NODE_TYPES = {})); +function findElementsBetweenComments(node, identification) { + var elements = []; + var childNodes = node.childNodes; + var startCommentExist = false; + for (var _i = 0, childNodes_1 = childNodes; _i < childNodes_1.length; _i++) { + var child = childNodes_1[_i]; + if (child.nodeType === NODE_TYPES.COMMENT && + child.nodeValue.trim() === identification && + !startCommentExist) { + startCommentExist = true; + } + else if (startCommentExist && child.nodeType === NODE_TYPES.ELEMENT) { + elements.push(child); + } + else if (child.nodeType === NODE_TYPES.COMMENT && startCommentExist) { + return elements; + } + } + return elements; +} +function findComment(node, identification) { + var childNodes = node.childNodes; + for (var _i = 0, childNodes_2 = childNodes; _i < childNodes_2.length; _i++) { + var child = childNodes_2[_i]; + if (child.nodeType === NODE_TYPES.COMMENT && + child.nodeValue.trim() === identification) { + return child; + } + } +} +function changePositionByComment(identification, presentParentNode, originalParentNode) { + if (!presentParentNode || !originalParentNode) { + return; + } + var elementNodes = findElementsBetweenComments(originalParentNode, identification); + var commentNode = findComment(presentParentNode, identification); + if (!elementNodes.length || !commentNode) { + return; + } + elementNodes.push(elementNodes[elementNodes.length - 1].nextSibling); + elementNodes.unshift(elementNodes[0].previousSibling); + // Deleting comment elements when using commet components will result in component uninstallation errors + for (var i = elementNodes.length - 1; i >= 0; i--) { + presentParentNode.insertBefore(elementNodes[i], commentNode); + } + originalParentNode.appendChild(commentNode); +} + + +/***/ }), + +/***/ "./es/utils/createEventEmitter.js": +/*!****************************************!*\ + !*** ./es/utils/createEventEmitter.js ***! + \****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return createEventEmitter; }); +/* harmony import */ var _debug__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./debug */ "./es/utils/debug.js"); + +function createEventEmitter() { + var events = Object.create(null); + function on(eventNames, listener, direction) { + if (direction === void 0) { direction = false; } + eventNames = getEventNames(eventNames); + var current = events; + var maxIndex = eventNames.length - 1; + for (var i = 0; i < eventNames.length; i++) { + var key = eventNames[i]; + if (!current[key]) { + current[key] = i === maxIndex ? [] : {}; + } + current = current[key]; + } + if (!Array.isArray(current)) { + Object(_debug__WEBPACK_IMPORTED_MODULE_0__["warn"])('[React Keep Alive] Access path error.'); + } + if (direction) { + current.unshift(listener); + } + else { + current.push(listener); + } + } + function off(eventNames, listener) { + var listeners = getListeners(eventNames); + if (!listeners) { + return; + } + var matchIndex = listeners.findIndex(function (v) { return v === listener; }); + if (matchIndex !== -1) { + listeners.splice(matchIndex, 1); + } + } + function removeAllListeners(eventNames) { + var listeners = getListeners(eventNames); + if (!listeners) { + return; + } + eventNames = getEventNames(eventNames); + var lastEventName = eventNames.pop(); + if (lastEventName) { + var event_1 = eventNames.reduce(function (obj, key) { return obj[key]; }, events); + event_1[lastEventName] = []; + } + } + function emit(eventNames) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var listeners = getListeners(eventNames); + if (!listeners) { + return; + } + for (var _a = 0, listeners_1 = listeners; _a < listeners_1.length; _a++) { + var listener = listeners_1[_a]; + if (listener) { + listener.apply(void 0, args); + } + } + } + function listenerCount(eventNames) { + var listeners = getListeners(eventNames); + return listeners ? listeners.length : 0; + } + function clear() { + events = Object.create(null); + } + function getListeners(eventNames) { + eventNames = getEventNames(eventNames); + try { + return eventNames.reduce(function (obj, key) { return obj[key]; }, events); + } + catch (e) { + return; + } + } + function getEventNames(eventNames) { + if (!eventNames) { + Object(_debug__WEBPACK_IMPORTED_MODULE_0__["warn"])('[React Keep Alive] Must exist event name.'); + } + if (typeof eventNames === 'string') { + eventNames = [eventNames]; + } + return eventNames; + } + return { + on: on, + off: off, + emit: emit, + clear: clear, + listenerCount: listenerCount, + removeAllListeners: removeAllListeners, + }; +} + + +/***/ }), + +/***/ "./es/utils/createStoreElement.js": +/*!****************************************!*\ + !*** ./es/utils/createStoreElement.js ***! + \****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return createStoreElement; }); +/* harmony import */ var _createUniqueIdentification__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./createUniqueIdentification */ "./es/utils/createUniqueIdentification.js"); + +function createStoreElement() { + var keepAliveDOM = document.createElement('div'); + keepAliveDOM.dataset.type = _createUniqueIdentification__WEBPACK_IMPORTED_MODULE_0__["prefix"]; + keepAliveDOM.style.display = 'none'; + document.body.appendChild(keepAliveDOM); + return keepAliveDOM; +} + + +/***/ }), + +/***/ "./es/utils/createUniqueIdentification.js": +/*!************************************************!*\ + !*** ./es/utils/createUniqueIdentification.js ***! + \************************************************/ +/*! exports provided: prefix, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prefix", function() { return prefix; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return createUniqueIdentification; }); +var hexDigits = '0123456789abcdef'; +var prefix = 'keep-alive'; +/** + * Create UUID + * Reference: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript + * @export + * @returns + */ +function createUniqueIdentification(length) { + if (length === void 0) { length = 6; } + var strings = []; + for (var i = 0; i < length; i++) { + strings[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1); + } + return prefix + "-" + strings.join(''); +} + + +/***/ }), + +/***/ "./es/utils/debug.js": +/*!***************************!*\ + !*** ./es/utils/debug.js ***! + \***************************/ +/*! exports provided: warn */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "warn", function() { return warn; }); +var warn = function () { return undefined; }; +if (true) { + /** + * Prints a warning in the console if it exists. + * + * @param {*} message + */ + warn = function (message) { + if (typeof console !== undefined && typeof console.error === 'function') { + console.error(message); + } + else { + throw new Error(message); + } + }; +} + + +/***/ }), + +/***/ "./es/utils/getDisplayName.js": +/*!************************************!*\ + !*** ./es/utils/getDisplayName.js ***! + \************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getDisplayName; }); +function getDisplayName(Component) { + return Component.displayName || Component.name || 'Component'; +} + + +/***/ }), + +/***/ "./es/utils/getKeepAlive.js": +/*!**********************************!*\ + !*** ./es/utils/getKeepAlive.js ***! + \**********************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getKeepAlive; }); +/* harmony import */ var _isRegExp__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isRegExp */ "./es/utils/isRegExp.js"); + +function matches(pattern, name) { + if (Array.isArray(pattern)) { + return pattern.indexOf(name) > -1; + } + else if (typeof pattern === 'string') { + return pattern.split(',').indexOf(name) > -1; + } + else if (Object(_isRegExp__WEBPACK_IMPORTED_MODULE_0__["default"])(pattern)) { + return pattern.test(name); + } + return false; +} +function getKeepAlive(name, include, exclude, disabled) { + if (disabled !== undefined) { + return !disabled; + } + if ((include && (!name || !matches(include, name))) || + (exclude && name && matches(exclude, name))) { + return false; + } + return true; +} + + +/***/ }), + +/***/ "./es/utils/getKeyByFiberNode.js": +/*!***************************************!*\ + !*** ./es/utils/getKeyByFiberNode.js ***! + \***************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return getKeyByFiberNode; }); +/* harmony import */ var _withKeepAliveContextConsumer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./withKeepAliveContextConsumer */ "./es/utils/withKeepAliveContextConsumer.js"); + +function getKeyByFiberNode(fiberNode) { + if (!fiberNode) { + return null; + } + var key = fiberNode.key, type = fiberNode.type; + if (type.displayName && type.displayName.indexOf(_withKeepAliveContextConsumer__WEBPACK_IMPORTED_MODULE_0__["WithKeepAliveContextConsumerDisplayName"]) !== -1) { + return key; + } + return getKeyByFiberNode(fiberNode.return); +} + + +/***/ }), + +/***/ "./es/utils/isRegExp.js": +/*!******************************!*\ + !*** ./es/utils/isRegExp.js ***! + \******************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return isRegExp; }); +function isRegExp(value) { + return value && Object.prototype.toString.call(value) === '[object RegExp]'; +} + + +/***/ }), + +/***/ "./es/utils/keepAliveDecorator.js": +/*!****************************************!*\ + !*** ./es/utils/keepAliveDecorator.js ***! + \****************************************/ +/*! exports provided: COMMAND, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "COMMAND", function() { return COMMAND; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return keepAliveDecorator; }); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! hoist-non-react-statics */ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js"); +/* harmony import */ var hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _contexts_IdentificationContext__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../contexts/IdentificationContext */ "./es/contexts/IdentificationContext.js"); +/* harmony import */ var _components_Consumer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../components/Consumer */ "./es/components/Consumer.js"); +/* harmony import */ var _components_Provider__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../components/Provider */ "./es/components/Provider.js"); +/* harmony import */ var _md5__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./md5 */ "./es/utils/md5.js"); +/* harmony import */ var _debug__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./debug */ "./es/utils/debug.js"); +/* harmony import */ var _getKeyByFiberNode__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./getKeyByFiberNode */ "./es/utils/getKeyByFiberNode.js"); +/* harmony import */ var _withIdentificationContextConsumer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./withIdentificationContextConsumer */ "./es/utils/withIdentificationContextConsumer.js"); +/* harmony import */ var _withKeepAliveContextConsumer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./withKeepAliveContextConsumer */ "./es/utils/withKeepAliveContextConsumer.js"); +/* harmony import */ var _shallowEqual__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./shallowEqual */ "./es/utils/shallowEqual.js"); +/* harmony import */ var _getKeepAlive__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./getKeepAlive */ "./es/utils/getKeepAlive.js"); +var __extends = (undefined && undefined.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; +var __rest = (undefined && undefined.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +var __spreadArrays = (undefined && undefined.__spreadArrays) || function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +}; + + + + + + + + + + + + +var COMMAND; +(function (COMMAND) { + COMMAND["UNACTIVATE"] = "unactivate"; + COMMAND["UNMOUNT"] = "unmount"; + COMMAND["ACTIVATE"] = "activate"; + COMMAND["CURRENT_UNMOUNT"] = "current_unmount"; + COMMAND["CURRENT_UNACTIVATE"] = "current_unactivate"; +})(COMMAND || (COMMAND = {})); +/** + * Decorating the component, the main function is to listen to events emitted by the upper component, triggering events of the current component. + * + * @export + * @template P + * @param {React.ComponentType} Component + * @returns {React.ComponentType

} + */ +function keepAliveDecorator(Component) { + var TriggerLifecycleContainer = /** @class */ (function (_super) { + __extends(TriggerLifecycleContainer, _super); + function TriggerLifecycleContainer(props) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var _this = _super.apply(this, __spreadArrays([props], args)) || this; + _this.activated = false; + _this.ifStillActivate = false; + // Let the lifecycle of the cached component be called normally. + _this.needActivate = true; + _this.lifecycle = _components_Provider__WEBPACK_IMPORTED_MODULE_4__["LIFECYCLE"].MOUNTED; + _this.activate = function () { + _this.activated = true; + }; + _this.reactivate = function () { + _this.ifStillActivate = false; + _this.forceUpdate(); + }; + _this.isNeedActivate = function () { + return _this.needActivate; + }; + _this.notNeedActivate = function () { + _this.needActivate = false; + }; + _this.getLifecycle = function () { + return _this.lifecycle; + }; + _this.setLifecycle = function (lifecycle) { + _this.lifecycle = lifecycle; + }; + var cache = props._keepAliveContextProps.cache; + if (!cache) { + Object(_debug__WEBPACK_IMPORTED_MODULE_6__["warn"])('[React Keep Alive] You should not use outside a .'); + } + return _this; + } + TriggerLifecycleContainer.prototype.componentDidMount = function () { + if (!this.ifStillActivate) { + this.activate(); + } + var _a = this.props, keepAlive = _a.keepAlive, eventEmitter = _a._keepAliveContextProps.eventEmitter; + if (keepAlive) { + this.needActivate = true; + eventEmitter.emit([this.identification, COMMAND.ACTIVATE]); + } + }; + TriggerLifecycleContainer.prototype.componentDidCatch = function () { + if (!this.activated) { + this.activate(); + } + }; + TriggerLifecycleContainer.prototype.componentWillUnmount = function () { + var _a = this.props, getCombinedKeepAlive = _a.getCombinedKeepAlive, _b = _a._keepAliveContextProps, eventEmitter = _b.eventEmitter, isExisted = _b.isExisted; + var keepAlive = getCombinedKeepAlive(); + if (!keepAlive || !isExisted()) { + eventEmitter.emit([this.identification, COMMAND.CURRENT_UNMOUNT]); + eventEmitter.emit([this.identification, COMMAND.UNMOUNT]); + } + // When the Provider components are unmounted, the cache is not needed, + // so you don't have to execute the componentWillUnactivate lifecycle. + if (keepAlive && isExisted()) { + eventEmitter.emit([this.identification, COMMAND.CURRENT_UNACTIVATE]); + eventEmitter.emit([this.identification, COMMAND.UNACTIVATE]); + } + }; + TriggerLifecycleContainer.prototype.render = function () { + var _a = this.props, propKey = _a.propKey, keepAlive = _a.keepAlive, extra = _a.extra, getCombinedKeepAlive = _a.getCombinedKeepAlive, _b = _a._keepAliveContextProps, isExisted = _b.isExisted, storeElement = _b.storeElement, cache = _b.cache, eventEmitter = _b.eventEmitter, setCache = _b.setCache, unactivate = _b.unactivate, providerIdentification = _b.providerIdentification, wrapperProps = __rest(_a, ["propKey", "keepAlive", "extra", "getCombinedKeepAlive", "_keepAliveContextProps"]); + if (!this.identification) { + // We need to generate a corresponding unique identifier based on the information of the component. + this.identification = Object(_md5__WEBPACK_IMPORTED_MODULE_5__["default"])("" + providerIdentification + propKey); + // The last activated component must be unactivated before it can be activated again. + var currentCache = cache[this.identification]; + if (currentCache) { + this.ifStillActivate = currentCache.activated; + currentCache.ifStillActivate = this.ifStillActivate; + currentCache.reactivate = this.reactivate; + } + } + var _c = this, isNeedActivate = _c.isNeedActivate, notNeedActivate = _c.notNeedActivate, activated = _c.activated, getLifecycle = _c.getLifecycle, setLifecycle = _c.setLifecycle, identification = _c.identification, ifStillActivate = _c.ifStillActivate; + return !ifStillActivate + ? (react__WEBPACK_IMPORTED_MODULE_0__["createElement"](_components_Consumer__WEBPACK_IMPORTED_MODULE_3__["default"], { identification: identification, keepAlive: keepAlive, cache: cache, setCache: setCache, unactivate: unactivate }, + react__WEBPACK_IMPORTED_MODULE_0__["createElement"](_contexts_IdentificationContext__WEBPACK_IMPORTED_MODULE_2__["default"].Provider, { value: { + identification: identification, + eventEmitter: eventEmitter, + keepAlive: keepAlive, + activated: activated, + getLifecycle: getLifecycle, + isExisted: isExisted, + extra: extra, + } }, + react__WEBPACK_IMPORTED_MODULE_0__["createElement"](Component, __assign({}, wrapperProps, { _container: { + isNeedActivate: isNeedActivate, + notNeedActivate: notNeedActivate, + setLifecycle: setLifecycle, + eventEmitter: eventEmitter, + identification: identification, + storeElement: storeElement, + keepAlive: keepAlive, + cache: cache, + } }))))) + : null; + }; + return TriggerLifecycleContainer; + }(react__WEBPACK_IMPORTED_MODULE_0__["PureComponent"])); + var ListenUpperKeepAliveContainer = /** @class */ (function (_super) { + __extends(ListenUpperKeepAliveContainer, _super); + function ListenUpperKeepAliveContainer() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.state = { + activated: true, + }; + _this.getCombinedKeepAlive = function () { + return _this.combinedKeepAlive; + }; + return _this; + } + ListenUpperKeepAliveContainer.prototype.shouldComponentUpdate = function (nextProps, nextState) { + if (this.state.activated !== nextState.activated) { + return true; + } + var _a = this.props, _keepAliveContextProps = _a._keepAliveContextProps, _identificationContextProps = _a._identificationContextProps, rest = __rest(_a, ["_keepAliveContextProps", "_identificationContextProps"]); + var nextKeepAliveContextProps = nextProps._keepAliveContextProps, nextIdentificationContextProps = nextProps._identificationContextProps, nextRest = __rest(nextProps, ["_keepAliveContextProps", "_identificationContextProps"]); + if (!Object(_shallowEqual__WEBPACK_IMPORTED_MODULE_10__["default"])(rest, nextRest)) { + return true; + } + if (!Object(_shallowEqual__WEBPACK_IMPORTED_MODULE_10__["default"])(_keepAliveContextProps, nextKeepAliveContextProps) || + !Object(_shallowEqual__WEBPACK_IMPORTED_MODULE_10__["default"])(_identificationContextProps, nextIdentificationContextProps)) { + return true; + } + return false; + }; + ListenUpperKeepAliveContainer.prototype.componentDidMount = function () { + this.listenUpperKeepAlive(); + }; + ListenUpperKeepAliveContainer.prototype.componentWillUnmount = function () { + this.unlistenUpperKeepAlive(); + }; + ListenUpperKeepAliveContainer.prototype.listenUpperKeepAlive = function () { + var _this = this; + var _a = this.props._identificationContextProps, identification = _a.identification, eventEmitter = _a.eventEmitter; + if (!identification) { + return; + } + eventEmitter.on([identification, COMMAND.ACTIVATE], this.activate = function () { return _this.setState({ activated: true }); }, true); + eventEmitter.on([identification, COMMAND.UNACTIVATE], this.unactivate = function () { return _this.setState({ activated: false }); }, true); + eventEmitter.on([identification, COMMAND.UNMOUNT], this.unmount = function () { return _this.setState({ activated: false }); }, true); + }; + ListenUpperKeepAliveContainer.prototype.unlistenUpperKeepAlive = function () { + var _a = this.props._identificationContextProps, identification = _a.identification, eventEmitter = _a.eventEmitter; + if (!identification) { + return; + } + eventEmitter.off([identification, COMMAND.ACTIVATE], this.activate); + eventEmitter.off([identification, COMMAND.UNACTIVATE], this.unactivate); + eventEmitter.off([identification, COMMAND.UNMOUNT], this.unmount); + }; + ListenUpperKeepAliveContainer.prototype.render = function () { + var _a = this.props, _b = _a._identificationContextProps, identification = _b.identification, upperKeepAlive = _b.keepAlive, getLifecycle = _b.getLifecycle, disabled = _a.disabled, name = _a.name, wrapperProps = __rest(_a, ["_identificationContextProps", "disabled", "name"]); + var activated = this.state.activated; + var _c = wrapperProps._keepAliveContextProps, include = _c.include, exclude = _c.exclude; + // When the parent KeepAlive component is mounted or unmounted, + // use the keepAlive prop of the parent KeepAlive component. + var propKey = name || Object(_getKeyByFiberNode__WEBPACK_IMPORTED_MODULE_7__["default"])(this._reactInternalFiber); + if (!propKey) { + Object(_debug__WEBPACK_IMPORTED_MODULE_6__["warn"])('[React Keep Alive] components must have key or name.'); + return null; + } + var newKeepAlive = Object(_getKeepAlive__WEBPACK_IMPORTED_MODULE_11__["default"])(propKey, include, exclude, disabled); + this.combinedKeepAlive = getLifecycle === undefined || getLifecycle() === _components_Provider__WEBPACK_IMPORTED_MODULE_4__["LIFECYCLE"].UPDATING + ? newKeepAlive + : identification + ? upperKeepAlive && newKeepAlive + : newKeepAlive; + return activated + ? (react__WEBPACK_IMPORTED_MODULE_0__["createElement"](TriggerLifecycleContainer, __assign({}, wrapperProps, { key: propKey, propKey: propKey, keepAlive: this.combinedKeepAlive, getCombinedKeepAlive: this.getCombinedKeepAlive }))) + : null; + }; + return ListenUpperKeepAliveContainer; + }(react__WEBPACK_IMPORTED_MODULE_0__["Component"])); + var KeepAlive = Object(_withKeepAliveContextConsumer__WEBPACK_IMPORTED_MODULE_9__["default"])(Object(_withIdentificationContextConsumer__WEBPACK_IMPORTED_MODULE_8__["default"])(ListenUpperKeepAliveContainer)); + return hoist_non_react_statics__WEBPACK_IMPORTED_MODULE_1___default()(KeepAlive, Component); +} + + +/***/ }), + +/***/ "./es/utils/md5.js": +/*!*************************!*\ + !*** ./es/utils/md5.js ***! + \*************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return createMD5; }); +/* harmony import */ var js_md5__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! js-md5 */ "./node_modules/js-md5/src/md5.js"); +/* harmony import */ var js_md5__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(js_md5__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _createUniqueIdentification__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./createUniqueIdentification */ "./es/utils/createUniqueIdentification.js"); + + +function createMD5(value, length) { + if (value === void 0) { value = ''; } + if (length === void 0) { length = 6; } + return _createUniqueIdentification__WEBPACK_IMPORTED_MODULE_1__["prefix"] + "-" + js_md5__WEBPACK_IMPORTED_MODULE_0___default()(value).substr(0, length); +} + + +/***/ }), + +/***/ "./es/utils/noop.js": +/*!**************************!*\ + !*** ./es/utils/noop.js ***! + \**************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +var noop = function () { return undefined; }; +/* harmony default export */ __webpack_exports__["default"] = (noop); + + +/***/ }), + +/***/ "./es/utils/shallowEqual.js": +/*!**********************************!*\ + !*** ./es/utils/shallowEqual.js ***! + \**********************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/** + * From react + */ +function is(x, y) { + return ((x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y) // eslint-disable-line no-self-compare + ); +} +var hasOwnProperty = Object.prototype.hasOwnProperty; +function shallowEqual(objA, objB) { + if (is(objA, objB)) { + return true; + } + if (typeof objA !== 'object' || + objA === null || + typeof objB !== 'object' || + objB === null) { + return false; + } + var keysA = Object.keys(objA); + var keysB = Object.keys(objB); + if (keysA.length !== keysB.length) { + return false; + } + // Test for A's keys different from B. + for (var _i = 0, keysA_1 = keysA; _i < keysA_1.length; _i++) { + var key = keysA_1[_i]; + if (!hasOwnProperty.call(objB, key) || + !is(objA[key], objB[key])) { + return false; + } + } + return true; +} +/* harmony default export */ __webpack_exports__["default"] = (shallowEqual); + + +/***/ }), + +/***/ "./es/utils/useKeepAliveEffect.js": +/*!****************************************!*\ + !*** ./es/utils/useKeepAliveEffect.js ***! + \****************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return useKeepAliveEffect; }); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _debug__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./debug */ "./es/utils/debug.js"); +/* harmony import */ var _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./keepAliveDecorator */ "./es/utils/keepAliveDecorator.js"); +/* harmony import */ var _contexts_IdentificationContext__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../contexts/IdentificationContext */ "./es/contexts/IdentificationContext.js"); + + + + +function useKeepAliveEffect(effect) { + if (!react__WEBPACK_IMPORTED_MODULE_0__["useEffect"]) { + Object(_debug__WEBPACK_IMPORTED_MODULE_1__["warn"])('[React Keep Alive] useKeepAliveEffect API requires react 16.8 or later.'); + } + var _a = Object(react__WEBPACK_IMPORTED_MODULE_0__["useContext"])(_contexts_IdentificationContext__WEBPACK_IMPORTED_MODULE_3__["default"]), eventEmitter = _a.eventEmitter, identification = _a.identification; + var effectRef = Object(react__WEBPACK_IMPORTED_MODULE_0__["useRef"])(effect); + effectRef.current = effect; + Object(react__WEBPACK_IMPORTED_MODULE_0__["useEffect"])(function () { + var bindActivate = null; + var bindUnactivate = null; + var bindUnmount = null; + var effectResult = effectRef.current(); + var unmounted = false; + eventEmitter.on([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_2__["COMMAND"].ACTIVATE], bindActivate = function () { + // Delayed update + Promise.resolve().then(function () { + effectResult = effectRef.current(); + }); + unmounted = false; + }, true); + eventEmitter.on([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_2__["COMMAND"].UNACTIVATE], bindUnactivate = function () { + if (effectResult) { + effectResult(); + unmounted = true; + } + }, true); + eventEmitter.on([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_2__["COMMAND"].UNMOUNT], bindUnmount = function () { + if (effectResult) { + effectResult(); + unmounted = true; + } + }, true); + return function () { + if (effectResult && !unmounted) { + effectResult(); + } + eventEmitter.off([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_2__["COMMAND"].ACTIVATE], bindActivate); + eventEmitter.off([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_2__["COMMAND"].UNACTIVATE], bindUnactivate); + eventEmitter.off([identification, _keepAliveDecorator__WEBPACK_IMPORTED_MODULE_2__["COMMAND"].UNMOUNT], bindUnmount); + }; + }, []); +} + + +/***/ }), + +/***/ "./es/utils/withIdentificationContextConsumer.js": +/*!*******************************************************!*\ + !*** ./es/utils/withIdentificationContextConsumer.js ***! + \*******************************************************/ +/*! exports provided: withIdentificationContextConsumerDisplayName, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withIdentificationContextConsumerDisplayName", function() { return withIdentificationContextConsumerDisplayName; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return withIdentificationContextConsumer; }); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _contexts_IdentificationContext__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../contexts/IdentificationContext */ "./es/contexts/IdentificationContext.js"); +/* harmony import */ var _getDisplayName__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./getDisplayName */ "./es/utils/getDisplayName.js"); +var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + + + +var withIdentificationContextConsumerDisplayName = 'withIdentificationContextConsumer'; +function withIdentificationContextConsumer(Component) { + var WithIdentificationContextConsumer = function (props) { return (react__WEBPACK_IMPORTED_MODULE_0__["createElement"](_contexts_IdentificationContext__WEBPACK_IMPORTED_MODULE_1__["default"].Consumer, null, function (contextProps) { return react__WEBPACK_IMPORTED_MODULE_0__["createElement"](Component, __assign({ _identificationContextProps: contextProps }, props)); })); }; + WithIdentificationContextConsumer.displayName = withIdentificationContextConsumerDisplayName + "(" + Object(_getDisplayName__WEBPACK_IMPORTED_MODULE_2__["default"])(Component) + ")"; + return WithIdentificationContextConsumer; +} + + +/***/ }), + +/***/ "./es/utils/withKeepAliveContextConsumer.js": +/*!**************************************************!*\ + !*** ./es/utils/withKeepAliveContextConsumer.js ***! + \**************************************************/ +/*! exports provided: WithKeepAliveContextConsumerDisplayName, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WithKeepAliveContextConsumerDisplayName", function() { return WithKeepAliveContextConsumerDisplayName; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return withKeepAliveContextConsumer; }); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _contexts_KeepAliveContext__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../contexts/KeepAliveContext */ "./es/contexts/KeepAliveContext.js"); +/* harmony import */ var _getDisplayName__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./getDisplayName */ "./es/utils/getDisplayName.js"); +var __assign = (undefined && undefined.__assign) || function () { + __assign = Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + + + +var WithKeepAliveContextConsumerDisplayName = 'withKeepAliveContextConsumer'; +function withKeepAliveContextConsumer(Component) { + var WithKeepAliveContextConsumer = function (props) { return (react__WEBPACK_IMPORTED_MODULE_0__["createElement"](_contexts_KeepAliveContext__WEBPACK_IMPORTED_MODULE_1__["default"].Consumer, null, function (contextProps) { return react__WEBPACK_IMPORTED_MODULE_0__["createElement"](Component, __assign({ _keepAliveContextProps: contextProps }, props)); })); }; + WithKeepAliveContextConsumer.displayName = WithKeepAliveContextConsumerDisplayName + "(" + Object(_getDisplayName__WEBPACK_IMPORTED_MODULE_2__["default"])(Component) + ")"; + return WithKeepAliveContextConsumer; +} + + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/extends.js": +/*!************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/extends.js ***! + \************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _extends; }); +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); +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js": +/*!******************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js ***! + \******************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _inheritsLoose; }); +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} + +/***/ }), + +/***/ "./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js": +/*!*********************************************************************************!*\ + !*** ./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js ***! + \*********************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return _objectWithoutPropertiesLoose; }); +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; +} + +/***/ }), + +/***/ "./node_modules/history/esm/history.js": +/*!*********************************************!*\ + !*** ./node_modules/history/esm/history.js ***! + \*********************************************/ +/*! exports provided: createBrowserHistory, createHashHistory, createMemoryHistory, createLocation, locationsAreEqual, parsePath, createPath */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createBrowserHistory", function() { return createBrowserHistory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createHashHistory", function() { return createHashHistory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createMemoryHistory", function() { return createMemoryHistory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createLocation", function() { return createLocation; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "locationsAreEqual", function() { return locationsAreEqual; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parsePath", function() { return parsePath; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createPath", function() { return createPath; }); +/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ "./node_modules/@babel/runtime/helpers/esm/extends.js"); +/* harmony import */ var resolve_pathname__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! resolve-pathname */ "./node_modules/resolve-pathname/esm/resolve-pathname.js"); +/* harmony import */ var value_equal__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! value-equal */ "./node_modules/value-equal/esm/value-equal.js"); +/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! tiny-warning */ "./node_modules/tiny-warning/dist/tiny-warning.esm.js"); +/* harmony import */ var tiny_invariant__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! tiny-invariant */ "./node_modules/tiny-invariant/dist/tiny-invariant.esm.js"); + + + + + + +function addLeadingSlash(path) { + return path.charAt(0) === '/' ? path : '/' + path; +} +function stripLeadingSlash(path) { + return path.charAt(0) === '/' ? path.substr(1) : path; +} +function hasBasename(path, prefix) { + return path.toLowerCase().indexOf(prefix.toLowerCase()) === 0 && '/?#'.indexOf(path.charAt(prefix.length)) !== -1; +} +function stripBasename(path, prefix) { + return hasBasename(path, prefix) ? path.substr(prefix.length) : path; +} +function stripTrailingSlash(path) { + return path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path; +} +function parsePath(path) { + var pathname = path || '/'; + var search = ''; + var hash = ''; + var hashIndex = pathname.indexOf('#'); + + if (hashIndex !== -1) { + hash = pathname.substr(hashIndex); + pathname = pathname.substr(0, hashIndex); + } + + var searchIndex = pathname.indexOf('?'); + + if (searchIndex !== -1) { + search = pathname.substr(searchIndex); + pathname = pathname.substr(0, searchIndex); + } + + return { + pathname: pathname, + search: search === '?' ? '' : search, + hash: hash === '#' ? '' : hash + }; +} +function createPath(location) { + var pathname = location.pathname, + search = location.search, + hash = location.hash; + var path = pathname || '/'; + if (search && search !== '?') path += search.charAt(0) === '?' ? search : "?" + search; + if (hash && hash !== '#') path += hash.charAt(0) === '#' ? hash : "#" + hash; + return path; +} + +function createLocation(path, state, key, currentLocation) { + var location; + + if (typeof path === 'string') { + // Two-arg form: push(path, state) + location = parsePath(path); + location.state = state; + } else { + // One-arg form: push(location) + location = Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])({}, path); + if (location.pathname === undefined) location.pathname = ''; + + if (location.search) { + if (location.search.charAt(0) !== '?') location.search = '?' + location.search; + } else { + location.search = ''; + } + + if (location.hash) { + if (location.hash.charAt(0) !== '#') location.hash = '#' + location.hash; + } else { + location.hash = ''; + } + + if (state !== undefined && location.state === undefined) location.state = state; + } + + try { + location.pathname = decodeURI(location.pathname); + } catch (e) { + if (e instanceof URIError) { + throw new URIError('Pathname "' + location.pathname + '" could not be decoded. ' + 'This is likely caused by an invalid percent-encoding.'); + } else { + throw e; + } + } + + if (key) location.key = key; + + if (currentLocation) { + // Resolve incomplete/relative pathname relative to current location. + if (!location.pathname) { + location.pathname = currentLocation.pathname; + } else if (location.pathname.charAt(0) !== '/') { + location.pathname = Object(resolve_pathname__WEBPACK_IMPORTED_MODULE_1__["default"])(location.pathname, currentLocation.pathname); + } + } else { + // When there is no prior location and pathname is empty, set it to / + if (!location.pathname) { + location.pathname = '/'; + } + } + + return location; +} +function locationsAreEqual(a, b) { + return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash && a.key === b.key && Object(value_equal__WEBPACK_IMPORTED_MODULE_2__["default"])(a.state, b.state); +} + +function createTransitionManager() { + var prompt = null; + + function setPrompt(nextPrompt) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(prompt == null, 'A history supports only one prompt at a time') : undefined; + prompt = nextPrompt; + return function () { + if (prompt === nextPrompt) prompt = null; + }; + } + + function confirmTransitionTo(location, action, getUserConfirmation, callback) { + // TODO: If another transition starts while we're still confirming + // the previous one, we may end up in a weird state. Figure out the + // best way to handle this. + if (prompt != null) { + var result = typeof prompt === 'function' ? prompt(location, action) : prompt; + + if (typeof result === 'string') { + if (typeof getUserConfirmation === 'function') { + getUserConfirmation(result, callback); + } else { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(false, 'A history needs a getUserConfirmation function in order to use a prompt message') : undefined; + callback(true); + } + } else { + // Return false from a transition hook to cancel the transition. + callback(result !== false); + } + } else { + callback(true); + } + } + + var listeners = []; + + function appendListener(fn) { + var isActive = true; + + function listener() { + if (isActive) fn.apply(void 0, arguments); + } + + listeners.push(listener); + return function () { + isActive = false; + listeners = listeners.filter(function (item) { + return item !== listener; + }); + }; + } + + function notifyListeners() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + listeners.forEach(function (listener) { + return listener.apply(void 0, args); + }); + } + + return { + setPrompt: setPrompt, + confirmTransitionTo: confirmTransitionTo, + appendListener: appendListener, + notifyListeners: notifyListeners + }; +} + +var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); +function getConfirmation(message, callback) { + callback(window.confirm(message)); // eslint-disable-line no-alert +} +/** + * Returns true if the HTML5 history API is supported. Taken from Modernizr. + * + * https://github.com/Modernizr/Modernizr/blob/master/LICENSE + * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js + * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586 + */ + +function supportsHistory() { + var ua = window.navigator.userAgent; + if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false; + return window.history && 'pushState' in window.history; +} +/** + * Returns true if browser fires popstate on hash change. + * IE10 and IE11 do not. + */ + +function supportsPopStateOnHashChange() { + return window.navigator.userAgent.indexOf('Trident') === -1; +} +/** + * Returns false if using go(n) with hash history causes a full page reload. + */ + +function supportsGoWithoutReloadUsingHash() { + return window.navigator.userAgent.indexOf('Firefox') === -1; +} +/** + * Returns true if a given popstate event is an extraneous WebKit event. + * Accounts for the fact that Chrome on iOS fires real popstate events + * containing undefined state when pressing the back button. + */ + +function isExtraneousPopstateEvent(event) { + return event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1; +} + +var PopStateEvent = 'popstate'; +var HashChangeEvent = 'hashchange'; + +function getHistoryState() { + try { + return window.history.state || {}; + } catch (e) { + // IE 11 sometimes throws when accessing window.history.state + // See https://github.com/ReactTraining/history/pull/289 + return {}; + } +} +/** + * Creates a history object that uses the HTML5 history API including + * pushState, replaceState, and the popstate event. + */ + + +function createBrowserHistory(props) { + if (props === void 0) { + props = {}; + } + + !canUseDOM ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_4__["default"])(false, 'Browser history needs a DOM') : undefined : void 0; + var globalHistory = window.history; + var canUseHistory = supportsHistory(); + var needsHashChangeListener = !supportsPopStateOnHashChange(); + var _props = props, + _props$forceRefresh = _props.forceRefresh, + forceRefresh = _props$forceRefresh === void 0 ? false : _props$forceRefresh, + _props$getUserConfirm = _props.getUserConfirmation, + getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm, + _props$keyLength = _props.keyLength, + keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength; + var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : ''; + + function getDOMLocation(historyState) { + var _ref = historyState || {}, + key = _ref.key, + state = _ref.state; + + var _window$location = window.location, + pathname = _window$location.pathname, + search = _window$location.search, + hash = _window$location.hash; + var path = pathname + search + hash; + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path "' + path + '" to begin with "' + basename + '".') : undefined; + if (basename) path = stripBasename(path, basename); + return createLocation(path, state, key); + } + + function createKey() { + return Math.random().toString(36).substr(2, keyLength); + } + + var transitionManager = createTransitionManager(); + + function setState(nextState) { + Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])(history, nextState); + + history.length = globalHistory.length; + transitionManager.notifyListeners(history.location, history.action); + } + + function handlePopState(event) { + // Ignore extraneous popstate events in WebKit. + if (isExtraneousPopstateEvent(event)) return; + handlePop(getDOMLocation(event.state)); + } + + function handleHashChange() { + handlePop(getDOMLocation(getHistoryState())); + } + + var forceNextPop = false; + + function handlePop(location) { + if (forceNextPop) { + forceNextPop = false; + setState(); + } else { + var action = 'POP'; + transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) { + if (ok) { + setState({ + action: action, + location: location + }); + } else { + revertPop(location); + } + }); + } + } + + function revertPop(fromLocation) { + var toLocation = history.location; // TODO: We could probably make this more reliable by + // keeping a list of keys we've seen in sessionStorage. + // Instead, we just default to 0 for keys we don't know. + + var toIndex = allKeys.indexOf(toLocation.key); + if (toIndex === -1) toIndex = 0; + var fromIndex = allKeys.indexOf(fromLocation.key); + if (fromIndex === -1) fromIndex = 0; + var delta = toIndex - fromIndex; + + if (delta) { + forceNextPop = true; + go(delta); + } + } + + var initialLocation = getDOMLocation(getHistoryState()); + var allKeys = [initialLocation.key]; // Public interface + + function createHref(location) { + return basename + createPath(location); + } + + function push(path, state) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined; + var action = 'PUSH'; + var location = createLocation(path, state, createKey(), history.location); + transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) { + if (!ok) return; + var href = createHref(location); + var key = location.key, + state = location.state; + + if (canUseHistory) { + globalHistory.pushState({ + key: key, + state: state + }, null, href); + + if (forceRefresh) { + window.location.href = href; + } else { + var prevIndex = allKeys.indexOf(history.location.key); + var nextKeys = allKeys.slice(0, prevIndex + 1); + nextKeys.push(location.key); + allKeys = nextKeys; + setState({ + action: action, + location: location + }); + } + } else { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(state === undefined, 'Browser history cannot push state in browsers that do not support HTML5 history') : undefined; + window.location.href = href; + } + }); + } + + function replace(path, state) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined; + var action = 'REPLACE'; + var location = createLocation(path, state, createKey(), history.location); + transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) { + if (!ok) return; + var href = createHref(location); + var key = location.key, + state = location.state; + + if (canUseHistory) { + globalHistory.replaceState({ + key: key, + state: state + }, null, href); + + if (forceRefresh) { + window.location.replace(href); + } else { + var prevIndex = allKeys.indexOf(history.location.key); + if (prevIndex !== -1) allKeys[prevIndex] = location.key; + setState({ + action: action, + location: location + }); + } + } else { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(state === undefined, 'Browser history cannot replace state in browsers that do not support HTML5 history') : undefined; + window.location.replace(href); + } + }); + } + + function go(n) { + globalHistory.go(n); + } + + function goBack() { + go(-1); + } + + function goForward() { + go(1); + } + + var listenerCount = 0; + + function checkDOMListeners(delta) { + listenerCount += delta; + + if (listenerCount === 1 && delta === 1) { + window.addEventListener(PopStateEvent, handlePopState); + if (needsHashChangeListener) window.addEventListener(HashChangeEvent, handleHashChange); + } else if (listenerCount === 0) { + window.removeEventListener(PopStateEvent, handlePopState); + if (needsHashChangeListener) window.removeEventListener(HashChangeEvent, handleHashChange); + } + } + + var isBlocked = false; + + function block(prompt) { + if (prompt === void 0) { + prompt = false; + } + + var unblock = transitionManager.setPrompt(prompt); + + if (!isBlocked) { + checkDOMListeners(1); + isBlocked = true; + } + + return function () { + if (isBlocked) { + isBlocked = false; + checkDOMListeners(-1); + } + + return unblock(); + }; + } + + function listen(listener) { + var unlisten = transitionManager.appendListener(listener); + checkDOMListeners(1); + return function () { + checkDOMListeners(-1); + unlisten(); + }; + } + + var history = { + length: globalHistory.length, + action: 'POP', + location: initialLocation, + createHref: createHref, + push: push, + replace: replace, + go: go, + goBack: goBack, + goForward: goForward, + block: block, + listen: listen + }; + return history; +} + +var HashChangeEvent$1 = 'hashchange'; +var HashPathCoders = { + hashbang: { + encodePath: function encodePath(path) { + return path.charAt(0) === '!' ? path : '!/' + stripLeadingSlash(path); + }, + decodePath: function decodePath(path) { + return path.charAt(0) === '!' ? path.substr(1) : path; + } + }, + noslash: { + encodePath: stripLeadingSlash, + decodePath: addLeadingSlash + }, + slash: { + encodePath: addLeadingSlash, + decodePath: addLeadingSlash + } +}; + +function stripHash(url) { + var hashIndex = url.indexOf('#'); + return hashIndex === -1 ? url : url.slice(0, hashIndex); +} + +function getHashPath() { + // We can't use window.location.hash here because it's not + // consistent across browsers - Firefox will pre-decode it! + var href = window.location.href; + var hashIndex = href.indexOf('#'); + return hashIndex === -1 ? '' : href.substring(hashIndex + 1); +} + +function pushHashPath(path) { + window.location.hash = path; +} + +function replaceHashPath(path) { + window.location.replace(stripHash(window.location.href) + '#' + path); +} + +function createHashHistory(props) { + if (props === void 0) { + props = {}; + } + + !canUseDOM ? true ? Object(tiny_invariant__WEBPACK_IMPORTED_MODULE_4__["default"])(false, 'Hash history needs a DOM') : undefined : void 0; + var globalHistory = window.history; + var canGoWithoutReload = supportsGoWithoutReloadUsingHash(); + var _props = props, + _props$getUserConfirm = _props.getUserConfirmation, + getUserConfirmation = _props$getUserConfirm === void 0 ? getConfirmation : _props$getUserConfirm, + _props$hashType = _props.hashType, + hashType = _props$hashType === void 0 ? 'slash' : _props$hashType; + var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : ''; + var _HashPathCoders$hashT = HashPathCoders[hashType], + encodePath = _HashPathCoders$hashT.encodePath, + decodePath = _HashPathCoders$hashT.decodePath; + + function getDOMLocation() { + var path = decodePath(getHashPath()); + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path "' + path + '" to begin with "' + basename + '".') : undefined; + if (basename) path = stripBasename(path, basename); + return createLocation(path); + } + + var transitionManager = createTransitionManager(); + + function setState(nextState) { + Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])(history, nextState); + + history.length = globalHistory.length; + transitionManager.notifyListeners(history.location, history.action); + } + + var forceNextPop = false; + var ignorePath = null; + + function locationsAreEqual$$1(a, b) { + return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash; + } + + function handleHashChange() { + var path = getHashPath(); + var encodedPath = encodePath(path); + + if (path !== encodedPath) { + // Ensure we always have a properly-encoded hash. + replaceHashPath(encodedPath); + } else { + var location = getDOMLocation(); + var prevLocation = history.location; + if (!forceNextPop && locationsAreEqual$$1(prevLocation, location)) return; // A hashchange doesn't always == location change. + + if (ignorePath === createPath(location)) return; // Ignore this change; we already setState in push/replace. + + ignorePath = null; + handlePop(location); + } + } + + function handlePop(location) { + if (forceNextPop) { + forceNextPop = false; + setState(); + } else { + var action = 'POP'; + transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) { + if (ok) { + setState({ + action: action, + location: location + }); + } else { + revertPop(location); + } + }); + } + } + + function revertPop(fromLocation) { + var toLocation = history.location; // TODO: We could probably make this more reliable by + // keeping a list of paths we've seen in sessionStorage. + // Instead, we just default to 0 for paths we don't know. + + var toIndex = allPaths.lastIndexOf(createPath(toLocation)); + if (toIndex === -1) toIndex = 0; + var fromIndex = allPaths.lastIndexOf(createPath(fromLocation)); + if (fromIndex === -1) fromIndex = 0; + var delta = toIndex - fromIndex; + + if (delta) { + forceNextPop = true; + go(delta); + } + } // Ensure the hash is encoded properly before doing anything else. + + + var path = getHashPath(); + var encodedPath = encodePath(path); + if (path !== encodedPath) replaceHashPath(encodedPath); + var initialLocation = getDOMLocation(); + var allPaths = [createPath(initialLocation)]; // Public interface + + function createHref(location) { + var baseTag = document.querySelector('base'); + var href = ''; + + if (baseTag && baseTag.getAttribute('href')) { + href = stripHash(window.location.href); + } + + return href + '#' + encodePath(basename + createPath(location)); + } + + function push(path, state) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(state === undefined, 'Hash history cannot push state; it is ignored') : undefined; + var action = 'PUSH'; + var location = createLocation(path, undefined, undefined, history.location); + transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) { + if (!ok) return; + var path = createPath(location); + var encodedPath = encodePath(basename + path); + var hashChanged = getHashPath() !== encodedPath; + + if (hashChanged) { + // We cannot tell if a hashchange was caused by a PUSH, so we'd + // rather setState here and ignore the hashchange. The caveat here + // is that other hash histories in the page will consider it a POP. + ignorePath = path; + pushHashPath(encodedPath); + var prevIndex = allPaths.lastIndexOf(createPath(history.location)); + var nextPaths = allPaths.slice(0, prevIndex + 1); + nextPaths.push(path); + allPaths = nextPaths; + setState({ + action: action, + location: location + }); + } else { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(false, 'Hash history cannot PUSH the same path; a new entry will not be added to the history stack') : undefined; + setState(); + } + }); + } + + function replace(path, state) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(state === undefined, 'Hash history cannot replace state; it is ignored') : undefined; + var action = 'REPLACE'; + var location = createLocation(path, undefined, undefined, history.location); + transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) { + if (!ok) return; + var path = createPath(location); + var encodedPath = encodePath(basename + path); + var hashChanged = getHashPath() !== encodedPath; + + if (hashChanged) { + // We cannot tell if a hashchange was caused by a REPLACE, so we'd + // rather setState here and ignore the hashchange. The caveat here + // is that other hash histories in the page will consider it a POP. + ignorePath = path; + replaceHashPath(encodedPath); + } + + var prevIndex = allPaths.indexOf(createPath(history.location)); + if (prevIndex !== -1) allPaths[prevIndex] = path; + setState({ + action: action, + location: location + }); + }); + } + + function go(n) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(canGoWithoutReload, 'Hash history go(n) causes a full page reload in this browser') : undefined; + globalHistory.go(n); + } + + function goBack() { + go(-1); + } + + function goForward() { + go(1); + } + + var listenerCount = 0; + + function checkDOMListeners(delta) { + listenerCount += delta; + + if (listenerCount === 1 && delta === 1) { + window.addEventListener(HashChangeEvent$1, handleHashChange); + } else if (listenerCount === 0) { + window.removeEventListener(HashChangeEvent$1, handleHashChange); + } + } + + var isBlocked = false; + + function block(prompt) { + if (prompt === void 0) { + prompt = false; + } + + var unblock = transitionManager.setPrompt(prompt); + + if (!isBlocked) { + checkDOMListeners(1); + isBlocked = true; + } + + return function () { + if (isBlocked) { + isBlocked = false; + checkDOMListeners(-1); + } + + return unblock(); + }; + } + + function listen(listener) { + var unlisten = transitionManager.appendListener(listener); + checkDOMListeners(1); + return function () { + checkDOMListeners(-1); + unlisten(); + }; + } + + var history = { + length: globalHistory.length, + action: 'POP', + location: initialLocation, + createHref: createHref, + push: push, + replace: replace, + go: go, + goBack: goBack, + goForward: goForward, + block: block, + listen: listen + }; + return history; +} + +function clamp(n, lowerBound, upperBound) { + return Math.min(Math.max(n, lowerBound), upperBound); +} +/** + * Creates a history object that stores locations in memory. + */ + + +function createMemoryHistory(props) { + if (props === void 0) { + props = {}; + } + + var _props = props, + getUserConfirmation = _props.getUserConfirmation, + _props$initialEntries = _props.initialEntries, + initialEntries = _props$initialEntries === void 0 ? ['/'] : _props$initialEntries, + _props$initialIndex = _props.initialIndex, + initialIndex = _props$initialIndex === void 0 ? 0 : _props$initialIndex, + _props$keyLength = _props.keyLength, + keyLength = _props$keyLength === void 0 ? 6 : _props$keyLength; + var transitionManager = createTransitionManager(); + + function setState(nextState) { + Object(_babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__["default"])(history, nextState); + + history.length = history.entries.length; + transitionManager.notifyListeners(history.location, history.action); + } + + function createKey() { + return Math.random().toString(36).substr(2, keyLength); + } + + var index = clamp(initialIndex, 0, initialEntries.length - 1); + var entries = initialEntries.map(function (entry) { + return typeof entry === 'string' ? createLocation(entry, undefined, createKey()) : createLocation(entry, undefined, entry.key || createKey()); + }); // Public interface + + var createHref = createPath; + + function push(path, state) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined; + var action = 'PUSH'; + var location = createLocation(path, state, createKey(), history.location); + transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) { + if (!ok) return; + var prevIndex = history.index; + var nextIndex = prevIndex + 1; + var nextEntries = history.entries.slice(0); + + if (nextEntries.length > nextIndex) { + nextEntries.splice(nextIndex, nextEntries.length - nextIndex, location); + } else { + nextEntries.push(location); + } + + setState({ + action: action, + location: location, + index: nextIndex, + entries: nextEntries + }); + }); + } + + function replace(path, state) { + true ? Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])(!(typeof path === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored') : undefined; + var action = 'REPLACE'; + var location = createLocation(path, state, createKey(), history.location); + transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) { + if (!ok) return; + history.entries[history.index] = location; + setState({ + action: action, + location: location + }); + }); + } + + function go(n) { + var nextIndex = clamp(history.index + n, 0, history.entries.length - 1); + var action = 'POP'; + var location = history.entries[nextIndex]; + transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) { + if (ok) { + setState({ + action: action, + location: location, + index: nextIndex + }); + } else { + // Mimic the behavior of DOM histories by + // causing a render after a cancelled POP. + setState(); + } + }); + } + + function goBack() { + go(-1); + } + + function goForward() { + go(1); + } + + function canGo(n) { + var nextIndex = history.index + n; + return nextIndex >= 0 && nextIndex < history.entries.length; + } + + function block(prompt) { + if (prompt === void 0) { + prompt = false; + } + + return transitionManager.setPrompt(prompt); + } + + function listen(listener) { + return transitionManager.appendListener(listener); + } + + var history = { + length: entries.length, + action: 'POP', + location: entries[index], + index: index, + entries: entries, + createHref: createHref, + push: push, + replace: replace, + go: go, + goBack: goBack, + goForward: goForward, + canGo: canGo, + block: block, + listen: listen + }; + return history; +} + + + + +/***/ }), + +/***/ "./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js": +/*!**********************************************************************************!*\ + !*** ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js ***! + \**********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var reactIs = __webpack_require__(/*! react-is */ "./node_modules/react-is/index.js"); + +/** + * Copyright 2015, Yahoo! Inc. + * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +var REACT_STATICS = { + childContextTypes: true, + contextType: true, + contextTypes: true, + defaultProps: true, + displayName: true, + getDefaultProps: true, + getDerivedStateFromError: 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 FORWARD_REF_STATICS = { + '$$typeof': true, + render: true, + defaultProps: true, + displayName: true, + propTypes: true +}; +var MEMO_STATICS = { + '$$typeof': true, + compare: true, + defaultProps: true, + displayName: true, + propTypes: true, + type: true +}; +var TYPE_STATICS = {}; +TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS; +TYPE_STATICS[reactIs.Memo] = MEMO_STATICS; + +function getStatics(component) { + // React v16.11 and below + if (reactIs.isMemo(component)) { + return MEMO_STATICS; + } // React v16.12 and above + + + return TYPE_STATICS[component['$$typeof']] || REACT_STATICS; +} + +var defineProperty = Object.defineProperty; +var getOwnPropertyNames = Object.getOwnPropertyNames; +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; +var getPrototypeOf = Object.getPrototypeOf; +var objectPrototype = Object.prototype; +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)); + } + + var targetStatics = getStatics(targetComponent); + var sourceStatics = getStatics(sourceComponent); + + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + + if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { + var descriptor = getOwnPropertyDescriptor(sourceComponent, key); + + try { + // Avoid failures from read-only properties + defineProperty(targetComponent, key, descriptor); + } catch (e) {} + } + } + } + + return targetComponent; +} + +module.exports = hoistNonReactStatics; + + +/***/ }), + +/***/ "./node_modules/js-md5/src/md5.js": +/*!****************************************!*\ + !*** ./node_modules/js-md5/src/md5.js ***! + \****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/** + * [js-md5]{@link https://github.com/emn178/js-md5} + * + * @namespace md5 + * @version 0.7.3 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2017 + * @license MIT + */ +(function () { + 'use strict'; + + var ERROR = 'input is invalid type'; + var WINDOW = typeof window === 'object'; + var root = WINDOW ? window : {}; + if (root.JS_MD5_NO_WINDOW) { + WINDOW = false; + } + var WEB_WORKER = !WINDOW && typeof self === 'object'; + var NODE_JS = !root.JS_MD5_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; + if (NODE_JS) { + root = global; + } else if (WEB_WORKER) { + root = self; + } + var COMMON_JS = !root.JS_MD5_NO_COMMON_JS && typeof module === 'object' && module.exports; + var AMD = true && __webpack_require__(/*! !webpack amd options */ "./node_modules/webpack/buildin/amd-options.js"); + var ARRAY_BUFFER = !root.JS_MD5_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined'; + var HEX_CHARS = '0123456789abcdef'.split(''); + var EXTRA = [128, 32768, 8388608, -2147483648]; + var SHIFT = [0, 8, 16, 24]; + var OUTPUT_TYPES = ['hex', 'array', 'digest', 'buffer', 'arrayBuffer', 'base64']; + var BASE64_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + var blocks = [], buffer8; + if (ARRAY_BUFFER) { + var buffer = new ArrayBuffer(68); + buffer8 = new Uint8Array(buffer); + blocks = new Uint32Array(buffer); + } + + if (root.JS_MD5_NO_NODE_JS || !Array.isArray) { + Array.isArray = function (obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; + }; + } + + if (ARRAY_BUFFER && (root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { + ArrayBuffer.isView = function (obj) { + return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer; + }; + } + + /** + * @method hex + * @memberof md5 + * @description Output hash as hex string + * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash + * @returns {String} Hex string + * @example + * md5.hex('The quick brown fox jumps over the lazy dog'); + * // equal to + * md5('The quick brown fox jumps over the lazy dog'); + */ + /** + * @method digest + * @memberof md5 + * @description Output hash as bytes array + * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash + * @returns {Array} Bytes array + * @example + * md5.digest('The quick brown fox jumps over the lazy dog'); + */ + /** + * @method array + * @memberof md5 + * @description Output hash as bytes array + * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash + * @returns {Array} Bytes array + * @example + * md5.array('The quick brown fox jumps over the lazy dog'); + */ + /** + * @method arrayBuffer + * @memberof md5 + * @description Output hash as ArrayBuffer + * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash + * @returns {ArrayBuffer} ArrayBuffer + * @example + * md5.arrayBuffer('The quick brown fox jumps over the lazy dog'); + */ + /** + * @method buffer + * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead. + * @memberof md5 + * @description Output hash as ArrayBuffer + * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash + * @returns {ArrayBuffer} ArrayBuffer + * @example + * md5.buffer('The quick brown fox jumps over the lazy dog'); + */ + /** + * @method base64 + * @memberof md5 + * @description Output hash as base64 string + * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash + * @returns {String} base64 string + * @example + * md5.base64('The quick brown fox jumps over the lazy dog'); + */ + var createOutputMethod = function (outputType) { + return function (message) { + return new Md5(true).update(message)[outputType](); + }; + }; + + /** + * @method create + * @memberof md5 + * @description Create Md5 object + * @returns {Md5} Md5 object. + * @example + * var hash = md5.create(); + */ + /** + * @method update + * @memberof md5 + * @description Create and update Md5 object + * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash + * @returns {Md5} Md5 object. + * @example + * var hash = md5.update('The quick brown fox jumps over the lazy dog'); + * // equal to + * var hash = md5.create(); + * hash.update('The quick brown fox jumps over the lazy dog'); + */ + var createMethod = function () { + var method = createOutputMethod('hex'); + if (NODE_JS) { + method = nodeWrap(method); + } + method.create = function () { + return new Md5(); + }; + method.update = function (message) { + return method.create().update(message); + }; + for (var i = 0; i < OUTPUT_TYPES.length; ++i) { + var type = OUTPUT_TYPES[i]; + method[type] = createOutputMethod(type); + } + return method; + }; + + var nodeWrap = function (method) { + var crypto = eval("require('crypto')"); + var Buffer = eval("require('buffer').Buffer"); + var nodeMethod = function (message) { + if (typeof message === 'string') { + return crypto.createHash('md5').update(message, 'utf8').digest('hex'); + } else { + if (message === null || message === undefined) { + throw ERROR; + } else if (message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } + } + if (Array.isArray(message) || ArrayBuffer.isView(message) || + message.constructor === Buffer) { + return crypto.createHash('md5').update(new Buffer(message)).digest('hex'); + } else { + return method(message); + } + }; + return nodeMethod; + }; + + /** + * Md5 class + * @class Md5 + * @description This is internal class. + * @see {@link md5.create} + */ + function Md5(sharedMemory) { + if (sharedMemory) { + blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = + blocks[4] = blocks[5] = blocks[6] = blocks[7] = + blocks[8] = blocks[9] = blocks[10] = blocks[11] = + blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + this.blocks = blocks; + this.buffer8 = buffer8; + } else { + if (ARRAY_BUFFER) { + var buffer = new ArrayBuffer(68); + this.buffer8 = new Uint8Array(buffer); + this.blocks = new Uint32Array(buffer); + } else { + this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } + } + this.h0 = this.h1 = this.h2 = this.h3 = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + } + + /** + * @method update + * @memberof Md5 + * @instance + * @description Update hash + * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash + * @returns {Md5} Md5 object. + * @see {@link md5.update} + */ + Md5.prototype.update = function (message) { + if (this.finalized) { + return; + } + + var notString, type = typeof message; + if (type !== 'string') { + if (type === 'object') { + if (message === null) { + throw ERROR; + } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw ERROR; + } + } + } else { + throw ERROR; + } + notString = true; + } + var code, index = 0, i, length = message.length, blocks = this.blocks; + var buffer8 = this.buffer8; + + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks[0] = blocks[16]; + blocks[16] = blocks[1] = blocks[2] = blocks[3] = + blocks[4] = blocks[5] = blocks[6] = blocks[7] = + blocks[8] = blocks[9] = blocks[10] = blocks[11] = + blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + } + + if (notString) { + if (ARRAY_BUFFER) { + for (i = this.start; index < length && i < 64; ++index) { + buffer8[i++] = message[index]; + } + } else { + for (i = this.start; index < length && i < 64; ++index) { + blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; + } + } + } else { + if (ARRAY_BUFFER) { + for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + buffer8[i++] = code; + } else if (code < 0x800) { + buffer8[i++] = 0xc0 | (code >> 6); + buffer8[i++] = 0x80 | (code & 0x3f); + } else if (code < 0xd800 || code >= 0xe000) { + buffer8[i++] = 0xe0 | (code >> 12); + buffer8[i++] = 0x80 | ((code >> 6) & 0x3f); + buffer8[i++] = 0x80 | (code & 0x3f); + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + buffer8[i++] = 0xf0 | (code >> 18); + buffer8[i++] = 0x80 | ((code >> 12) & 0x3f); + buffer8[i++] = 0x80 | ((code >> 6) & 0x3f); + buffer8[i++] = 0x80 | (code & 0x3f); + } + } + } else { + for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 0x80) { + blocks[i >> 2] |= code << SHIFT[i++ & 3]; + } else if (code < 0x800) { + blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else if (code < 0xd800 || code >= 0xe000) { + blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } else { + code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); + blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; + blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; + } + } + } + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.start = i - 64; + this.hash(); + this.hashed = true; + } else { + this.start = i; + } + } + if (this.bytes > 4294967295) { + this.hBytes += this.bytes / 4294967296 << 0; + this.bytes = this.bytes % 4294967296; + } + return this; + }; + + Md5.prototype.finalize = function () { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i = this.lastByteIndex; + blocks[i >> 2] |= EXTRA[i & 3]; + if (i >= 56) { + if (!this.hashed) { + this.hash(); + } + blocks[0] = blocks[16]; + blocks[16] = blocks[1] = blocks[2] = blocks[3] = + blocks[4] = blocks[5] = blocks[6] = blocks[7] = + blocks[8] = blocks[9] = blocks[10] = blocks[11] = + blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + } + blocks[14] = this.bytes << 3; + blocks[15] = this.hBytes << 3 | this.bytes >>> 29; + this.hash(); + }; + + Md5.prototype.hash = function () { + var a, b, c, d, bc, da, blocks = this.blocks; + + if (this.first) { + a = blocks[0] - 680876937; + a = (a << 7 | a >>> 25) - 271733879 << 0; + d = (-1732584194 ^ a & 2004318071) + blocks[1] - 117830708; + d = (d << 12 | d >>> 20) + a << 0; + c = (-271733879 ^ (d & (a ^ -271733879))) + blocks[2] - 1126478375; + c = (c << 17 | c >>> 15) + d << 0; + b = (a ^ (c & (d ^ a))) + blocks[3] - 1316259209; + b = (b << 22 | b >>> 10) + c << 0; + } else { + a = this.h0; + b = this.h1; + c = this.h2; + d = this.h3; + a += (d ^ (b & (c ^ d))) + blocks[0] - 680876936; + a = (a << 7 | a >>> 25) + b << 0; + d += (c ^ (a & (b ^ c))) + blocks[1] - 389564586; + d = (d << 12 | d >>> 20) + a << 0; + c += (b ^ (d & (a ^ b))) + blocks[2] + 606105819; + c = (c << 17 | c >>> 15) + d << 0; + b += (a ^ (c & (d ^ a))) + blocks[3] - 1044525330; + b = (b << 22 | b >>> 10) + c << 0; + } + + a += (d ^ (b & (c ^ d))) + blocks[4] - 176418897; + a = (a << 7 | a >>> 25) + b << 0; + d += (c ^ (a & (b ^ c))) + blocks[5] + 1200080426; + d = (d << 12 | d >>> 20) + a << 0; + c += (b ^ (d & (a ^ b))) + blocks[6] - 1473231341; + c = (c << 17 | c >>> 15) + d << 0; + b += (a ^ (c & (d ^ a))) + blocks[7] - 45705983; + b = (b << 22 | b >>> 10) + c << 0; + a += (d ^ (b & (c ^ d))) + blocks[8] + 1770035416; + a = (a << 7 | a >>> 25) + b << 0; + d += (c ^ (a & (b ^ c))) + blocks[9] - 1958414417; + d = (d << 12 | d >>> 20) + a << 0; + c += (b ^ (d & (a ^ b))) + blocks[10] - 42063; + c = (c << 17 | c >>> 15) + d << 0; + b += (a ^ (c & (d ^ a))) + blocks[11] - 1990404162; + b = (b << 22 | b >>> 10) + c << 0; + a += (d ^ (b & (c ^ d))) + blocks[12] + 1804603682; + a = (a << 7 | a >>> 25) + b << 0; + d += (c ^ (a & (b ^ c))) + blocks[13] - 40341101; + d = (d << 12 | d >>> 20) + a << 0; + c += (b ^ (d & (a ^ b))) + blocks[14] - 1502002290; + c = (c << 17 | c >>> 15) + d << 0; + b += (a ^ (c & (d ^ a))) + blocks[15] + 1236535329; + b = (b << 22 | b >>> 10) + c << 0; + a += (c ^ (d & (b ^ c))) + blocks[1] - 165796510; + a = (a << 5 | a >>> 27) + b << 0; + d += (b ^ (c & (a ^ b))) + blocks[6] - 1069501632; + d = (d << 9 | d >>> 23) + a << 0; + c += (a ^ (b & (d ^ a))) + blocks[11] + 643717713; + c = (c << 14 | c >>> 18) + d << 0; + b += (d ^ (a & (c ^ d))) + blocks[0] - 373897302; + b = (b << 20 | b >>> 12) + c << 0; + a += (c ^ (d & (b ^ c))) + blocks[5] - 701558691; + a = (a << 5 | a >>> 27) + b << 0; + d += (b ^ (c & (a ^ b))) + blocks[10] + 38016083; + d = (d << 9 | d >>> 23) + a << 0; + c += (a ^ (b & (d ^ a))) + blocks[15] - 660478335; + c = (c << 14 | c >>> 18) + d << 0; + b += (d ^ (a & (c ^ d))) + blocks[4] - 405537848; + b = (b << 20 | b >>> 12) + c << 0; + a += (c ^ (d & (b ^ c))) + blocks[9] + 568446438; + a = (a << 5 | a >>> 27) + b << 0; + d += (b ^ (c & (a ^ b))) + blocks[14] - 1019803690; + d = (d << 9 | d >>> 23) + a << 0; + c += (a ^ (b & (d ^ a))) + blocks[3] - 187363961; + c = (c << 14 | c >>> 18) + d << 0; + b += (d ^ (a & (c ^ d))) + blocks[8] + 1163531501; + b = (b << 20 | b >>> 12) + c << 0; + a += (c ^ (d & (b ^ c))) + blocks[13] - 1444681467; + a = (a << 5 | a >>> 27) + b << 0; + d += (b ^ (c & (a ^ b))) + blocks[2] - 51403784; + d = (d << 9 | d >>> 23) + a << 0; + c += (a ^ (b & (d ^ a))) + blocks[7] + 1735328473; + c = (c << 14 | c >>> 18) + d << 0; + b += (d ^ (a & (c ^ d))) + blocks[12] - 1926607734; + b = (b << 20 | b >>> 12) + c << 0; + bc = b ^ c; + a += (bc ^ d) + blocks[5] - 378558; + a = (a << 4 | a >>> 28) + b << 0; + d += (bc ^ a) + blocks[8] - 2022574463; + d = (d << 11 | d >>> 21) + a << 0; + da = d ^ a; + c += (da ^ b) + blocks[11] + 1839030562; + c = (c << 16 | c >>> 16) + d << 0; + b += (da ^ c) + blocks[14] - 35309556; + b = (b << 23 | b >>> 9) + c << 0; + bc = b ^ c; + a += (bc ^ d) + blocks[1] - 1530992060; + a = (a << 4 | a >>> 28) + b << 0; + d += (bc ^ a) + blocks[4] + 1272893353; + d = (d << 11 | d >>> 21) + a << 0; + da = d ^ a; + c += (da ^ b) + blocks[7] - 155497632; + c = (c << 16 | c >>> 16) + d << 0; + b += (da ^ c) + blocks[10] - 1094730640; + b = (b << 23 | b >>> 9) + c << 0; + bc = b ^ c; + a += (bc ^ d) + blocks[13] + 681279174; + a = (a << 4 | a >>> 28) + b << 0; + d += (bc ^ a) + blocks[0] - 358537222; + d = (d << 11 | d >>> 21) + a << 0; + da = d ^ a; + c += (da ^ b) + blocks[3] - 722521979; + c = (c << 16 | c >>> 16) + d << 0; + b += (da ^ c) + blocks[6] + 76029189; + b = (b << 23 | b >>> 9) + c << 0; + bc = b ^ c; + a += (bc ^ d) + blocks[9] - 640364487; + a = (a << 4 | a >>> 28) + b << 0; + d += (bc ^ a) + blocks[12] - 421815835; + d = (d << 11 | d >>> 21) + a << 0; + da = d ^ a; + c += (da ^ b) + blocks[15] + 530742520; + c = (c << 16 | c >>> 16) + d << 0; + b += (da ^ c) + blocks[2] - 995338651; + b = (b << 23 | b >>> 9) + c << 0; + a += (c ^ (b | ~d)) + blocks[0] - 198630844; + a = (a << 6 | a >>> 26) + b << 0; + d += (b ^ (a | ~c)) + blocks[7] + 1126891415; + d = (d << 10 | d >>> 22) + a << 0; + c += (a ^ (d | ~b)) + blocks[14] - 1416354905; + c = (c << 15 | c >>> 17) + d << 0; + b += (d ^ (c | ~a)) + blocks[5] - 57434055; + b = (b << 21 | b >>> 11) + c << 0; + a += (c ^ (b | ~d)) + blocks[12] + 1700485571; + a = (a << 6 | a >>> 26) + b << 0; + d += (b ^ (a | ~c)) + blocks[3] - 1894986606; + d = (d << 10 | d >>> 22) + a << 0; + c += (a ^ (d | ~b)) + blocks[10] - 1051523; + c = (c << 15 | c >>> 17) + d << 0; + b += (d ^ (c | ~a)) + blocks[1] - 2054922799; + b = (b << 21 | b >>> 11) + c << 0; + a += (c ^ (b | ~d)) + blocks[8] + 1873313359; + a = (a << 6 | a >>> 26) + b << 0; + d += (b ^ (a | ~c)) + blocks[15] - 30611744; + d = (d << 10 | d >>> 22) + a << 0; + c += (a ^ (d | ~b)) + blocks[6] - 1560198380; + c = (c << 15 | c >>> 17) + d << 0; + b += (d ^ (c | ~a)) + blocks[13] + 1309151649; + b = (b << 21 | b >>> 11) + c << 0; + a += (c ^ (b | ~d)) + blocks[4] - 145523070; + a = (a << 6 | a >>> 26) + b << 0; + d += (b ^ (a | ~c)) + blocks[11] - 1120210379; + d = (d << 10 | d >>> 22) + a << 0; + c += (a ^ (d | ~b)) + blocks[2] + 718787259; + c = (c << 15 | c >>> 17) + d << 0; + b += (d ^ (c | ~a)) + blocks[9] - 343485551; + b = (b << 21 | b >>> 11) + c << 0; + + if (this.first) { + this.h0 = a + 1732584193 << 0; + this.h1 = b - 271733879 << 0; + this.h2 = c - 1732584194 << 0; + this.h3 = d + 271733878 << 0; + this.first = false; + } else { + this.h0 = this.h0 + a << 0; + this.h1 = this.h1 + b << 0; + this.h2 = this.h2 + c << 0; + this.h3 = this.h3 + d << 0; + } + }; + + /** + * @method hex + * @memberof Md5 + * @instance + * @description Output hash as hex string + * @returns {String} Hex string + * @see {@link md5.hex} + * @example + * hash.hex(); + */ + Md5.prototype.hex = function () { + this.finalize(); + + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3; + + return HEX_CHARS[(h0 >> 4) & 0x0F] + HEX_CHARS[h0 & 0x0F] + + HEX_CHARS[(h0 >> 12) & 0x0F] + HEX_CHARS[(h0 >> 8) & 0x0F] + + HEX_CHARS[(h0 >> 20) & 0x0F] + HEX_CHARS[(h0 >> 16) & 0x0F] + + HEX_CHARS[(h0 >> 28) & 0x0F] + HEX_CHARS[(h0 >> 24) & 0x0F] + + HEX_CHARS[(h1 >> 4) & 0x0F] + HEX_CHARS[h1 & 0x0F] + + HEX_CHARS[(h1 >> 12) & 0x0F] + HEX_CHARS[(h1 >> 8) & 0x0F] + + HEX_CHARS[(h1 >> 20) & 0x0F] + HEX_CHARS[(h1 >> 16) & 0x0F] + + HEX_CHARS[(h1 >> 28) & 0x0F] + HEX_CHARS[(h1 >> 24) & 0x0F] + + HEX_CHARS[(h2 >> 4) & 0x0F] + HEX_CHARS[h2 & 0x0F] + + HEX_CHARS[(h2 >> 12) & 0x0F] + HEX_CHARS[(h2 >> 8) & 0x0F] + + HEX_CHARS[(h2 >> 20) & 0x0F] + HEX_CHARS[(h2 >> 16) & 0x0F] + + HEX_CHARS[(h2 >> 28) & 0x0F] + HEX_CHARS[(h2 >> 24) & 0x0F] + + HEX_CHARS[(h3 >> 4) & 0x0F] + HEX_CHARS[h3 & 0x0F] + + HEX_CHARS[(h3 >> 12) & 0x0F] + HEX_CHARS[(h3 >> 8) & 0x0F] + + HEX_CHARS[(h3 >> 20) & 0x0F] + HEX_CHARS[(h3 >> 16) & 0x0F] + + HEX_CHARS[(h3 >> 28) & 0x0F] + HEX_CHARS[(h3 >> 24) & 0x0F]; + }; + + /** + * @method toString + * @memberof Md5 + * @instance + * @description Output hash as hex string + * @returns {String} Hex string + * @see {@link md5.hex} + * @example + * hash.toString(); + */ + Md5.prototype.toString = Md5.prototype.hex; + + /** + * @method digest + * @memberof Md5 + * @instance + * @description Output hash as bytes array + * @returns {Array} Bytes array + * @see {@link md5.digest} + * @example + * hash.digest(); + */ + Md5.prototype.digest = function () { + this.finalize(); + + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3; + return [ + h0 & 0xFF, (h0 >> 8) & 0xFF, (h0 >> 16) & 0xFF, (h0 >> 24) & 0xFF, + h1 & 0xFF, (h1 >> 8) & 0xFF, (h1 >> 16) & 0xFF, (h1 >> 24) & 0xFF, + h2 & 0xFF, (h2 >> 8) & 0xFF, (h2 >> 16) & 0xFF, (h2 >> 24) & 0xFF, + h3 & 0xFF, (h3 >> 8) & 0xFF, (h3 >> 16) & 0xFF, (h3 >> 24) & 0xFF + ]; + }; + + /** + * @method array + * @memberof Md5 + * @instance + * @description Output hash as bytes array + * @returns {Array} Bytes array + * @see {@link md5.array} + * @example + * hash.array(); + */ + Md5.prototype.array = Md5.prototype.digest; + + /** + * @method arrayBuffer + * @memberof Md5 + * @instance + * @description Output hash as ArrayBuffer + * @returns {ArrayBuffer} ArrayBuffer + * @see {@link md5.arrayBuffer} + * @example + * hash.arrayBuffer(); + */ + Md5.prototype.arrayBuffer = function () { + this.finalize(); + + var buffer = new ArrayBuffer(16); + var blocks = new Uint32Array(buffer); + blocks[0] = this.h0; + blocks[1] = this.h1; + blocks[2] = this.h2; + blocks[3] = this.h3; + return buffer; + }; + + /** + * @method buffer + * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead. + * @memberof Md5 + * @instance + * @description Output hash as ArrayBuffer + * @returns {ArrayBuffer} ArrayBuffer + * @see {@link md5.buffer} + * @example + * hash.buffer(); + */ + Md5.prototype.buffer = Md5.prototype.arrayBuffer; + + /** + * @method base64 + * @memberof Md5 + * @instance + * @description Output hash as base64 string + * @returns {String} base64 string + * @see {@link md5.base64} + * @example + * hash.base64(); + */ + Md5.prototype.base64 = function () { + var v1, v2, v3, base64Str = '', bytes = this.array(); + for (var i = 0; i < 15;) { + v1 = bytes[i++]; + v2 = bytes[i++]; + v3 = bytes[i++]; + base64Str += BASE64_ENCODE_CHAR[v1 >>> 2] + + BASE64_ENCODE_CHAR[(v1 << 4 | v2 >>> 4) & 63] + + BASE64_ENCODE_CHAR[(v2 << 2 | v3 >>> 6) & 63] + + BASE64_ENCODE_CHAR[v3 & 63]; + } + v1 = bytes[i]; + base64Str += BASE64_ENCODE_CHAR[v1 >>> 2] + + BASE64_ENCODE_CHAR[(v1 << 4) & 63] + + '=='; + return base64Str; + }; + + var exports = createMethod(); + + if (COMMON_JS) { + module.exports = exports; + } else { + /** + * @method md5 + * @description Md5 hash function, export to global in browsers. + * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash + * @returns {String} md5 hashes + * @example + * md5(''); // d41d8cd98f00b204e9800998ecf8427e + * md5('The quick brown fox jumps over the lazy dog'); // 9e107d9d372bb6826bd81d3542a419d6 + * md5('The quick brown fox jumps over the lazy dog.'); // e4d909c290d0fb1ca068ffaddf22cbd0 + * + * // It also supports UTF-8 encoding + * md5('中文'); // a7bac2239fcdcb3a067903d8077c4a07 + * + * // It also supports byte `Array`, `Uint8Array`, `ArrayBuffer` + * md5([]); // d41d8cd98f00b204e9800998ecf8427e + * md5(new Uint8Array([])); // d41d8cd98f00b204e9800998ecf8427e + */ + root.md5 = exports; + if (AMD) { + !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { + return exports; + }).call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } + } +})(); + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"), __webpack_require__(/*! ./../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/mini-create-react-context/dist/esm/index.js": +/*!******************************************************************!*\ + !*** ./node_modules/mini-create-react-context/dist/esm/index.js ***! + \******************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/inheritsLoose */ "./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js"); +/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! prop-types */ "./node_modules/prop-types/index.js"); +/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var tiny_warning__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! tiny-warning */ "./node_modules/tiny-warning/dist/tiny-warning.esm.js"); + + + + + +var MAX_SIGNED_31_BIT_INT = 1073741823; +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : {}; + +function getUniqueId() { + var key = '__global_unique_id__'; + return commonjsGlobal[key] = (commonjsGlobal[key] || 0) + 1; +} + +function objectIs(x, y) { + if (x === y) { + return x !== 0 || 1 / x === 1 / y; + } else { + return x !== x && y !== y; + } +} + +function createEventEmitter(value) { + var handlers = []; + return { + on: function on(handler) { + handlers.push(handler); + }, + off: function off(handler) { + handlers = handlers.filter(function (h) { + return h !== handler; + }); + }, + get: function get() { + return value; + }, + set: function set(newValue, changedBits) { + value = newValue; + handlers.forEach(function (handler) { + return handler(value, changedBits); + }); + } + }; +} + +function onlyChild(children) { + return Array.isArray(children) ? children[0] : children; +} + +function createReactContext(defaultValue, calculateChangedBits) { + var _Provider$childContex, _Consumer$contextType; + + var contextProp = '__create-react-context-' + getUniqueId() + '__'; + + var Provider = /*#__PURE__*/function (_Component) { + Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__["default"])(Provider, _Component); + + function Provider() { + var _this; + + _this = _Component.apply(this, arguments) || this; + _this.emitter = createEventEmitter(_this.props.value); + return _this; + } + + var _proto = Provider.prototype; + + _proto.getChildContext = function getChildContext() { + var _ref; + + return _ref = {}, _ref[contextProp] = this.emitter, _ref; + }; + + _proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { + if (this.props.value !== nextProps.value) { + var oldValue = this.props.value; + var newValue = nextProps.value; + var changedBits; + + if (objectIs(oldValue, newValue)) { + changedBits = 0; + } else { + changedBits = typeof calculateChangedBits === 'function' ? calculateChangedBits(oldValue, newValue) : MAX_SIGNED_31_BIT_INT; + + if (true) { + Object(tiny_warning__WEBPACK_IMPORTED_MODULE_3__["default"])((changedBits & MAX_SIGNED_31_BIT_INT) === changedBits, 'calculateChangedBits: Expected the return value to be a ' + '31-bit integer. Instead received: ' + changedBits); + } + + changedBits |= 0; + + if (changedBits !== 0) { + this.emitter.set(nextProps.value, changedBits); + } + } + } + }; + + _proto.render = function render() { + return this.props.children; + }; + + return Provider; + }(react__WEBPACK_IMPORTED_MODULE_0__["Component"]); + + Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[contextProp] = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object.isRequired, _Provider$childContex); + + var Consumer = /*#__PURE__*/function (_Component2) { + Object(_babel_runtime_helpers_esm_inheritsLoose__WEBPACK_IMPORTED_MODULE_1__["default"])(Consumer, _Component2); + + function Consumer() { + var _this2; + + _this2 = _Component2.apply(this, arguments) || this; + _this2.state = { + value: _this2.getValue() + }; + + _this2.onUpdate = function (newValue, changedBits) { + var observedBits = _this2.observedBits | 0; + + if ((observedBits & changedBits) !== 0) { + _this2.setState({ + value: _this2.getValue() + }); + } + }; + + return _this2; + } + + var _proto2 = Consumer.prototype; + + _proto2.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { + var observedBits = nextProps.observedBits; + this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits; + }; + + _proto2.componentDidMount = function componentDidMount() { + if (this.context[contextProp]) { + this.context[contextProp].on(this.onUpdate); + } + + var observedBits = this.props.observedBits; + this.observedBits = observedBits === undefined || observedBits === null ? MAX_SIGNED_31_BIT_INT : observedBits; + }; + + _proto2.componentWillUnmount = function componentWillUnmount() { + if (this.context[contextProp]) { + this.context[contextProp].off(this.onUpdate); + } + }; + + _proto2.getValue = function getValue() { + if (this.context[contextProp]) { + return this.context[contextProp].get(); + } else { + return defaultValue; + } + }; + + _proto2.render = function render() { + return onlyChild(this.props.children)(this.state.value); + }; + + return Consumer; + }(react__WEBPACK_IMPORTED_MODULE_0__["Component"]); + + Consumer.contextTypes = (_Consumer$contextType = {}, _Consumer$contextType[contextProp] = prop_types__WEBPACK_IMPORTED_MODULE_2___default.a.object, _Consumer$contextType); + return { + Provider: Provider, + Consumer: Consumer + }; +} + +var index = react__WEBPACK_IMPORTED_MODULE_0___default.a.createContext || createReactContext; + +/* harmony default export */ __webpack_exports__["default"] = (index); + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/object-assign/index.js": +/*!*********************************************!*\ + !*** ./node_modules/object-assign/index.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + + +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + + +/***/ }), + +/***/ "./node_modules/process/browser.js": +/*!*****************************************!*\ + !*** ./node_modules/process/browser.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), + +/***/ "./node_modules/prop-types/checkPropTypes.js": +/*!***************************************************!*\ + !*** ./node_modules/prop-types/checkPropTypes.js ***! + \***************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * 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. + */ + + + +var printWarning = function() {}; + +if (true) { + var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "./node_modules/prop-types/lib/ReactPropTypesSecret.js"); + var loggedTypeFailures = {}; + var has = Function.call.bind(Object.prototype.hasOwnProperty); + + printWarning = function(text) { + var message = 'Warning: ' + text; + if (typeof console !== 'undefined') { + console.error(message); + } + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + throw new Error(message); + } catch (x) {} + }; +} + +/** + * Assert that the values match with the type specs. + * Error messages are memorized and will only be shown once. + * + * @param {object} typeSpecs Map of name to a ReactPropType + * @param {object} values Runtime values that need to be type-checked + * @param {string} location e.g. "prop", "context", "child context" + * @param {string} componentName Name of the component for error messages. + * @param {?Function} getStack Returns the component stack. + * @private + */ +function checkPropTypes(typeSpecs, values, location, componentName, getStack) { + if (true) { + for (var typeSpecName in typeSpecs) { + if (has(typeSpecs, typeSpecName)) { + var error; + // Prop type validation may throw. In case they do, we don't want to + // fail the render phase where it didn't fail before. So we log it. + // After these have been cleaned up, we'll let them throw. + try { + // This is intentionally an invariant that gets caught. It's the same + // behavior as without this statement except with a better message. + if (typeof typeSpecs[typeSpecName] !== 'function') { + var err = Error( + (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + ); + err.name = 'Invariant Violation'; + throw err; + } + error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); + } catch (ex) { + error = ex; + } + if (error && !(error instanceof Error)) { + printWarning( + (componentName || 'React class') + ': type specification of ' + + location + ' `' + typeSpecName + '` is invalid; the type checker ' + + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + + 'You may have forgotten to pass an argument to the type checker ' + + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + + 'shape all require an argument).' + ); + } + if (error instanceof Error && !(error.message in loggedTypeFailures)) { + // Only monitor this failure once because there tends to be a lot of the + // same error. + loggedTypeFailures[error.message] = true; + + var stack = getStack ? getStack() : ''; + + printWarning( + 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') + ); + } + } + } + } +} + +/** + * Resets warning cache when testing. + * + * @private + */ +checkPropTypes.resetWarningCache = function() { + if (true) { + loggedTypeFailures = {}; + } +} + +module.exports = checkPropTypes; + + +/***/ }), + +/***/ "./node_modules/prop-types/factoryWithTypeCheckers.js": +/*!************************************************************!*\ + !*** ./node_modules/prop-types/factoryWithTypeCheckers.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * 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. + */ + + + +var ReactIs = __webpack_require__(/*! react-is */ "./node_modules/react-is/index.js"); +var assign = __webpack_require__(/*! object-assign */ "./node_modules/object-assign/index.js"); + +var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "./node_modules/prop-types/lib/ReactPropTypesSecret.js"); +var checkPropTypes = __webpack_require__(/*! ./checkPropTypes */ "./node_modules/prop-types/checkPropTypes.js"); + +var has = Function.call.bind(Object.prototype.hasOwnProperty); +var printWarning = function() {}; + +if (true) { + printWarning = function(text) { + var message = 'Warning: ' + text; + if (typeof console !== 'undefined') { + console.error(message); + } + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + throw new Error(message); + } catch (x) {} + }; +} + +function emptyFunctionThatReturnsNull() { + return null; +} + +module.exports = function(isValidElement, throwOnDirectAccess) { + /* global Symbol */ + var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; + var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. + + /** + * Returns the iterator method function contained on the iterable object. + * + * Be sure to invoke the function with the iterable as context: + * + * var iteratorFn = getIteratorFn(myIterable); + * if (iteratorFn) { + * var iterator = iteratorFn.call(myIterable); + * ... + * } + * + * @param {?object} maybeIterable + * @return {?function} + */ + function getIteratorFn(maybeIterable) { + var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); + if (typeof iteratorFn === 'function') { + return iteratorFn; + } + } + + /** + * Collection of methods that allow declaration and validation of props that are + * supplied to React components. Example usage: + * + * var Props = require('ReactPropTypes'); + * var MyArticle = React.createClass({ + * propTypes: { + * // An optional string prop named "description". + * description: Props.string, + * + * // A required enum prop named "category". + * category: Props.oneOf(['News','Photos']).isRequired, + * + * // A prop named "dialog" that requires an instance of Dialog. + * dialog: Props.instanceOf(Dialog).isRequired + * }, + * render: function() { ... } + * }); + * + * A more formal specification of how these methods are used: + * + * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) + * decl := ReactPropTypes.{type}(.isRequired)? + * + * Each and every declaration produces a function with the same signature. This + * allows the creation of custom validation functions. For example: + * + * var MyLink = React.createClass({ + * propTypes: { + * // An optional string or URI prop named "href". + * href: function(props, propName, componentName) { + * var propValue = props[propName]; + * if (propValue != null && typeof propValue !== 'string' && + * !(propValue instanceof URI)) { + * return new Error( + * 'Expected a string or an URI for ' + propName + ' in ' + + * componentName + * ); + * } + * } + * }, + * render: function() {...} + * }); + * + * @internal + */ + + var ANONYMOUS = '<>'; + + // Important! + // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. + var ReactPropTypes = { + array: createPrimitiveTypeChecker('array'), + bool: createPrimitiveTypeChecker('boolean'), + func: createPrimitiveTypeChecker('function'), + number: createPrimitiveTypeChecker('number'), + object: createPrimitiveTypeChecker('object'), + string: createPrimitiveTypeChecker('string'), + symbol: createPrimitiveTypeChecker('symbol'), + + any: createAnyTypeChecker(), + arrayOf: createArrayOfTypeChecker, + element: createElementTypeChecker(), + elementType: createElementTypeTypeChecker(), + instanceOf: createInstanceTypeChecker, + node: createNodeChecker(), + objectOf: createObjectOfTypeChecker, + oneOf: createEnumTypeChecker, + oneOfType: createUnionTypeChecker, + shape: createShapeTypeChecker, + exact: createStrictShapeTypeChecker, + }; + + /** + * inlined Object.is polyfill to avoid requiring consumers ship their own + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + */ + /*eslint-disable no-self-compare*/ + function is(x, y) { + // SameValue algorithm + if (x === y) { + // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + return x !== 0 || 1 / x === 1 / y; + } else { + // Step 6.a: NaN == NaN + return x !== x && y !== y; + } + } + /*eslint-enable no-self-compare*/ + + /** + * We use an Error-like object for backward compatibility as people may call + * PropTypes directly and inspect their output. However, we don't use real + * Errors anymore. We don't inspect their stack anyway, and creating them + * is prohibitively expensive if they are created too often, such as what + * happens in oneOfType() for any type before the one that matched. + */ + function PropTypeError(message) { + this.message = message; + this.stack = ''; + } + // Make `instanceof Error` still work for returned errors. + PropTypeError.prototype = Error.prototype; + + function createChainableTypeChecker(validate) { + if (true) { + var manualPropTypeCallCache = {}; + var manualPropTypeWarningCount = 0; + } + function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { + componentName = componentName || ANONYMOUS; + propFullName = propFullName || propName; + + if (secret !== ReactPropTypesSecret) { + if (throwOnDirectAccess) { + // New behavior only for users of `prop-types` package + var err = new Error( + 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + + 'Use `PropTypes.checkPropTypes()` to call them. ' + + 'Read more at http://fb.me/use-check-prop-types' + ); + err.name = 'Invariant Violation'; + throw err; + } else if ( true && typeof console !== 'undefined') { + // Old behavior for people using React.PropTypes + var cacheKey = componentName + ':' + propName; + if ( + !manualPropTypeCallCache[cacheKey] && + // Avoid spamming the console because they are often not actionable except for lib authors + manualPropTypeWarningCount < 3 + ) { + printWarning( + 'You are manually calling a React.PropTypes validation ' + + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + + 'and will throw in the standalone `prop-types` package. ' + + 'You may be seeing this warning due to a third-party PropTypes ' + + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' + ); + manualPropTypeCallCache[cacheKey] = true; + manualPropTypeWarningCount++; + } + } + } + if (props[propName] == null) { + if (isRequired) { + if (props[propName] === null) { + return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); + } + return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); + } + return null; + } else { + return validate(props, propName, componentName, location, propFullName); + } + } + + var chainedCheckType = checkType.bind(null, false); + chainedCheckType.isRequired = checkType.bind(null, true); + + return chainedCheckType; + } + + function createPrimitiveTypeChecker(expectedType) { + function validate(props, propName, componentName, location, propFullName, secret) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== expectedType) { + // `propValue` being instance of, say, date/regexp, pass the 'object' + // check, but we can offer a more precise error message here rather than + // 'of type `object`'. + var preciseType = getPreciseType(propValue); + + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createAnyTypeChecker() { + return createChainableTypeChecker(emptyFunctionThatReturnsNull); + } + + function createArrayOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + if (typeof typeChecker !== 'function') { + return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); + } + var propValue = props[propName]; + if (!Array.isArray(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); + } + for (var i = 0; i < propValue.length; i++) { + var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); + if (error instanceof Error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createElementTypeChecker() { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + if (!isValidElement(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createElementTypeTypeChecker() { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + if (!ReactIs.isValidElementType(propValue)) { + var propType = getPropType(propValue); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createInstanceTypeChecker(expectedClass) { + function validate(props, propName, componentName, location, propFullName) { + if (!(props[propName] instanceof expectedClass)) { + var expectedClassName = expectedClass.name || ANONYMOUS; + var actualClassName = getClassName(props[propName]); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createEnumTypeChecker(expectedValues) { + if (!Array.isArray(expectedValues)) { + if (true) { + if (arguments.length > 1) { + printWarning( + 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' + + 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).' + ); + } else { + printWarning('Invalid argument supplied to oneOf, expected an array.'); + } + } + return emptyFunctionThatReturnsNull; + } + + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + for (var i = 0; i < expectedValues.length; i++) { + if (is(propValue, expectedValues[i])) { + return null; + } + } + + var valuesString = JSON.stringify(expectedValues, function replacer(key, value) { + var type = getPreciseType(value); + if (type === 'symbol') { + return String(value); + } + return value; + }); + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); + } + return createChainableTypeChecker(validate); + } + + function createObjectOfTypeChecker(typeChecker) { + function validate(props, propName, componentName, location, propFullName) { + if (typeof typeChecker !== 'function') { + return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); + } + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); + } + for (var key in propValue) { + if (has(propValue, key)) { + var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); + if (error instanceof Error) { + return error; + } + } + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createUnionTypeChecker(arrayOfTypeCheckers) { + if (!Array.isArray(arrayOfTypeCheckers)) { + true ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : undefined; + return emptyFunctionThatReturnsNull; + } + + for (var i = 0; i < arrayOfTypeCheckers.length; i++) { + var checker = arrayOfTypeCheckers[i]; + if (typeof checker !== 'function') { + printWarning( + 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.' + ); + return emptyFunctionThatReturnsNull; + } + } + + function validate(props, propName, componentName, location, propFullName) { + for (var i = 0; i < arrayOfTypeCheckers.length; i++) { + var checker = arrayOfTypeCheckers[i]; + if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { + return null; + } + } + + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); + } + return createChainableTypeChecker(validate); + } + + function createNodeChecker() { + function validate(props, propName, componentName, location, propFullName) { + if (!isNode(props[propName])) { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createShapeTypeChecker(shapeTypes) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); + } + for (var key in shapeTypes) { + var checker = shapeTypes[key]; + if (!checker) { + continue; + } + var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); + if (error) { + return error; + } + } + return null; + } + return createChainableTypeChecker(validate); + } + + function createStrictShapeTypeChecker(shapeTypes) { + function validate(props, propName, componentName, location, propFullName) { + var propValue = props[propName]; + var propType = getPropType(propValue); + if (propType !== 'object') { + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); + } + // We need to check all keys in case some are required but missing from + // props. + var allKeys = assign({}, props[propName], shapeTypes); + for (var key in allKeys) { + var checker = shapeTypes[key]; + if (!checker) { + return new PropTypeError( + 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') + ); + } + var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); + if (error) { + return error; + } + } + return null; + } + + return createChainableTypeChecker(validate); + } + + function isNode(propValue) { + switch (typeof propValue) { + case 'number': + case 'string': + case 'undefined': + return true; + case 'boolean': + return !propValue; + case 'object': + if (Array.isArray(propValue)) { + return propValue.every(isNode); + } + if (propValue === null || isValidElement(propValue)) { + return true; + } + + var iteratorFn = getIteratorFn(propValue); + if (iteratorFn) { + var iterator = iteratorFn.call(propValue); + var step; + if (iteratorFn !== propValue.entries) { + while (!(step = iterator.next()).done) { + if (!isNode(step.value)) { + return false; + } + } + } else { + // Iterator will provide entry [k,v] tuples rather than values. + while (!(step = iterator.next()).done) { + var entry = step.value; + if (entry) { + if (!isNode(entry[1])) { + return false; + } + } + } + } + } else { + return false; + } + + return true; + default: + return false; + } + } + + function isSymbol(propType, propValue) { + // Native Symbol. + if (propType === 'symbol') { + return true; + } + + // falsy value can't be a Symbol + if (!propValue) { + return false; + } + + // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' + if (propValue['@@toStringTag'] === 'Symbol') { + return true; + } + + // Fallback for non-spec compliant Symbols which are polyfilled. + if (typeof Symbol === 'function' && propValue instanceof Symbol) { + return true; + } + + return false; + } + + // Equivalent of `typeof` but with special handling for array and regexp. + function getPropType(propValue) { + var propType = typeof propValue; + if (Array.isArray(propValue)) { + return 'array'; + } + if (propValue instanceof RegExp) { + // Old webkits (at least until Android 4.0) return 'function' rather than + // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ + // passes PropTypes.object. + return 'object'; + } + if (isSymbol(propType, propValue)) { + return 'symbol'; + } + return propType; + } + + // This handles more types than `getPropType`. Only used for error messages. + // See `createPrimitiveTypeChecker`. + function getPreciseType(propValue) { + if (typeof propValue === 'undefined' || propValue === null) { + return '' + propValue; + } + var propType = getPropType(propValue); + if (propType === 'object') { + if (propValue instanceof Date) { + return 'date'; + } else if (propValue instanceof RegExp) { + return 'regexp'; + } + } + return propType; + } + + // Returns a string that is postfixed to a warning about an invalid type. + // For example, "undefined" or "of type array" + function getPostfixForTypeWarning(value) { + var type = getPreciseType(value); + switch (type) { + case 'array': + case 'object': + return 'an ' + type; + case 'boolean': + case 'date': + case 'regexp': + return 'a ' + type; + default: + return type; + } + } + + // Returns class name of the object, if any. + function getClassName(propValue) { + if (!propValue.constructor || !propValue.constructor.name) { + return ANONYMOUS; + } + return propValue.constructor.name; + } + + ReactPropTypes.checkPropTypes = checkPropTypes; + ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache; + ReactPropTypes.PropTypes = ReactPropTypes; + + return ReactPropTypes; +}; + + +/***/ }), + +/***/ "./node_modules/prop-types/index.js": +/*!******************************************!*\ + !*** ./node_modules/prop-types/index.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * 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. + */ + +if (true) { + var ReactIs = __webpack_require__(/*! react-is */ "./node_modules/react-is/index.js"); + + // By explicitly using `prop-types` you are opting into new development behavior. + // http://fb.me/prop-types-in-prod + var throwOnDirectAccess = true; + module.exports = __webpack_require__(/*! ./factoryWithTypeCheckers */ "./node_modules/prop-types/factoryWithTypeCheckers.js")(ReactIs.isElement, throwOnDirectAccess); +} else {} + + +/***/ }), + +/***/ "./node_modules/prop-types/lib/ReactPropTypesSecret.js": +/*!*************************************************************!*\ + !*** ./node_modules/prop-types/lib/ReactPropTypesSecret.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** + * 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. + */ + + + +var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; + +module.exports = ReactPropTypesSecret; + + +/***/ }), + +/***/ "./node_modules/react-dom/cjs/react-dom.development.js": +/*!*************************************************************!*\ + !*** ./node_modules/react-dom/cjs/react-dom.development.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/** @license React v16.13.1 + * react-dom.development.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + + + +if (true) { + (function() { +'use strict'; + +var React = __webpack_require__(/*! react */ "./node_modules/react/index.js"); +var _assign = __webpack_require__(/*! object-assign */ "./node_modules/object-assign/index.js"); +var Scheduler = __webpack_require__(/*! scheduler */ "./node_modules/scheduler/index.js"); +var checkPropTypes = __webpack_require__(/*! prop-types/checkPropTypes */ "./node_modules/prop-types/checkPropTypes.js"); +var tracing = __webpack_require__(/*! scheduler/tracing */ "./node_modules/scheduler/tracing.js"); + +var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions. +// Current owner and dispatcher used to share the same ref, +// but PR #14548 split them out to better support the react-debug-tools package. + +if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) { + ReactSharedInternals.ReactCurrentDispatcher = { + current: null + }; +} + +if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) { + ReactSharedInternals.ReactCurrentBatchConfig = { + suspense: null + }; +} + +// by calls to these methods by a Babel plugin. +// +// In PROD (or in packages without access to React internals), +// they are left as they are instead. + +function warn(format) { + { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + printWarning('warn', format, args); + } +} +function error(format) { + { + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; + } + + printWarning('error', format, args); + } +} + +function printWarning(level, format, args) { + // When changing this logic, you might want to also + // update consoleWithStackDev.www.js as well. + { + var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n in') === 0; + + if (!hasExistingStack) { + var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; + var stack = ReactDebugCurrentFrame.getStackAddendum(); + + if (stack !== '') { + format += '%s'; + args = args.concat([stack]); + } + } + + var argsWithFormat = args.map(function (item) { + return '' + item; + }); // Careful: RN currently depends on this prefix + + argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it + // breaks IE9: https://github.com/facebook/react/issues/13610 + // eslint-disable-next-line react-internal/no-production-logging + + Function.prototype.apply.call(console[level], console, argsWithFormat); + + try { + // --- Welcome to debugging React --- + // This error was thrown as a convenience so that you can use this stack + // to find the callsite that caused this warning to fire. + var argIndex = 0; + var message = 'Warning: ' + format.replace(/%s/g, function () { + return args[argIndex++]; + }); + throw new Error(message); + } catch (x) {} + } +} + +if (!React) { + { + throw Error( "ReactDOM was loaded before React. Make sure you load the React package before loading ReactDOM." ); + } +} + +var invokeGuardedCallbackImpl = function (name, func, context, a, b, c, d, e, f) { + var funcArgs = Array.prototype.slice.call(arguments, 3); + + try { + func.apply(context, funcArgs); + } catch (error) { + this.onError(error); + } +}; + +{ + // In DEV mode, we swap out invokeGuardedCallback for a special version + // that plays more nicely with the browser's DevTools. The idea is to preserve + // "Pause on exceptions" behavior. Because React wraps all user-provided + // functions in invokeGuardedCallback, and the production version of + // invokeGuardedCallback uses a try-catch, all user exceptions are treated + // like caught exceptions, and the DevTools won't pause unless the developer + // takes the extra step of enabling pause on caught exceptions. This is + // unintuitive, though, because even though React has caught the error, from + // the developer's perspective, the error is uncaught. + // + // To preserve the expected "Pause on exceptions" behavior, we don't use a + // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake + // DOM node, and call the user-provided callback from inside an event handler + // for that fake event. If the callback throws, the error is "captured" using + // a global event handler. But because the error happens in a different + // event loop context, it does not interrupt the normal program flow. + // Effectively, this gives us try-catch behavior without actually using + // try-catch. Neat! + // Check that the browser supports the APIs we need to implement our special + // DEV version of invokeGuardedCallback + if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { + var fakeNode = document.createElement('react'); + + var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) { + // If document doesn't exist we know for sure we will crash in this method + // when we call document.createEvent(). However this can cause confusing + // errors: https://github.com/facebookincubator/create-react-app/issues/3482 + // So we preemptively throw with a better message instead. + if (!(typeof document !== 'undefined')) { + { + throw Error( "The `document` global was defined when React was initialized, but is not defined anymore. This can happen in a test environment if a component schedules an update from an asynchronous callback, but the test has already finished running. To solve this, you can either unmount the component at the end of your test (and ensure that any asynchronous operations get canceled in `componentWillUnmount`), or you can change the test itself to be asynchronous." ); + } + } + + var evt = document.createEvent('Event'); // Keeps track of whether the user-provided callback threw an error. We + // set this to true at the beginning, then set it to false right after + // calling the function. If the function errors, `didError` will never be + // set to false. This strategy works even if the browser is flaky and + // fails to call our global error handler, because it doesn't rely on + // the error event at all. + + var didError = true; // Keeps track of the value of window.event so that we can reset it + // during the callback to let user code access window.event in the + // browsers that support it. + + var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event + // dispatching: https://github.com/facebook/react/issues/13688 + + var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event'); // Create an event handler for our fake event. We will synchronously + // dispatch our fake event using `dispatchEvent`. Inside the handler, we + // call the user-provided callback. + + var funcArgs = Array.prototype.slice.call(arguments, 3); + + function callCallback() { + // We immediately remove the callback from event listeners so that + // nested `invokeGuardedCallback` calls do not clash. Otherwise, a + // nested call would trigger the fake event handlers of any call higher + // in the stack. + fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the + // window.event assignment in both IE <= 10 as they throw an error + // "Member not found" in strict mode, and in Firefox which does not + // support window.event. + + if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) { + window.event = windowEvent; + } + + func.apply(context, funcArgs); + didError = false; + } // Create a global error event handler. We use this to capture the value + // that was thrown. It's possible that this error handler will fire more + // than once; for example, if non-React code also calls `dispatchEvent` + // and a handler for that event throws. We should be resilient to most of + // those cases. Even if our error event handler fires more than once, the + // last error event is always used. If the callback actually does error, + // we know that the last error event is the correct one, because it's not + // possible for anything else to have happened in between our callback + // erroring and the code that follows the `dispatchEvent` call below. If + // the callback doesn't error, but the error event was fired, we know to + // ignore it because `didError` will be false, as described above. + + + var error; // Use this to track whether the error event is ever called. + + var didSetError = false; + var isCrossOriginError = false; + + function handleWindowError(event) { + error = event.error; + didSetError = true; + + if (error === null && event.colno === 0 && event.lineno === 0) { + isCrossOriginError = true; + } + + if (event.defaultPrevented) { + // Some other error handler has prevented default. + // Browsers silence the error report if this happens. + // We'll remember this to later decide whether to log it or not. + if (error != null && typeof error === 'object') { + try { + error._suppressLogging = true; + } catch (inner) {// Ignore. + } + } + } + } // Create a fake event type. + + + var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers + + window.addEventListener('error', handleWindowError); + fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function + // errors, it will trigger our global error handler. + + evt.initEvent(evtType, false, false); + fakeNode.dispatchEvent(evt); + + if (windowEventDescriptor) { + Object.defineProperty(window, 'event', windowEventDescriptor); + } + + if (didError) { + if (!didSetError) { + // The callback errored, but the error event never fired. + error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); + } else if (isCrossOriginError) { + error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.'); + } + + this.onError(error); + } // Remove our event listeners + + + window.removeEventListener('error', handleWindowError); + }; + + invokeGuardedCallbackImpl = invokeGuardedCallbackDev; + } +} + +var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl; + +var hasError = false; +var caughtError = null; // Used by event system to capture/rethrow the first error. + +var hasRethrowError = false; +var rethrowError = null; +var reporter = { + onError: function (error) { + hasError = true; + caughtError = error; + } +}; +/** + * Call a function while guarding against errors that happens within it. + * Returns an error if it throws, otherwise null. + * + * In production, this is implemented using a try-catch. The reason we don't + * use a try-catch directly is so that we can swap out a different + * implementation in DEV mode. + * + * @param {String} name of the guard to use for logging or debugging + * @param {Function} func The function to invoke + * @param {*} context The context to use when calling the function + * @param {...*} args Arguments for function + */ + +function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) { + hasError = false; + caughtError = null; + invokeGuardedCallbackImpl$1.apply(reporter, arguments); +} +/** + * Same as invokeGuardedCallback, but instead of returning an error, it stores + * it in a global so it can be rethrown by `rethrowCaughtError` later. + * TODO: See if caughtError and rethrowError can be unified. + * + * @param {String} name of the guard to use for logging or debugging + * @param {Function} func The function to invoke + * @param {*} context The context to use when calling the function + * @param {...*} args Arguments for function + */ + +function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) { + invokeGuardedCallback.apply(this, arguments); + + if (hasError) { + var error = clearCaughtError(); + + if (!hasRethrowError) { + hasRethrowError = true; + rethrowError = error; + } + } +} +/** + * During execution of guarded functions we will capture the first error which + * we will rethrow to be handled by the top level error handler. + */ + +function rethrowCaughtError() { + if (hasRethrowError) { + var error = rethrowError; + hasRethrowError = false; + rethrowError = null; + throw error; + } +} +function hasCaughtError() { + return hasError; +} +function clearCaughtError() { + if (hasError) { + var error = caughtError; + hasError = false; + caughtError = null; + return error; + } else { + { + { + throw Error( "clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue." ); + } + } + } +} + +var getFiberCurrentPropsFromNode = null; +var getInstanceFromNode = null; +var getNodeFromInstance = null; +function setComponentTree(getFiberCurrentPropsFromNodeImpl, getInstanceFromNodeImpl, getNodeFromInstanceImpl) { + getFiberCurrentPropsFromNode = getFiberCurrentPropsFromNodeImpl; + getInstanceFromNode = getInstanceFromNodeImpl; + getNodeFromInstance = getNodeFromInstanceImpl; + + { + if (!getNodeFromInstance || !getInstanceFromNode) { + error('EventPluginUtils.setComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.'); + } + } +} +var validateEventDispatches; + +{ + validateEventDispatches = function (event) { + var dispatchListeners = event._dispatchListeners; + var dispatchInstances = event._dispatchInstances; + var listenersIsArr = Array.isArray(dispatchListeners); + var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; + var instancesIsArr = Array.isArray(dispatchInstances); + var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; + + if (instancesIsArr !== listenersIsArr || instancesLen !== listenersLen) { + error('EventPluginUtils: Invalid `event`.'); + } + }; +} +/** + * Dispatch the event to the listener. + * @param {SyntheticEvent} event SyntheticEvent to handle + * @param {function} listener Application-level callback + * @param {*} inst Internal component instance + */ + + +function executeDispatch(event, listener, inst) { + var type = event.type || 'unknown-event'; + event.currentTarget = getNodeFromInstance(inst); + invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); + event.currentTarget = null; +} +/** + * Standard/simple iteration through an event's collected dispatches. + */ + +function executeDispatchesInOrder(event) { + var dispatchListeners = event._dispatchListeners; + var dispatchInstances = event._dispatchInstances; + + { + validateEventDispatches(event); + } + + if (Array.isArray(dispatchListeners)) { + for (var i = 0; i < dispatchListeners.length; i++) { + if (event.isPropagationStopped()) { + break; + } // Listeners and Instances are two parallel arrays that are always in sync. + + + executeDispatch(event, dispatchListeners[i], dispatchInstances[i]); + } + } else if (dispatchListeners) { + executeDispatch(event, dispatchListeners, dispatchInstances); + } + + event._dispatchListeners = null; + event._dispatchInstances = null; +} + +var FunctionComponent = 0; +var ClassComponent = 1; +var IndeterminateComponent = 2; // Before we know whether it is function or class + +var HostRoot = 3; // Root of a host tree. Could be nested inside another node. + +var HostPortal = 4; // A subtree. Could be an entry point to a different renderer. + +var HostComponent = 5; +var HostText = 6; +var Fragment = 7; +var Mode = 8; +var ContextConsumer = 9; +var ContextProvider = 10; +var ForwardRef = 11; +var Profiler = 12; +var SuspenseComponent = 13; +var MemoComponent = 14; +var SimpleMemoComponent = 15; +var LazyComponent = 16; +var IncompleteClassComponent = 17; +var DehydratedFragment = 18; +var SuspenseListComponent = 19; +var FundamentalComponent = 20; +var ScopeComponent = 21; +var Block = 22; + +/** + * Injectable ordering of event plugins. + */ +var eventPluginOrder = null; +/** + * Injectable mapping from names to event plugin modules. + */ + +var namesToPlugins = {}; +/** + * Recomputes the plugin list using the injected plugins and plugin ordering. + * + * @private + */ + +function recomputePluginOrdering() { + if (!eventPluginOrder) { + // Wait until an `eventPluginOrder` is injected. + return; + } + + for (var pluginName in namesToPlugins) { + var pluginModule = namesToPlugins[pluginName]; + var pluginIndex = eventPluginOrder.indexOf(pluginName); + + if (!(pluginIndex > -1)) { + { + throw Error( "EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `" + pluginName + "`." ); + } + } + + if (plugins[pluginIndex]) { + continue; + } + + if (!pluginModule.extractEvents) { + { + throw Error( "EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `" + pluginName + "` does not." ); + } + } + + plugins[pluginIndex] = pluginModule; + var publishedEvents = pluginModule.eventTypes; + + for (var eventName in publishedEvents) { + if (!publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName)) { + { + throw Error( "EventPluginRegistry: Failed to publish event `" + eventName + "` for plugin `" + pluginName + "`." ); + } + } + } + } +} +/** + * Publishes an event so that it can be dispatched by the supplied plugin. + * + * @param {object} dispatchConfig Dispatch configuration for the event. + * @param {object} PluginModule Plugin publishing the event. + * @return {boolean} True if the event was successfully published. + * @private + */ + + +function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { + if (!!eventNameDispatchConfigs.hasOwnProperty(eventName)) { + { + throw Error( "EventPluginRegistry: More than one plugin attempted to publish the same event name, `" + eventName + "`." ); + } + } + + eventNameDispatchConfigs[eventName] = dispatchConfig; + var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; + + if (phasedRegistrationNames) { + for (var phaseName in phasedRegistrationNames) { + if (phasedRegistrationNames.hasOwnProperty(phaseName)) { + var phasedRegistrationName = phasedRegistrationNames[phaseName]; + publishRegistrationName(phasedRegistrationName, pluginModule, eventName); + } + } + + return true; + } else if (dispatchConfig.registrationName) { + publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); + return true; + } + + return false; +} +/** + * Publishes a registration name that is used to identify dispatched events. + * + * @param {string} registrationName Registration name to add. + * @param {object} PluginModule Plugin publishing the event. + * @private + */ + + +function publishRegistrationName(registrationName, pluginModule, eventName) { + if (!!registrationNameModules[registrationName]) { + { + throw Error( "EventPluginRegistry: More than one plugin attempted to publish the same registration name, `" + registrationName + "`." ); + } + } + + registrationNameModules[registrationName] = pluginModule; + registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; + + { + var lowerCasedName = registrationName.toLowerCase(); + possibleRegistrationNames[lowerCasedName] = registrationName; + + if (registrationName === 'onDoubleClick') { + possibleRegistrationNames.ondblclick = registrationName; + } + } +} +/** + * Registers plugins so that they can extract and dispatch events. + */ + +/** + * Ordered list of injected plugins. + */ + + +var plugins = []; +/** + * Mapping from event name to dispatch config + */ + +var eventNameDispatchConfigs = {}; +/** + * Mapping from registration name to plugin module + */ + +var registrationNameModules = {}; +/** + * Mapping from registration name to event name + */ + +var registrationNameDependencies = {}; +/** + * Mapping from lowercase registration names to the properly cased version, + * used to warn in the case of missing event handlers. Available + * only in true. + * @type {Object} + */ + +var possibleRegistrationNames = {} ; // Trust the developer to only use possibleRegistrationNames in true + +/** + * Injects an ordering of plugins (by plugin name). This allows the ordering + * to be decoupled from injection of the actual plugins so that ordering is + * always deterministic regardless of packaging, on-the-fly injection, etc. + * + * @param {array} InjectedEventPluginOrder + * @internal + */ + +function injectEventPluginOrder(injectedEventPluginOrder) { + if (!!eventPluginOrder) { + { + throw Error( "EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React." ); + } + } // Clone the ordering so it cannot be dynamically mutated. + + + eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); + recomputePluginOrdering(); +} +/** + * Injects plugins to be used by plugin event system. The plugin names must be + * in the ordering injected by `injectEventPluginOrder`. + * + * Plugins can be injected as part of page initialization or on-the-fly. + * + * @param {object} injectedNamesToPlugins Map from names to plugin modules. + * @internal + */ + +function injectEventPluginsByName(injectedNamesToPlugins) { + var isOrderingDirty = false; + + for (var pluginName in injectedNamesToPlugins) { + if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { + continue; + } + + var pluginModule = injectedNamesToPlugins[pluginName]; + + if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { + if (!!namesToPlugins[pluginName]) { + { + throw Error( "EventPluginRegistry: Cannot inject two different event plugins using the same name, `" + pluginName + "`." ); + } + } + + namesToPlugins[pluginName] = pluginModule; + isOrderingDirty = true; + } + } + + if (isOrderingDirty) { + recomputePluginOrdering(); + } +} + +var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined'); + +var PLUGIN_EVENT_SYSTEM = 1; +var IS_REPLAYED = 1 << 5; +var IS_FIRST_ANCESTOR = 1 << 6; + +var restoreImpl = null; +var restoreTarget = null; +var restoreQueue = null; + +function restoreStateOfTarget(target) { + // We perform this translation at the end of the event loop so that we + // always receive the correct fiber here + var internalInstance = getInstanceFromNode(target); + + if (!internalInstance) { + // Unmounted + return; + } + + if (!(typeof restoreImpl === 'function')) { + { + throw Error( "setRestoreImplementation() needs to be called to handle a target for controlled events. This error is likely caused by a bug in React. Please file an issue." ); + } + } + + var stateNode = internalInstance.stateNode; // Guard against Fiber being unmounted. + + if (stateNode) { + var _props = getFiberCurrentPropsFromNode(stateNode); + + restoreImpl(internalInstance.stateNode, internalInstance.type, _props); + } +} + +function setRestoreImplementation(impl) { + restoreImpl = impl; +} +function enqueueStateRestore(target) { + if (restoreTarget) { + if (restoreQueue) { + restoreQueue.push(target); + } else { + restoreQueue = [target]; + } + } else { + restoreTarget = target; + } +} +function needsStateRestore() { + return restoreTarget !== null || restoreQueue !== null; +} +function restoreStateIfNeeded() { + if (!restoreTarget) { + return; + } + + var target = restoreTarget; + var queuedTargets = restoreQueue; + restoreTarget = null; + restoreQueue = null; + restoreStateOfTarget(target); + + if (queuedTargets) { + for (var i = 0; i < queuedTargets.length; i++) { + restoreStateOfTarget(queuedTargets[i]); + } + } +} + +var enableProfilerTimer = true; // Trace which interactions trigger each commit. + +var enableDeprecatedFlareAPI = false; // Experimental Host Component support. + +var enableFundamentalAPI = false; // Experimental Scope support. +var warnAboutStringRefs = false; + +// the renderer. Such as when we're dispatching events or if third party +// libraries need to call batchedUpdates. Eventually, this API will go away when +// everything is batched by default. We'll then have a similar API to opt-out of +// scheduled work and instead do synchronous work. +// Defaults + +var batchedUpdatesImpl = function (fn, bookkeeping) { + return fn(bookkeeping); +}; + +var discreteUpdatesImpl = function (fn, a, b, c, d) { + return fn(a, b, c, d); +}; + +var flushDiscreteUpdatesImpl = function () {}; + +var batchedEventUpdatesImpl = batchedUpdatesImpl; +var isInsideEventHandler = false; +var isBatchingEventUpdates = false; + +function finishEventHandler() { + // Here we wait until all updates have propagated, which is important + // when using controlled components within layers: + // https://github.com/facebook/react/issues/1698 + // Then we restore state of any controlled component. + var controlledComponentsHavePendingUpdates = needsStateRestore(); + + if (controlledComponentsHavePendingUpdates) { + // If a controlled event was fired, we may need to restore the state of + // the DOM node back to the controlled value. This is necessary when React + // bails out of the update without touching the DOM. + flushDiscreteUpdatesImpl(); + restoreStateIfNeeded(); + } +} + +function batchedUpdates(fn, bookkeeping) { + if (isInsideEventHandler) { + // If we are currently inside another batch, we need to wait until it + // fully completes before restoring state. + return fn(bookkeeping); + } + + isInsideEventHandler = true; + + try { + return batchedUpdatesImpl(fn, bookkeeping); + } finally { + isInsideEventHandler = false; + finishEventHandler(); + } +} +function batchedEventUpdates(fn, a, b) { + if (isBatchingEventUpdates) { + // If we are currently inside another batch, we need to wait until it + // fully completes before restoring state. + return fn(a, b); + } + + isBatchingEventUpdates = true; + + try { + return batchedEventUpdatesImpl(fn, a, b); + } finally { + isBatchingEventUpdates = false; + finishEventHandler(); + } +} // This is for the React Flare event system +function discreteUpdates(fn, a, b, c, d) { + var prevIsInsideEventHandler = isInsideEventHandler; + isInsideEventHandler = true; + + try { + return discreteUpdatesImpl(fn, a, b, c, d); + } finally { + isInsideEventHandler = prevIsInsideEventHandler; + + if (!isInsideEventHandler) { + finishEventHandler(); + } + } +} +function flushDiscreteUpdatesIfNeeded(timeStamp) { + // event.timeStamp isn't overly reliable due to inconsistencies in + // how different browsers have historically provided the time stamp. + // Some browsers provide high-resolution time stamps for all events, + // some provide low-resolution time stamps for all events. FF < 52 + // even mixes both time stamps together. Some browsers even report + // negative time stamps or time stamps that are 0 (iOS9) in some cases. + // Given we are only comparing two time stamps with equality (!==), + // we are safe from the resolution differences. If the time stamp is 0 + // we bail-out of preventing the flush, which can affect semantics, + // such as if an earlier flush removes or adds event listeners that + // are fired in the subsequent flush. However, this is the same + // behaviour as we had before this change, so the risks are low. + if (!isInsideEventHandler && (!enableDeprecatedFlareAPI )) { + flushDiscreteUpdatesImpl(); + } +} +function setBatchingImplementation(_batchedUpdatesImpl, _discreteUpdatesImpl, _flushDiscreteUpdatesImpl, _batchedEventUpdatesImpl) { + batchedUpdatesImpl = _batchedUpdatesImpl; + discreteUpdatesImpl = _discreteUpdatesImpl; + flushDiscreteUpdatesImpl = _flushDiscreteUpdatesImpl; + batchedEventUpdatesImpl = _batchedEventUpdatesImpl; +} + +var DiscreteEvent = 0; +var UserBlockingEvent = 1; +var ContinuousEvent = 2; + +// A reserved attribute. +// It is handled by React separately and shouldn't be written to the DOM. +var RESERVED = 0; // A simple string attribute. +// Attributes that aren't in the whitelist are presumed to have this type. + +var STRING = 1; // A string attribute that accepts booleans in React. In HTML, these are called +// "enumerated" attributes with "true" and "false" as possible values. +// When true, it should be set to a "true" string. +// When false, it should be set to a "false" string. + +var BOOLEANISH_STRING = 2; // A real boolean attribute. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. + +var BOOLEAN = 3; // An attribute that can be used as a flag as well as with a value. +// When true, it should be present (set either to an empty string or its name). +// When false, it should be omitted. +// For any other value, should be present with that value. + +var OVERLOADED_BOOLEAN = 4; // An attribute that must be numeric or parse as a numeric. +// When falsy, it should be removed. + +var NUMERIC = 5; // An attribute that must be positive numeric or parse as a positive numeric. +// When falsy, it should be removed. + +var POSITIVE_NUMERIC = 6; + +/* eslint-disable max-len */ +var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; +/* eslint-enable max-len */ + +var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; +var ROOT_ATTRIBUTE_NAME = 'data-reactroot'; +var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + ATTRIBUTE_NAME_START_CHAR + '][' + ATTRIBUTE_NAME_CHAR + ']*$'); +var hasOwnProperty = Object.prototype.hasOwnProperty; +var illegalAttributeNameCache = {}; +var validatedAttributeNameCache = {}; +function isAttributeNameSafe(attributeName) { + if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { + return true; + } + + if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { + return false; + } + + if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { + validatedAttributeNameCache[attributeName] = true; + return true; + } + + illegalAttributeNameCache[attributeName] = true; + + { + error('Invalid attribute name: `%s`', attributeName); + } + + return false; +} +function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null) { + return propertyInfo.type === RESERVED; + } + + if (isCustomComponentTag) { + return false; + } + + if (name.length > 2 && (name[0] === 'o' || name[0] === 'O') && (name[1] === 'n' || name[1] === 'N')) { + return true; + } + + return false; +} +function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { + if (propertyInfo !== null && propertyInfo.type === RESERVED) { + return false; + } + + switch (typeof value) { + case 'function': // $FlowIssue symbol is perfectly valid here + + case 'symbol': + // eslint-disable-line + return true; + + case 'boolean': + { + if (isCustomComponentTag) { + return false; + } + + if (propertyInfo !== null) { + return !propertyInfo.acceptsBooleans; + } else { + var prefix = name.toLowerCase().slice(0, 5); + return prefix !== 'data-' && prefix !== 'aria-'; + } + } + + default: + return false; + } +} +function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { + if (value === null || typeof value === 'undefined') { + return true; + } + + if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { + return true; + } + + if (isCustomComponentTag) { + return false; + } + + if (propertyInfo !== null) { + switch (propertyInfo.type) { + case BOOLEAN: + return !value; + + case OVERLOADED_BOOLEAN: + return value === false; + + case NUMERIC: + return isNaN(value); + + case POSITIVE_NUMERIC: + return isNaN(value) || value < 1; + } + } + + return false; +} +function getPropertyInfo(name) { + return properties.hasOwnProperty(name) ? properties[name] : null; +} + +function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL) { + this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; + this.attributeName = attributeName; + this.attributeNamespace = attributeNamespace; + this.mustUseProperty = mustUseProperty; + this.propertyName = name; + this.type = type; + this.sanitizeURL = sanitizeURL; +} // When adding attributes to this list, be sure to also add them to +// the `possibleStandardNames` module to ensure casing and incorrect +// name warnings. + + +var properties = {}; // These props are reserved by React. They shouldn't be written to the DOM. + +var reservedProps = ['children', 'dangerouslySetInnerHTML', // TODO: This prevents the assignment of defaultValue to regular +// elements (not just inputs). Now that ReactDOMInput assigns to the +// defaultValue property -- do we need this? +'defaultValue', 'defaultChecked', 'innerHTML', 'suppressContentEditableWarning', 'suppressHydrationWarning', 'style']; + +reservedProps.forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, RESERVED, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // A few React string attributes have a different name. +// This is a mapping from React prop names to the attribute names. + +[['acceptCharset', 'accept-charset'], ['className', 'class'], ['htmlFor', 'for'], ['httpEquiv', 'http-equiv']].forEach(function (_ref) { + var name = _ref[0], + attributeName = _ref[1]; + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, // attributeName + null, // attributeNamespace + false); +}); // These are "enumerated" HTML attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). + +['contentEditable', 'draggable', 'spellCheck', 'value'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false); +}); // These are "enumerated" SVG attributes that accept "true" and "false". +// In React, we let users pass `true` and `false` even though technically +// these aren't boolean attributes (they are coerced to strings). +// Since these are SVG attributes, their attribute names are case-sensitive. + +['autoReverse', 'externalResourcesRequired', 'focusable', 'preserveAlpha'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // These are HTML boolean attributes. + +['allowFullScreen', 'async', // Note: there is a special case that prevents it from being written to the DOM +// on the client side because the browsers are inconsistent. Instead we call focus(). +'autoFocus', 'autoPlay', 'controls', 'default', 'defer', 'disabled', 'disablePictureInPicture', 'formNoValidate', 'hidden', 'loop', 'noModule', 'noValidate', 'open', 'playsInline', 'readOnly', 'required', 'reversed', 'scoped', 'seamless', // Microdata +'itemScope'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false); +}); // These are the few React props that we set as DOM properties +// rather than attributes. These are all booleans. + +['checked', // Note: `option.selected` is not updated if `select.multiple` is +// disabled with `removeAttribute`. We have special logic for handling this. +'multiple', 'muted', 'selected' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // These are HTML attributes that are "overloaded booleans": they behave like +// booleans, but can also accept a string value. + +['capture', 'download' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // These are HTML attributes that must be positive numbers. + +['cols', 'rows', 'size', 'span' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, // mustUseProperty + name, // attributeName + null, // attributeNamespace + false); +}); // These are HTML attributes that must be numbers. + +['rowSpan', 'start'].forEach(function (name) { + properties[name] = new PropertyInfoRecord(name, NUMERIC, false, // mustUseProperty + name.toLowerCase(), // attributeName + null, // attributeNamespace + false); +}); +var CAMELIZE = /[\-\:]([a-z])/g; + +var capitalize = function (token) { + return token[1].toUpperCase(); +}; // This is a list of all SVG attributes that need special casing, namespacing, +// or boolean value assignment. Regular attributes that just accept strings +// and have the same names are omitted, just like in the HTML whitelist. +// Some of these attributes can be hard to find. This list was created by +// scraping the MDN documentation. + + +['accent-height', 'alignment-baseline', 'arabic-form', 'baseline-shift', 'cap-height', 'clip-path', 'clip-rule', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'dominant-baseline', 'enable-background', 'fill-opacity', 'fill-rule', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'glyph-name', 'glyph-orientation-horizontal', 'glyph-orientation-vertical', 'horiz-adv-x', 'horiz-origin-x', 'image-rendering', 'letter-spacing', 'lighting-color', 'marker-end', 'marker-mid', 'marker-start', 'overline-position', 'overline-thickness', 'paint-order', 'panose-1', 'pointer-events', 'rendering-intent', 'shape-rendering', 'stop-color', 'stop-opacity', 'strikethrough-position', 'strikethrough-thickness', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke-width', 'text-anchor', 'text-decoration', 'text-rendering', 'underline-position', 'underline-thickness', 'unicode-bidi', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'vector-effect', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'word-spacing', 'writing-mode', 'xmlns:xlink', 'x-height' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, null, // attributeNamespace + false); +}); // String SVG attributes with the xlink namespace. + +['xlink:actuate', 'xlink:arcrole', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/1999/xlink', false); +}); // String SVG attributes with the xml namespace. + +['xml:base', 'xml:lang', 'xml:space' // NOTE: if you add a camelCased prop to this list, +// you'll need to set attributeName to name.toLowerCase() +// instead in the assignment below. +].forEach(function (attributeName) { + var name = attributeName.replace(CAMELIZE, capitalize); + properties[name] = new PropertyInfoRecord(name, STRING, false, // mustUseProperty + attributeName, 'http://www.w3.org/XML/1998/namespace', false); +}); // These attribute exists both in HTML and SVG. +// The attribute name is case-sensitive in SVG so we can't just use +// the React name like we do for attributes that exist only in HTML. + +['tabIndex', 'crossOrigin'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + false); +}); // These attributes accept URLs. These must not allow javascript: URLS. +// These will also need to accept Trusted Types object in the future. + +var xlinkHref = 'xlinkHref'; +properties[xlinkHref] = new PropertyInfoRecord('xlinkHref', STRING, false, // mustUseProperty +'xlink:href', 'http://www.w3.org/1999/xlink', true); +['src', 'href', 'action', 'formAction'].forEach(function (attributeName) { + properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, // mustUseProperty + attributeName.toLowerCase(), // attributeName + null, // attributeNamespace + true); +}); + +var ReactDebugCurrentFrame = null; + +{ + ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; +} // A javascript: URL can contain leading C0 control or \u0020 SPACE, +// and any newline or tab are filtered out as if they're not part of the URL. +// https://url.spec.whatwg.org/#url-parsing +// Tab or newline are defined as \r\n\t: +// https://infra.spec.whatwg.org/#ascii-tab-or-newline +// A C0 control is a code point in the range \u0000 NULL to \u001F +// INFORMATION SEPARATOR ONE, inclusive: +// https://infra.spec.whatwg.org/#c0-control-or-space + +/* eslint-disable max-len */ + + +var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; +var didWarn = false; + +function sanitizeURL(url) { + { + if (!didWarn && isJavaScriptProtocol.test(url)) { + didWarn = true; + + error('A future version of React will block javascript: URLs as a security precaution. ' + 'Use event handlers instead if you can. If you need to generate unsafe HTML try ' + 'using dangerouslySetInnerHTML instead. React was passed %s.', JSON.stringify(url)); + } + } +} + +/** + * Get the value for a property on a node. Only used in DEV for SSR validation. + * The "expected" argument is used as a hint of what the expected value is. + * Some properties have multiple equivalent values. + */ +function getValueForProperty(node, name, expected, propertyInfo) { + { + if (propertyInfo.mustUseProperty) { + var propertyName = propertyInfo.propertyName; + return node[propertyName]; + } else { + if ( propertyInfo.sanitizeURL) { + // If we haven't fully disabled javascript: URLs, and if + // the hydration is successful of a javascript: URL, we + // still want to warn on the client. + sanitizeURL('' + expected); + } + + var attributeName = propertyInfo.attributeName; + var stringValue = null; + + if (propertyInfo.type === OVERLOADED_BOOLEAN) { + if (node.hasAttribute(attributeName)) { + var value = node.getAttribute(attributeName); + + if (value === '') { + return true; + } + + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return value; + } + + if (value === '' + expected) { + return expected; + } + + return value; + } + } else if (node.hasAttribute(attributeName)) { + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + // We had an attribute but shouldn't have had one, so read it + // for the error message. + return node.getAttribute(attributeName); + } + + if (propertyInfo.type === BOOLEAN) { + // If this was a boolean, it doesn't matter what the value is + // the fact that we have it is the same as the expected. + return expected; + } // Even if this property uses a namespace we use getAttribute + // because we assume its namespaced name is the same as our config. + // To use getAttributeNS we need the local name which we don't have + // in our config atm. + + + stringValue = node.getAttribute(attributeName); + } + + if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { + return stringValue === null ? expected : stringValue; + } else if (stringValue === '' + expected) { + return expected; + } else { + return stringValue; + } + } + } +} +/** + * Get the value for a attribute on a node. Only used in DEV for SSR validation. + * The third argument is used as a hint of what the expected value is. Some + * attributes have multiple equivalent values. + */ + +function getValueForAttribute(node, name, expected) { + { + if (!isAttributeNameSafe(name)) { + return; + } + + if (!node.hasAttribute(name)) { + return expected === undefined ? undefined : null; + } + + var value = node.getAttribute(name); + + if (value === '' + expected) { + return expected; + } + + return value; + } +} +/** + * Sets the value for a property on a node. + * + * @param {DOMElement} node + * @param {string} name + * @param {*} value + */ + +function setValueForProperty(node, name, value, isCustomComponentTag) { + var propertyInfo = getPropertyInfo(name); + + if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { + return; + } + + if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { + value = null; + } // If the prop isn't in the special list, treat it as a simple attribute. + + + if (isCustomComponentTag || propertyInfo === null) { + if (isAttributeNameSafe(name)) { + var _attributeName = name; + + if (value === null) { + node.removeAttribute(_attributeName); + } else { + node.setAttribute(_attributeName, '' + value); + } + } + + return; + } + + var mustUseProperty = propertyInfo.mustUseProperty; + + if (mustUseProperty) { + var propertyName = propertyInfo.propertyName; + + if (value === null) { + var type = propertyInfo.type; + node[propertyName] = type === BOOLEAN ? false : ''; + } else { + // Contrary to `setAttribute`, object properties are properly + // `toString`ed by IE8/9. + node[propertyName] = value; + } + + return; + } // The rest are treated as attributes with special cases. + + + var attributeName = propertyInfo.attributeName, + attributeNamespace = propertyInfo.attributeNamespace; + + if (value === null) { + node.removeAttribute(attributeName); + } else { + var _type = propertyInfo.type; + var attributeValue; + + if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { + // If attribute type is boolean, we know for sure it won't be an execution sink + // and we won't require Trusted Type here. + attributeValue = ''; + } else { + // `setAttribute` with objects becomes only `[object]` in IE8/9, + // ('' + value) makes it output the correct toString()-value. + { + attributeValue = '' + value; + } + + if (propertyInfo.sanitizeURL) { + sanitizeURL(attributeValue.toString()); + } + } + + if (attributeNamespace) { + node.setAttributeNS(attributeNamespace, attributeName, attributeValue); + } else { + node.setAttribute(attributeName, attributeValue); + } + } +} + +var BEFORE_SLASH_RE = /^(.*)[\\\/]/; +function describeComponentFrame (name, source, ownerName) { + var sourceInfo = ''; + + if (source) { + var path = source.fileName; + var fileName = path.replace(BEFORE_SLASH_RE, ''); + + { + // In DEV, include code for a common special case: + // prefer "folder/index.js" instead of just "index.js". + if (/^index\./.test(fileName)) { + var match = path.match(BEFORE_SLASH_RE); + + if (match) { + var pathBeforeSlash = match[1]; + + if (pathBeforeSlash) { + var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); + fileName = folderName + '/' + fileName; + } + } + } + } + + sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; + } else if (ownerName) { + sourceInfo = ' (created by ' + ownerName + ')'; + } + + return '\n in ' + (name || 'Unknown') + sourceInfo; +} + +// The Symbol used to tag the ReactElement-like types. If there is no native Symbol +// nor polyfill, then a plain number is used for performance. +var hasSymbol = typeof Symbol === 'function' && Symbol.for; +var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; +var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; +var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; +var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; +var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; +var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; +var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary +var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; +var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; +var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; +var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8; +var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; +var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; +var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9; +var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; +var FAUX_ITERATOR_SYMBOL = '@@iterator'; +function getIteratorFn(maybeIterable) { + if (maybeIterable === null || typeof maybeIterable !== 'object') { + return null; + } + + var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; + + if (typeof maybeIterator === 'function') { + return maybeIterator; + } + + return null; +} + +var Uninitialized = -1; +var Pending = 0; +var Resolved = 1; +var Rejected = 2; +function refineResolvedLazyComponent(lazyComponent) { + return lazyComponent._status === Resolved ? lazyComponent._result : null; +} +function initializeLazyComponentType(lazyComponent) { + if (lazyComponent._status === Uninitialized) { + lazyComponent._status = Pending; + var ctor = lazyComponent._ctor; + var thenable = ctor(); + lazyComponent._result = thenable; + thenable.then(function (moduleObject) { + if (lazyComponent._status === Pending) { + var defaultExport = moduleObject.default; + + { + if (defaultExport === undefined) { + error('lazy: Expected the result of a dynamic import() call. ' + 'Instead received: %s\n\nYour code should look like: \n ' + "const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); + } + } + + lazyComponent._status = Resolved; + lazyComponent._result = defaultExport; + } + }, function (error) { + if (lazyComponent._status === Pending) { + lazyComponent._status = Rejected; + lazyComponent._result = error; + } + }); + } +} + +function getWrappedName(outerType, innerType, wrapperName) { + var functionName = innerType.displayName || innerType.name || ''; + return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); +} + +function getComponentName(type) { + if (type == null) { + // Host root, text node or just invalid type. + return null; + } + + { + if (typeof type.tag === 'number') { + error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); + } + } + + if (typeof type === 'function') { + return type.displayName || type.name || null; + } + + if (typeof type === 'string') { + return type; + } + + switch (type) { + case REACT_FRAGMENT_TYPE: + return 'Fragment'; + + case REACT_PORTAL_TYPE: + return 'Portal'; + + case REACT_PROFILER_TYPE: + return "Profiler"; + + case REACT_STRICT_MODE_TYPE: + return 'StrictMode'; + + case REACT_SUSPENSE_TYPE: + return 'Suspense'; + + case REACT_SUSPENSE_LIST_TYPE: + return 'SuspenseList'; + } + + if (typeof type === 'object') { + switch (type.$$typeof) { + case REACT_CONTEXT_TYPE: + return 'Context.Consumer'; + + case REACT_PROVIDER_TYPE: + return 'Context.Provider'; + + case REACT_FORWARD_REF_TYPE: + return getWrappedName(type, type.render, 'ForwardRef'); + + case REACT_MEMO_TYPE: + return getComponentName(type.type); + + case REACT_BLOCK_TYPE: + return getComponentName(type.render); + + case REACT_LAZY_TYPE: + { + var thenable = type; + var resolvedThenable = refineResolvedLazyComponent(thenable); + + if (resolvedThenable) { + return getComponentName(resolvedThenable); + } + + break; + } + } + } + + return null; +} + +var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; + +function describeFiber(fiber) { + switch (fiber.tag) { + case HostRoot: + case HostPortal: + case HostText: + case Fragment: + case ContextProvider: + case ContextConsumer: + return ''; + + default: + var owner = fiber._debugOwner; + var source = fiber._debugSource; + var name = getComponentName(fiber.type); + var ownerName = null; + + if (owner) { + ownerName = getComponentName(owner.type); + } + + return describeComponentFrame(name, source, ownerName); + } +} + +function getStackByFiberInDevAndProd(workInProgress) { + var info = ''; + var node = workInProgress; + + do { + info += describeFiber(node); + node = node.return; + } while (node); + + return info; +} +var current = null; +var isRendering = false; +function getCurrentFiberOwnerNameInDevOrNull() { + { + if (current === null) { + return null; + } + + var owner = current._debugOwner; + + if (owner !== null && typeof owner !== 'undefined') { + return getComponentName(owner.type); + } + } + + return null; +} +function getCurrentFiberStackInDev() { + { + if (current === null) { + return ''; + } // Safe because if current fiber exists, we are reconciling, + // and it is guaranteed to be the work-in-progress version. + + + return getStackByFiberInDevAndProd(current); + } +} +function resetCurrentFiber() { + { + ReactDebugCurrentFrame$1.getCurrentStack = null; + current = null; + isRendering = false; + } +} +function setCurrentFiber(fiber) { + { + ReactDebugCurrentFrame$1.getCurrentStack = getCurrentFiberStackInDev; + current = fiber; + isRendering = false; + } +} +function setIsRendering(rendering) { + { + isRendering = rendering; + } +} + +// Flow does not allow string concatenation of most non-string types. To work +// around this limitation, we use an opaque type that can only be obtained by +// passing the value through getToStringValue first. +function toString(value) { + return '' + value; +} +function getToStringValue(value) { + switch (typeof value) { + case 'boolean': + case 'number': + case 'object': + case 'string': + case 'undefined': + return value; + + default: + // function, symbol are assigned as empty strings + return ''; + } +} + +var ReactDebugCurrentFrame$2 = null; +var ReactControlledValuePropTypes = { + checkPropTypes: null +}; + +{ + ReactDebugCurrentFrame$2 = ReactSharedInternals.ReactDebugCurrentFrame; + var hasReadOnlyValue = { + button: true, + checkbox: true, + image: true, + hidden: true, + radio: true, + reset: true, + submit: true + }; + var propTypes = { + value: function (props, propName, componentName) { + if (hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) { + return null; + } + + return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + }, + checked: function (props, propName, componentName) { + if (props.onChange || props.readOnly || props.disabled || props[propName] == null || enableDeprecatedFlareAPI ) { + return null; + } + + return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); + } + }; + /** + * Provide a linked `value` attribute for controlled forms. You should not use + * this outside of the ReactDOM controlled form components. + */ + + ReactControlledValuePropTypes.checkPropTypes = function (tagName, props) { + checkPropTypes(propTypes, props, 'prop', tagName, ReactDebugCurrentFrame$2.getStackAddendum); + }; +} + +function isCheckable(elem) { + var type = elem.type; + var nodeName = elem.nodeName; + return nodeName && nodeName.toLowerCase() === 'input' && (type === 'checkbox' || type === 'radio'); +} + +function getTracker(node) { + return node._valueTracker; +} + +function detachTracker(node) { + node._valueTracker = null; +} + +function getValueFromNode(node) { + var value = ''; + + if (!node) { + return value; + } + + if (isCheckable(node)) { + value = node.checked ? 'true' : 'false'; + } else { + value = node.value; + } + + return value; +} + +function trackValueOnNode(node) { + var valueField = isCheckable(node) ? 'checked' : 'value'; + var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); + var currentValue = '' + node[valueField]; // if someone has already defined a value or Safari, then bail + // and don't track value will cause over reporting of changes, + // but it's better then a hard failure + // (needed for certain tests that spyOn input values and Safari) + + if (node.hasOwnProperty(valueField) || typeof descriptor === 'undefined' || typeof descriptor.get !== 'function' || typeof descriptor.set !== 'function') { + return; + } + + var get = descriptor.get, + set = descriptor.set; + Object.defineProperty(node, valueField, { + configurable: true, + get: function () { + return get.call(this); + }, + set: function (value) { + currentValue = '' + value; + set.call(this, value); + } + }); // We could've passed this the first time + // but it triggers a bug in IE11 and Edge 14/15. + // Calling defineProperty() again should be equivalent. + // https://github.com/facebook/react/issues/11768 + + Object.defineProperty(node, valueField, { + enumerable: descriptor.enumerable + }); + var tracker = { + getValue: function () { + return currentValue; + }, + setValue: function (value) { + currentValue = '' + value; + }, + stopTracking: function () { + detachTracker(node); + delete node[valueField]; + } + }; + return tracker; +} + +function track(node) { + if (getTracker(node)) { + return; + } // TODO: Once it's just Fiber we can move this to node._wrapperState + + + node._valueTracker = trackValueOnNode(node); +} +function updateValueIfChanged(node) { + if (!node) { + return false; + } + + var tracker = getTracker(node); // if there is no tracker at this point it's unlikely + // that trying again will succeed + + if (!tracker) { + return true; + } + + var lastValue = tracker.getValue(); + var nextValue = getValueFromNode(node); + + if (nextValue !== lastValue) { + tracker.setValue(nextValue); + return true; + } + + return false; +} + +var didWarnValueDefaultValue = false; +var didWarnCheckedDefaultChecked = false; +var didWarnControlledToUncontrolled = false; +var didWarnUncontrolledToControlled = false; + +function isControlled(props) { + var usesChecked = props.type === 'checkbox' || props.type === 'radio'; + return usesChecked ? props.checked != null : props.value != null; +} +/** + * Implements an host component that allows setting these optional + * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. + * + * If `checked` or `value` are not supplied (or null/undefined), user actions + * that affect the checked state or value will trigger updates to the element. + * + * If they are supplied (and not null/undefined), the rendered element will not + * trigger updates to the element. Instead, the props must change in order for + * the rendered element to be updated. + * + * The rendered element will be initialized as unchecked (or `defaultChecked`) + * with an empty value (or `defaultValue`). + * + * See http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html + */ + + +function getHostProps(element, props) { + var node = element; + var checked = props.checked; + + var hostProps = _assign({}, props, { + defaultChecked: undefined, + defaultValue: undefined, + value: undefined, + checked: checked != null ? checked : node._wrapperState.initialChecked + }); + + return hostProps; +} +function initWrapperState(element, props) { + { + ReactControlledValuePropTypes.checkPropTypes('input', props); + + if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { + error('%s contains an input of type %s with both checked and defaultChecked props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); + + didWarnCheckedDefaultChecked = true; + } + + if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { + error('%s contains an input of type %s with both value and defaultValue props. ' + 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components', getCurrentFiberOwnerNameInDevOrNull() || 'A component', props.type); + + didWarnValueDefaultValue = true; + } + } + + var node = element; + var defaultValue = props.defaultValue == null ? '' : props.defaultValue; + node._wrapperState = { + initialChecked: props.checked != null ? props.checked : props.defaultChecked, + initialValue: getToStringValue(props.value != null ? props.value : defaultValue), + controlled: isControlled(props) + }; +} +function updateChecked(element, props) { + var node = element; + var checked = props.checked; + + if (checked != null) { + setValueForProperty(node, 'checked', checked, false); + } +} +function updateWrapper(element, props) { + var node = element; + + { + var controlled = isControlled(props); + + if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { + error('A component is changing an uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type); + + didWarnUncontrolledToControlled = true; + } + + if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { + error('A component is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', props.type); + + didWarnControlledToUncontrolled = true; + } + } + + updateChecked(element, props); + var value = getToStringValue(props.value); + var type = props.type; + + if (value != null) { + if (type === 'number') { + if (value === 0 && node.value === '' || // We explicitly want to coerce to number here if possible. + // eslint-disable-next-line + node.value != value) { + node.value = toString(value); + } + } else if (node.value !== toString(value)) { + node.value = toString(value); + } + } else if (type === 'submit' || type === 'reset') { + // Submit/reset inputs need the attribute removed completely to avoid + // blank-text buttons. + node.removeAttribute('value'); + return; + } + + { + // When syncing the value attribute, the value comes from a cascade of + // properties: + // 1. The value React property + // 2. The defaultValue React property + // 3. Otherwise there should be no change + if (props.hasOwnProperty('value')) { + setDefaultValue(node, props.type, value); + } else if (props.hasOwnProperty('defaultValue')) { + setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); + } + } + + { + // When syncing the checked attribute, it only changes when it needs + // to be removed, such as transitioning from a checkbox into a text input + if (props.checked == null && props.defaultChecked != null) { + node.defaultChecked = !!props.defaultChecked; + } + } +} +function postMountWrapper(element, props, isHydrating) { + var node = element; // Do not assign value if it is already set. This prevents user text input + // from being lost during SSR hydration. + + if (props.hasOwnProperty('value') || props.hasOwnProperty('defaultValue')) { + var type = props.type; + var isButton = type === 'submit' || type === 'reset'; // Avoid setting value attribute on submit/reset inputs as it overrides the + // default value provided by the browser. See: #12872 + + if (isButton && (props.value === undefined || props.value === null)) { + return; + } + + var initialValue = toString(node._wrapperState.initialValue); // Do not assign value if it is already set. This prevents user text input + // from being lost during SSR hydration. + + if (!isHydrating) { + { + // When syncing the value attribute, the value property should use + // the wrapperState._initialValue property. This uses: + // + // 1. The value React property when present + // 2. The defaultValue React property when present + // 3. An empty string + if (initialValue !== node.value) { + node.value = initialValue; + } + } + } + + { + // Otherwise, the value attribute is synchronized to the property, + // so we assign defaultValue to the same thing as the value property + // assignment step above. + node.defaultValue = initialValue; + } + } // Normally, we'd just do `node.checked = node.checked` upon initial mount, less this bug + // this is needed to work around a chrome bug where setting defaultChecked + // will sometimes influence the value of checked (even after detachment). + // Reference: https://bugs.chromium.org/p/chromium/issues/detail?id=608416 + // We need to temporarily unset name to avoid disrupting radio button groups. + + + var name = node.name; + + if (name !== '') { + node.name = ''; + } + + { + // When syncing the checked attribute, both the checked property and + // attribute are assigned at the same time using defaultChecked. This uses: + // + // 1. The checked React property when present + // 2. The defaultChecked React property when present + // 3. Otherwise, false + node.defaultChecked = !node.defaultChecked; + node.defaultChecked = !!node._wrapperState.initialChecked; + } + + if (name !== '') { + node.name = name; + } +} +function restoreControlledState(element, props) { + var node = element; + updateWrapper(node, props); + updateNamedCousins(node, props); +} + +function updateNamedCousins(rootNode, props) { + var name = props.name; + + if (props.type === 'radio' && name != null) { + var queryRoot = rootNode; + + while (queryRoot.parentNode) { + queryRoot = queryRoot.parentNode; + } // If `rootNode.form` was non-null, then we could try `form.elements`, + // but that sometimes behaves strangely in IE8. We could also try using + // `form.getElementsByName`, but that will only return direct children + // and won't include inputs that use the HTML5 `form=` attribute. Since + // the input might not even be in a form. It might not even be in the + // document. Let's just use the local `querySelectorAll` to ensure we don't + // miss anything. + + + var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); + + for (var i = 0; i < group.length; i++) { + var otherNode = group[i]; + + if (otherNode === rootNode || otherNode.form !== rootNode.form) { + continue; + } // This will throw if radio buttons rendered by different copies of React + // and the same name are rendered into the same form (same as #1939). + // That's probably okay; we don't support it just as we don't support + // mixing React radio buttons with non-React ones. + + + var otherProps = getFiberCurrentPropsFromNode$1(otherNode); + + if (!otherProps) { + { + throw Error( "ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported." ); + } + } // We need update the tracked value on the named cousin since the value + // was changed but the input saw no event or value set + + + updateValueIfChanged(otherNode); // If this is a controlled radio button group, forcing the input that + // was previously checked to update will cause it to be come re-checked + // as appropriate. + + updateWrapper(otherNode, otherProps); + } + } +} // In Chrome, assigning defaultValue to certain input types triggers input validation. +// For number inputs, the display value loses trailing decimal points. For email inputs, +// Chrome raises "The specified value is not a valid email address". +// +// Here we check to see if the defaultValue has actually changed, avoiding these problems +// when the user is inputting text +// +// https://github.com/facebook/react/issues/7253 + + +function setDefaultValue(node, type, value) { + if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js + type !== 'number' || node.ownerDocument.activeElement !== node) { + if (value == null) { + node.defaultValue = toString(node._wrapperState.initialValue); + } else if (node.defaultValue !== toString(value)) { + node.defaultValue = toString(value); + } + } +} + +var didWarnSelectedSetOnOption = false; +var didWarnInvalidChild = false; + +function flattenChildren(children) { + var content = ''; // Flatten children. We'll warn if they are invalid + // during validateProps() which runs for hydration too. + // Note that this would throw on non-element objects. + // Elements are stringified (which is normally irrelevant + // but matters for ). + + React.Children.forEach(children, function (child) { + if (child == null) { + return; + } + + content += child; // Note: we don't warn about invalid children here. + // Instead, this is done separately below so that + // it happens during the hydration codepath too. + }); + return content; +} +/** + * Implements an