{"name":"react-activation","version":"0.8.0-beta.1","description":"<KeepAlive /> for React like <keep-alive /> in vue","main":"index.js","scripts":{"build":"rollup --config","format":"prettier --write \"./src/**/*.js\"","manual:publish":"npm run build && np --no-cleanup --yolo --no-publish && npm publish"},"keywords":["React Keep Alive","Keep Alive","keep-alive","KeepAlive","activation","react cache","react tabs cache","react router cache","vue keep-alive"],"sideEffects":false,"author":{"name":"CJY0208"},"license":"ISC","homepage":"https://github.com/CJY0208/react-activation","repository":{"type":"git","url":"git+https://github.com/CJY0208/react-activation.git"},"peerDependencies":{"react":">=16"},"dependencies":{"create-react-context":"^0.3.0","hoist-non-react-statics":"^3.3.0","jsx-ast-utils":"^2.2.1","react-node-key":"^0.2.0","szfe-tools":"^0.0.0-beta.7"},"devDependencies":{"@babel/core":"^7.5.5","@babel/plugin-proposal-class-properties":"^7.5.5","@babel/preset-env":"^7.5.5","@babel/preset-react":"^7.0.0","babel-plugin-import":"^1.13.3","np":"^6.2.5","prettier":"^2.2.1","rollup":"^1.11.3","rollup-plugin-babel":"^4.3.2","rollup-plugin-node-resolve":"^4.2.3","rollup-plugin-uglify":"^6.0.2"},"readme":"# React Activation\r\n\r\n[![size](https://img.shields.io/bundlephobia/minzip/react-activation@latest.svg)](https://bundlephobia.com/result?p=react-activation@latest)\r\n[![dm](https://img.shields.io/npm/dm/react-activation.svg)](https://github.com/CJY0208/react-activation)\r\n![](https://visitor-badge.glitch.me/badge?page_id=cjy0208.react-activation)\r\n\r\nEnglish | [中文说明](./README_CN.md)\r\n\r\nImplementation of the `<keep-alive />` function in `Vue` For `React`\r\n\r\n---\r\n\r\nMore stable `<KeepAlive />` function with `babel` pre-compilation\r\n\r\n[Online Demo](https://codesandbox.io/s/affectionate-beaver-solkt)\r\n\r\n<img src=\"./docs/basicReactActivation.gif\">\r\n\r\n---\r\n\r\n## More examples\r\n\r\n- [Closable tabs with `react-router`](https://codesandbox.io/s/keguanbideyifangwenluyou-tab-shilikeanluyoucanshufenduofenhuancun-ewycx)\r\n- [Closable tabs with `umi`](https://codesandbox.io/s/umi-keep-alive-tabs-demo-knfxy)\r\n- [Using Animation with `react-router`](https://codesandbox.io/s/luyouzhuanchangdonghuashili-jdhq1)\r\n\r\n---\r\n\r\n## Compatibility\r\n\r\n- React v17+ (beta)\r\n\r\n- React v16+\r\n\r\n- Preact v10+\r\n\r\n- Compatible with SSR\r\n\r\n---\r\n\r\n## Install\r\n\r\n```bash\r\nyarn add react-activation\r\n# or\r\nnpm install react-activation\r\n```\r\n\r\n---\r\n\r\n## Usage\r\n\r\n#### 1. Add `react-activation/babel` plugins in `.babelrc`\r\n\r\n[Why is it needed?](https://github.com/CJY0208/react-activation/issues/18#issuecomment-564360695)\r\n\r\nThe plugin adds a `_nk` attribute to each JSX element during compilation to help the `react-activation` runtime **generate an unique identifier by render location** base on [`react-node-key`](https://github.com/CJY0208/react-node-key).\r\n\r\n```javascript\r\n{\r\n  \"plugins\": [\r\n    \"react-activation/babel\"\r\n  ]\r\n}\r\n```\r\n\r\n#### 2. In your business code, place the `<AliveScope>` outer layer at a location that will not be unmounted, usually at the application entrance\r\n\r\nNote: When used with `react-router` or `react-redux`, you need to place `<AliveScope>` inside `<Router>` or `<Provider>`\r\n\r\n```javascript\r\n// entry.js\r\n\r\nimport React from 'react'\r\nimport ReactDOM from 'react-dom'\r\nimport { AliveScope } from 'react-activation'\r\n\r\nimport Test from './Test'\r\n\r\nReactDOM.render(\r\n  <AliveScope>\r\n    <Test />\r\n  </AliveScope>,\r\n  document.getElementById('root')\r\n)\r\n```\r\n\r\n#### 3. Wrap the components that need to keep states with `<KeepAlive>`\r\n\r\nLike the `<Counter>` component in the example\r\n\r\n```javascript\r\n// Test.js\r\n\r\nimport React, { useState } from 'react'\r\nimport KeepAlive from 'react-activation'\r\n\r\nfunction Counter() {\r\n  const [count, setCount] = useState(0)\r\n\r\n  return (\r\n    <div>\r\n      <p>count: {count}</p>\r\n      <button onClick={() => setCount(count => count + 1)}>Add</button>\r\n    </div>\r\n  )\r\n}\r\n\r\nfunction Test() {\r\n  const [show, setShow] = useState(true)\r\n\r\n  return (\r\n    <div>\r\n      <button onClick={() => setShow(show => !show)}>Toggle</button>\r\n      {show && (\r\n        <KeepAlive>\r\n          <Counter />\r\n        </KeepAlive>\r\n      )}\r\n    </div>\r\n  )\r\n}\r\n\r\nexport default Test\r\n```\r\n\r\n---\r\n\r\n## Lifecycle\r\n\r\n`ClassComponent` works with `withActivation` decorator\r\n\r\nUse `componentDidActivate` and `componentWillUnactivate` to correspond to the two states of \"activate\" and \"unactivate\" respectively.\r\n\r\n`FunctionComponent` uses the `useActivate` and `useUnactivate` hooks respectively\r\n\r\n```javascript\r\n...\r\nimport KeepAlive, { useActivate, useUnactivate, withActivation } from 'react-activation'\r\n\r\n@withActivation\r\nclass TestClass extends Component {\r\n  ...\r\n  componentDidActivate() {\r\n    console.log('TestClass: componentDidActivate')\r\n  }\r\n\r\n  componentWillUnactivate() {\r\n    console.log('TestClass: componentWillUnactivate')\r\n  }\r\n  ...\r\n}\r\n...\r\nfunction TestFunction() {\r\n  useActivate(() => {\r\n    console.log('TestFunction: didActivate')\r\n  })\r\n\r\n  useUnactivate(() => {\r\n    console.log('TestFunction: willUnactivate')\r\n  })\r\n  ...\r\n}\r\n...\r\nfunction App() {\r\n  ...\r\n  return (\r\n    {show && (\r\n      <KeepAlive>\r\n        <TestClass />\r\n        <TestFunction />\r\n      </KeepAlive>\r\n    )}\r\n  )\r\n}\r\n...\r\n```\r\n\r\n---\r\n\r\n## Save Scroll Position (`true` by default)\r\n\r\n`<KeepAlive />` would try to detect scrollable nodes in its `children`, then, save their scroll position automaticlly before `componentWillUnactivate` and restore saving position after `componentDidActivate`\r\n\r\nIf you don't want `<KeepAlive />` to do this thing, set `saveScrollPosition` prop to `false`\r\n\r\n```javascript\r\n<KeepAlive saveScrollPosition={false} />\r\n```\r\n\r\nIf your components share screen scroll container, `document.body` or `document.documentElement`, set `saveScrollPosition` prop to `\"screen\"` can save sharing screen container's scroll position before `componentWillUnactivate`\r\n\r\n```javascript\r\n<KeepAlive saveScrollPosition=\"screen\" />\r\n```\r\n\r\n---\r\n\r\n## Multiple Cache\r\n\r\nUnder the same parent node, `<KeepAlive>` in the same location will use the same cache by default.\r\n\r\nFor example, with the following parameter routing scenario, the `/item` route will be rendered differently by `id`, but only the same cache can be kept.\r\n\r\n```javascript\r\n<Route\r\n  path=\"/item/:id\"\r\n  render={props => (\r\n    <KeepAlive>\r\n      <Item {...props} />\r\n    </KeepAlive>\r\n  )}\r\n/>\r\n```\r\n\r\nSimilar scenarios, you can use the `id` attribute of `<KeepAlive>` to implement multiple caches according to specific conditions.\r\n\r\n```javascript\r\n<Route\r\n  path=\"/item/:id\"\r\n  render={props => (\r\n    <KeepAlive id={props.match.params.id}>\r\n      <Item {...props} />\r\n    </KeepAlive>\r\n  )}\r\n/>\r\n```\r\n\r\n---\r\n\r\n## Cache Control\r\n\r\n### Automatic control cache\r\n\r\nAdd the `when` attribute to the `<KeepAlive />` tag that needs to control the cache. The value is as follows\r\n\r\n#### When the `when` type is `Boolean`\r\n\r\n- **true**: Cache after uninstallation\r\n- **false**: Not cached after uninstallation\r\n\r\n```javascript\r\n<KeepAlive when={false}>\r\n```\r\n\r\n#### When the `when` type is `Array`\r\n\r\nThe **1th** parameter indicates whether it needs to be cached at the time of uninstallation.\r\n\r\nThe **2th** parameter indicates whether to unload all cache contents of `<KeepAlive>`, including all `<KeepAlive>` nested in `<KeepAlive>`.\r\n\r\n```javascript\r\n// For example:\r\n// The following indicates that it is not cached when uninstalling\r\n// And uninstalls all nested `<KeepAlive>`\r\n<KeepAlive when={[false, true]}>\r\n  ...\r\n  <KeepAlive>\r\n    ...\r\n    <KeepAlive>...</KeepAlive>\r\n    ...\r\n  </KeepAlive>\r\n  ...\r\n</KeepAlive>\r\n```\r\n\r\n#### When the `when` type is `Function`\r\n\r\nThe return value is the above `Boolean` or `Array`, which takes effect as described above.\r\n\r\n### Manually control the cache\r\n\r\n1. Add the `name` attribute to the `<KeepAlive>` tag that needs to control the cache.\r\n\r\n2. Get control functions using `withAliveScope` or `useAliveController`\r\n\r\n   - **drop(name)**\r\n\r\n     Unload the `<KeepAlive>` node in cache state by name. The name can be of type `String` or `RegExp`. Note that only the first layer of content that hits `<KeepAlive>` is unloaded and will not be uninstalled in `<KeepAlive>`. Would not unload nested `<KeepAlive>`\r\n\r\n   - **dropScope(name)**\r\n\r\n     Unloads the `<KeepAlive>` node in cache state by name. The name optional type is `String` or `RegExp`, which will unload all content of `<KeepAlive>`, including all `<KeepAlive>` nested in `<KeepAlive>`.\r\n\r\n   - **clear()**\r\n\r\n     will clear all `<KeepAlive>` in the cache\r\n\r\n   - **getCachingNodes()**\r\n\r\n     Get all the nodes in the cache\r\n\r\n```javascript\r\n...\r\nimport KeepAlive, { withAliveScope, useAliveController } from 'react-activation'\r\n...\r\n<KeepAlive name=\"Test\">\r\n  ...\r\n    <KeepAlive>\r\n      ...\r\n        <KeepAlive>\r\n          ...\r\n        </KeepAlive>\r\n      ...\r\n    </KeepAlive>\r\n  ...\r\n</KeepAlive>\r\n...\r\nfunction App() {\r\n  const { drop, dropScope, clear, getCachingNodes } = useAliveController()\r\n\r\n  useEffect(() => {\r\n    drop('Test')\r\n    // or\r\n    drop(/Test/)\r\n    // or\r\n    dropScope('Test')\r\n\r\n    clear()\r\n  })\r\n\r\n  return (\r\n    ...\r\n  )\r\n}\r\n// or\r\n@withAliveScope\r\nclass App extends Component {\r\n  render() {\r\n    const { drop, dropScope, clear, getCachingNodes } = this.props\r\n\r\n    return (\r\n      ...\r\n    )\r\n  }\r\n}\r\n...\r\n```\r\n\r\n---\r\n\r\n## Principle\r\n\r\nPass the `children` attribute of `<KeepAlive />` to `<AliveScope />` and render it with `<Keeper />`\r\n\r\nAfter rendering `<Keeper />`, the content is transferred to `<KeepAlive />` through `DOM` operation.\r\n\r\nSince `<Keeper />` will not be uninstalled, caching can be implemented.\r\n\r\n[Simplest Implementation Demo](https://codesandbox.io/s/zuijian-react-keepalive-shixian-ovh90)\r\n\r\n<img src=\"./docs/reactActivationPrinciple.gif\">\r\n\r\n---\r\n\r\n## Breaking Change\r\n\r\n1. `<KeepAlive />` needs to pass children to `<AliveScope />` , so the rendering of the real content will be **slower than the normal situation**\r\n\r\n   Will have a certain impact on the function of strictly relying on the lifecycle order, such as getting the value of `ref` in `componentDidMount`, as follows\r\n\r\n   ```javascript\r\n   class Test extends Component {\r\n     componentDidMount() {\r\n       console.log(this.outside) // will log <div /> instance\r\n       console.log(this.inside) // will log undefined\r\n     }\r\n\r\n     render() {\r\n       return (\r\n         <div>\r\n           <div\r\n             ref={ref => {\r\n               this.outside = ref\r\n             }}\r\n           >\r\n             Outside KeepAlive\r\n           </div>\r\n           <KeepAlive>\r\n             <div\r\n               ref={ref => {\r\n                 this.inside = ref\r\n               }}\r\n             >\r\n               Inside KeepAlive\r\n             </div>\r\n           </KeepAlive>\r\n         </div>\r\n       )\r\n     }\r\n   }\r\n   ```\r\n\r\n   The above error in `ClassComponent` can be fixed by using the `withActivation` high-level component\r\n\r\n   `FunctionComponent` currently has no processing method, you can use `setTimeout` or `nextTick` to delay ref getting behavior\r\n\r\n   ```javascript\r\n   @withActivation\r\n   class Test extends Component {\r\n     componentDidMount() {\r\n       console.log(this.outside) // will log <div /> instance\r\n       console.log(this.inside) // will log <div /> instance\r\n     }\r\n\r\n     render() {\r\n       return (\r\n         <div>\r\n           <div\r\n             ref={ref => {\r\n               this.outside = ref\r\n             }}\r\n           >\r\n             Outside KeepAlive\r\n           </div>\r\n           <KeepAlive>\r\n             <div\r\n               ref={ref => {\r\n                 this.inside = ref\r\n               }}\r\n             >\r\n               Inside KeepAlive\r\n             </div>\r\n           </KeepAlive>\r\n         </div>\r\n       )\r\n     }\r\n   }\r\n   ```\r\n\r\n2. Destructive impact on `Context`, need to be manually fixed\r\n\r\n   Problem reference: https://github.com/StructureBuilder/react-keep-alive/issues/36\r\n\r\n   ```javascript\r\n   <Provider value={1}>\r\n     {show && (\r\n       <KeepAlive>\r\n         <Consumer>\r\n           {(\r\n             context // Since the rendering level is broken, the context cannot be obtained here.\r\n           ) => <Test contextValue={context} />}\r\n         </Consumer>\r\n       </KeepAlive>\r\n     )}\r\n     <button onClick={toggle}>toggle</button>\r\n   </Provider>\r\n   ```\r\n\r\n   Choose a repair method\r\n\r\n   - Create `Context` using `createContext` exported from `react-activation`\r\n\r\n   - Fix the affected `Context` with `fixContext` exported from `react-activation`\r\n\r\n   ```javascript\r\n   ...\r\n   import { createContext } from 'react-activation'\r\n\r\n   const { Provider, Consumer } = createContext()\r\n   ...\r\n   // or\r\n   ...\r\n   import { createContext } from 'react'\r\n   import { fixContext } from 'react-activation'\r\n\r\n   const Context = createContext()\r\n   const { Provider, Consumer } = Context\r\n\r\n   fixContext(Context)\r\n   ...\r\n   ```\r\n\r\n3. Affects the functionality that depends on the level of the React component, as follows\r\n\r\n   - [x] [Fix `withRouter/hooks` of react-router](https://github.com/CJY0208/react-activation/issues/77)\r\n   - [x] ~~Error Boundaries~~ (Fixed)\r\n   - [x] ~~React.Suspense & React.lazy~~ (Fixed)\r\n   - [ ] React Synthetic Event Bubbling Failure\r\n   - [ ] Other undiscovered features\r\n\r\n---\r\n","readmeFilename":"README.md","gitHead":"0c736a46caf68c7ecbf5d0c4d1c59a165211d58e","bugs":{"url":"https://github.com/CJY0208/react-activation/issues"},"_id":"react-activation@0.8.0-beta.1","_npmVersion":"6.4.1","_nodeVersion":"12.6.0","_npmUser":{"name":"cjy0208","email":"fanluan058@gmail.com"},"dist":{"integrity":"sha512-YNzaykj7nrTHykQiUrXEv2Q0uljjtisayHY3owteQxw2CVeNqx4yMJ56Sc9npqP/pO/uIQ5Cc9BHVYVnvUPgYA==","shasum":"bd1c73d95dddc0feb39f89ee2ecbec319b421133","tarball":"http://registry-npm.ywwl.com/react-activation/download/react-activation-0.8.0-beta.1.tgz","fileCount":8,"unpackedSize":174608,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgFQSQCRA9TVsSAnZWagAAR6sP+gIOPEbEFXkfMxFEiFz1\nKa6FcpvGGAEA3O96Oxu7Nk25IcTPz61D7Q9HX17dofxy7OfjPgvGPLcHpszg\n8vu7NXaJYKd60r96NZrH4INDZjIv2o0h09Igm8nBURjic7S4dzxyp+JsnGKd\nR1PkpuabeIK7nr7AUeeHnON0HzwDNwsbpbDbwah/7ya7R8LM1om1WXVr1ERc\n2ZGcme4XPmDA6SEq6yxrmsgV6tUWxATz3INKhLpWeEByp1G0YWcuyOQs0PsG\nyaGRlBAoJihqgIaY4mkGMp2zu0DxH5vIbsxXhhibc996XmjKygiQb0rbWsqi\nBsGIZzXCEgVjgLfyCZAkOGjkglQl0RNZnuPR5jJpiohMuSk2IGu31zua/BBO\n8pfmgKqE90iymyCe6agVRklQeKh0WyypvrlJL8pt4UhIOONwbf3NfVZldbHP\nDy+0JtVm8pk5eA+PUyXBoSJw2q+fp4S4NgRGBjtcbPBQz4qOPeDADQYYZ7wM\n2ZxsnWf/5mSoYpJPDXoitwb2H0G1l2M8MsVDk6pQE7ORHCj5tQgParxNY5sa\nHH3/W8fHcvKwk4dJTQ+bROFqdseJRQEnUbK5xHaWl5OODHBXbU7A3FQUMcUp\nerVu+QoLhjaiMHKQ2s+FyxsdNInPjXkd+mKkKrMJmXCquHoO1XVEuXXiJX+Y\ntwAe\r\n=K60f\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIGLZ7G5V9BNdWX/5suGOQsfctDEtmZqwF9kK1Ivgo+vgAiEAgQWXj+NEju1XADvudNFrYYUd/7DVYVAEAaufGidDxyo="}],"size":48225,"noattachment":false,"key":"/react-activation/-/react-activation-0.8.0-beta.1.tgz"},"directories":{},"maintainers":[{"name":"cjy0208","email":"fanluan058@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/react-activation_0.8.0-beta.1_1611990159875_0.5855677546465385"},"_hasShrinkwrap":false,"publish_time":1611990159989,"_cnpm_publish_time":1611990159989,"dist-tags":{"beta":"0.8.0-beta.1","latest":"0.13.4"}}