{"name":"react-activation","version":"0.2.2","description":"<KeepAlive /> for React like <keep-alive /> in vue","main":"index.js","scripts":{"build":"rollup --config"},"keywords":["React Keep Alive","Keep Alive","keep-alive","KeepAlive","activation","react cache"],"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"},"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","rollup":"^1.11.3","rollup-plugin-babel":"^4.3.2","rollup-plugin-commonjs":"^10.1.0","rollup-plugin-node-resolve":"^4.2.3","rollup-plugin-uglify":"^6.0.2"},"gitHead":"4ef7af658a0b6e4b826da4ff31bd73f9e81675ab","bugs":{"url":"https://github.com/CJY0208/react-activation/issues"},"_id":"react-activation@0.2.2","_npmVersion":"6.4.1","_nodeVersion":"11.3.0","_npmUser":{"name":"cjy0208","email":"fanluan058@gmail.com"},"dist":{"integrity":"sha512-Ss8scakKE417UHUT3gahwn4ZF0xN86OxF1X0qnRD4Fn7Zy2eEH5U31gWX587nJb+2gTvoj/6GvzjsIChjI4Y8g==","shasum":"d18d99cdd4e3a75f84a96995ab055d941b8f149d","tarball":"http://registry-npm.ywwl.com/react-activation/download/react-activation-0.2.2.tgz","fileCount":10,"unpackedSize":114014,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdoEAdCRA9TVsSAnZWagAAFc0P/iXoWe6Pz1OvUcLkKpfM\n3BJc2pyqxqUmJHQg97k+gMqoCoV0wpuHSWTG9geVgmv2tsfMHZC3E75NFIY5\nDchQaZljJ6iR72BKz54gBu8/HrR+ZLm9lifrVIDT5qCzZDFeZcRHrQ4FsjU/\ng9xWiaz0kc8tBtXHsT15wKgCjfIgLZeq26kLPNNG5D8KrOcOgDQczmcWcD0B\nVBPychwErwjtJC7ApUu3SzJDoJnHXtZ7IEaMf+ra5jibAhptbCqoaZUfh4pY\nD3fC5r5na1Pq/lDkVLnCV3R/DwRb79FAuR7kFQi+S0U4/TJzYA6mP5lMROj5\nQj4aQPJPdpOmg4e2k+Xq2cjDg8AWrA1r3MTjVQxPMZ5OuCX62Iv2q/DRftHy\ncYyVVG7E0lU/vXyccfcCzlszdLNjCRTgoXJdKDmL4FP92ad7ET+lkL/8VsGy\ngo6xuBgoTN98JR0geUP88y3e6aI/qMpmWH8902QX2FMi+AWKtI8wrV6vmRV5\n83OXCavvNc+IQtn2xNrJiGWmBJyUvn4cqe2i+F3Sn9+toWyahgWgqxJV2IqC\nJ8NXoOLzyW61EPQ6HfCOZPPrbHlBLY+DHXdiYB6Mi5qoRyTpWJpzFLUUnsSG\n4DK1DovCD2musjh0ZJ4YW+quw5x7SwqnJEX+xbk54i4XK2IPpl2YgizYiORI\nfdJF\r\n=QSjl\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCICUB1y1ebgHEOozjrLQ+DrfHWdBaddnwSIIIMIaJru46AiEAlVstyFQqwK92mz/FVevx+M8Nv+/ZUHItQU131hzi/8g="}],"size":28901,"noattachment":false,"key":"/react-activation/-/react-activation-0.2.2.tgz"},"maintainers":[{"name":"cjy0208","email":"fanluan058@gmail.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/react-activation_0.2.2_1570783260374_0.07584943235333408"},"_hasShrinkwrap":false,"readme":"### NOTICE\n\n- DO NOT use `<React.StrictMode />`\n- (React v18+) DO NOT use `ReactDOMClient.createRoot`, use `ReactDOM.render` instead, https://github.com/CJY0208/react-activation/issues/225#issuecomment-1311136388\n\n# React Activation\n\n[![size](https://img.shields.io/bundlephobia/minzip/react-activation@latest.svg)](https://bundlephobia.com/result?p=react-activation@latest)\n[![dm](https://img.shields.io/npm/dm/react-activation.svg)](https://github.com/CJY0208/react-activation)\n![](https://visitor-badge.glitch.me/badge?page_id=cjy0208.react-activation)\n\nEnglish | [中文说明](./README_CN.md)\n\n**HACK Implementation** of the `<keep-alive />` function in `Vue` For `React`\n\nPlease also pay attention to official support [`<Offsreen />`](https://github.com/reactwg/react-18/discussions/19) in `React 18.x`\n\n---\n\nMore stable `<KeepAlive />` function with `babel` pre-compilation\n\n[Online Demo](https://codesandbox.io/s/affectionate-beaver-solkt)\n\n<img src=\"./docs/basicReactActivation.gif\">\n\n---\n\n## More examples\n\n- [Closable tabs with `react-router`](https://codesandbox.io/s/keguanbideyifangwenluyou-tab-shilikeanluyoucanshufenduofenhuancun-ewycx)\n- [Closable tabs with `umi`](https://codesandbox.io/s/umi-keep-alive-tabs-demo-knfxy)\n- [Using Animation with `react-router`](https://codesandbox.io/s/luyouzhuanchangdonghuashili-jdhq1)\n\n---\n\n## Compatibility\n\n- React v16 / v17 / v18\n\n- Preact v10+\n\n- Compatible with SSR\n\n---\n\n## Install\n\n```bash\nyarn add react-activation\n# or\nnpm install react-activation\n```\n\n---\n\n## Usage\n\n#### 1. (Optional, Recommended) Add `react-activation/babel` plugins in `.babelrc`\n\n[Why is it needed?](https://github.com/CJY0208/react-activation/issues/18#issuecomment-564360695)\n\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).\n\n```javascript\n{\n  \"plugins\": [\n    \"react-activation/babel\"\n  ]\n}\n```\n\n**(0.11.0+)** If you don't want to use Babel, it is recommended that each `<KeepAlive>` declare a globally unique and invariant `cacheKey` attribute to ensure the stability of the cache, as follows:\n\n```jsx\n<KeepAlive cacheKey=\"UNIQUE_ID\" />\n```\n\n#### 2. Wrap the components that need to keep states with `<KeepAlive>`\n\nLike the `<Counter>` component in the example\n\n```javascript\n// App.js\n\nimport React, { useState } from 'react'\nimport KeepAlive from 'react-activation'\n\nfunction Counter() {\n  const [count, setCount] = useState(0)\n\n  return (\n    <div>\n      <p>count: {count}</p>\n      <button onClick={() => setCount(count => count + 1)}>Add</button>\n    </div>\n  )\n}\n\nfunction App() {\n  const [show, setShow] = useState(true)\n\n  return (\n    <div>\n      <button onClick={() => setShow(show => !show)}>Toggle</button>\n      {show && (\n        <KeepAlive>\n          <Counter />\n        </KeepAlive>\n      )}\n    </div>\n  )\n}\n\nexport default App\n```\n\n#### 3. Place the `<AliveScope>` outer layer at a location that will not be unmounted, usually at the application entrance\n\nNote: When used with `react-router` or `react-redux`, you need to place `<AliveScope>` inside `<Router>` or `<Provider>`\n\n```javascript\n// index.js\n\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport { AliveScope } from 'react-activation'\n\nimport App from './App'\n\nReactDOM.render(\n  <AliveScope>\n    <App />\n  </AliveScope>,\n  document.getElementById('root')\n)\n```\n\n---\n\n## Lifecycle\n\n`ClassComponent` works with `withActivation` decorator\n\nUse `componentDidActivate` and `componentWillUnactivate` to correspond to the two states of \"activate\" and \"unactivate\" respectively.\n\n`FunctionComponent` uses the `useActivate` and `useUnactivate` hooks respectively\n\n```javascript\n...\nimport KeepAlive, { useActivate, useUnactivate, withActivation } from 'react-activation'\n\n@withActivation\nclass TestClass extends Component {\n  ...\n  componentDidActivate() {\n    console.log('TestClass: componentDidActivate')\n  }\n\n  componentWillUnactivate() {\n    console.log('TestClass: componentWillUnactivate')\n  }\n  ...\n}\n...\nfunction TestFunction() {\n  useActivate(() => {\n    console.log('TestFunction: didActivate')\n  })\n\n  useUnactivate(() => {\n    console.log('TestFunction: willUnactivate')\n  })\n  ...\n}\n...\nfunction App() {\n  ...\n  return (\n    {show && (\n      <KeepAlive>\n        <TestClass />\n        <TestFunction />\n      </KeepAlive>\n    )}\n  )\n}\n...\n```\n\n---\n\n## Cache Control\n\n### Manually control the cache\n\n1. Add the `name` attribute to the `<KeepAlive>` tag that needs to control the cache.\n\n2. Get control functions using `withAliveScope` or `useAliveController`.\n\n   - **drop(name)**: (`drop` can only be used for nodes in the cache state. If the node is not cached but needs to clear the cache state, please use `refresh`)\n\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>`.\n\n   - **dropScope(name)**: (`dropScope` can only be used for nodes in the cache state. If the node is not cached but needs to clear the cache state, please use `refreshScope`)\n\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>`.\n\n   - **refresh(name)**:\n\n     Refresh 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 refreshed and will not be uninstalled in `<KeepAlive>`. Would not refresh nested `<KeepAlive>`.\n\n   - **refreshScope(name)**:\n\n     Refresh the `<KeepAlive>` node in cache state by name. The name optional type is `String` or `RegExp`, which will refresh all content of `<KeepAlive>`, including all `<KeepAlive>` nested in `<KeepAlive>`.\n\n\n   - **clear()**:\n\n     will clear all `<KeepAlive>` in the cache\n\n   - **getCachingNodes()**:\n\n     Get all the nodes in the cache\n\n```javascript\n...\nimport KeepAlive, { withAliveScope, useAliveController } from 'react-activation'\n...\n<KeepAlive name=\"Test\">\n  ...\n    <KeepAlive>\n      ...\n        <KeepAlive>\n          ...\n        </KeepAlive>\n      ...\n    </KeepAlive>\n  ...\n</KeepAlive>\n...\nfunction App() {\n  const { drop, dropScope, clear, getCachingNodes } = useAliveController()\n\n  useEffect(() => {\n    drop('Test')\n    // or\n    drop(/Test/)\n    // or\n    dropScope('Test')\n\n    clear()\n  })\n\n  return (\n    ...\n  )\n}\n// or\n@withAliveScope\nclass App extends Component {\n  render() {\n    const { drop, dropScope, clear, getCachingNodes } = this.props\n\n    return (\n      ...\n    )\n  }\n}\n...\n```\n\n---\n\n### Automatic control cache\n\nAdd the `when` attribute to the `<KeepAlive />` tag that needs to control the cache. The value is as follows\n\n#### When the `when` type is `Boolean`\n\n- **true**: Cache after uninstallation\n- **false**: Not cached after uninstallation\n\n```javascript\n<KeepAlive when={false}>\n```\n\n#### When the `when` type is `Array`\n\nThe **1th** parameter indicates whether it needs to be cached at the time of uninstallation.\n\nThe **2th** parameter indicates whether to unload all cache contents of `<KeepAlive>`, including all `<KeepAlive>` nested in `<KeepAlive>`.\n\n```javascript\n// For example:\n// The following indicates that it is not cached when uninstalling\n// And uninstalls all nested `<KeepAlive>`\n<KeepAlive when={[false, true]}>\n  ...\n  <KeepAlive>\n    ...\n    <KeepAlive>...</KeepAlive>\n    ...\n  </KeepAlive>\n  ...\n</KeepAlive>\n```\n\n#### When the `when` type is `Function` (**Recommended**)\n\nThe return value is the above `Boolean` or `Array`, which takes effect as described above.\n\nThe final calculation time of `when` is adjusted to `componentWillUnmount` lifecicle of `<KeepAlive>`, the problem that most of the `when` do not achieve the expected effect can be avoided.\n\n```jsx\n<KeepAlive when={() => true}>\n<KeepAlive when={() => [false, true]}>\n```\n\n---\n\n## Multiple Cache\n\nUnder the same parent node, `<KeepAlive>` in the same location will use the same cache by default.\n\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.\n\n```javascript\n<Route\n  path=\"/item/:id\"\n  render={props => (\n    <KeepAlive>\n      <Item {...props} />\n    </KeepAlive>\n  )}\n/>\n```\n\nSimilar scenarios, you can use the `id` attribute of `<KeepAlive>` to implement multiple caches according to specific conditions.\n\n```javascript\n<Route\n  path=\"/item/:id\"\n  render={props => (\n    <KeepAlive id={props.match.params.id}>\n      <Item {...props} />\n    </KeepAlive>\n  )}\n/>\n```\n\n---\n\n## Save Scroll Position (`true` by default)\n\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`\n\nIf you don't want `<KeepAlive />` to do this thing, set `saveScrollPosition` prop to `false`\n\n```javascript\n<KeepAlive saveScrollPosition={false} />\n```\n\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`\n\n```javascript\n<KeepAlive saveScrollPosition=\"screen\" />\n```\n\n---\n\n## Principle\n\nPass the `children` attribute of `<KeepAlive />` to `<AliveScope />` and render it with `<Keeper />`\n\nAfter rendering `<Keeper />`, the content is transferred to `<KeepAlive />` through `DOM` operation.\n\nSince `<Keeper />` will not be uninstalled, caching can be implemented.\n\n[Simplest Implementation Demo](https://codesandbox.io/s/zuijian-react-keepalive-shixian-ovh90)\n\n<img src=\"./docs/reactActivationPrinciple.gif\">\n\n---\n\n## Breaking Change\n\n1. `<KeepAlive />` needs to pass children to `<AliveScope />` , so the rendering of the real content will be **slower than the normal situation**\n\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\n\n   ```javascript\n   class Test extends Component {\n     componentDidMount() {\n       console.log(this.outside) // will log <div /> instance\n       console.log(this.inside) // will log undefined\n     }\n\n     render() {\n       return (\n         <div>\n           <div\n             ref={ref => {\n               this.outside = ref\n             }}\n           >\n             Outside KeepAlive\n           </div>\n           <KeepAlive>\n             <div\n               ref={ref => {\n                 this.inside = ref\n               }}\n             >\n               Inside KeepAlive\n             </div>\n           </KeepAlive>\n         </div>\n       )\n     }\n   }\n   ```\n\n   The above error in `ClassComponent` can be fixed by using the `withActivation` high-level component\n\n   `FunctionComponent` currently has no processing method, you can use `setTimeout` or `nextTick` to delay ref getting behavior\n\n   ```javascript\n   @withActivation\n   class Test extends Component {\n     componentDidMount() {\n       console.log(this.outside) // will log <div /> instance\n       console.log(this.inside) // will log <div /> instance\n     }\n\n     render() {\n       return (\n         <div>\n           <div\n             ref={ref => {\n               this.outside = ref\n             }}\n           >\n             Outside KeepAlive\n           </div>\n           <KeepAlive>\n             <div\n               ref={ref => {\n                 this.inside = ref\n               }}\n             >\n               Inside KeepAlive\n             </div>\n           </KeepAlive>\n         </div>\n       )\n     }\n   }\n   ```\n\n2. Destructive impact on `Context`\n\n   after `react-actication@0.8.0` with `react@16.3+`, this question has been automatic fixed\n\n   `react-actication@0.8.0` with `react@17+` you Need to make the following changes to achieve automatic repair\n\n   ```jsx\n   import { autoFixContext } from 'react-activation'\n\n   autoFixContext(\n    [require('react/jsx-runtime'), 'jsx', 'jsxs', 'jsxDEV'],\n    [require('react/jsx-dev-runtime'), 'jsx', 'jsxs', 'jsxDEV']\n   )\n   ```\n   \n   Versions below `react-actication@0.8.0` need to be repaired manually, refer to the following\n\n   Problem reference: https://github.com/StructureBuilder/react-keep-alive/issues/36\n\n   ```javascript\n   <Provider value={1}>\n     {show && (\n       <KeepAlive>\n         <Consumer>\n           {(\n             context // Since the rendering level is broken, the context cannot be obtained here.\n           ) => <Test contextValue={context} />}\n         </Consumer>\n       </KeepAlive>\n     )}\n     <button onClick={toggle}>toggle</button>\n   </Provider>\n   ```\n\n   Choose a repair method\n\n   - Create `Context` using `createContext` exported from `react-activation`\n\n   - Fix the affected `Context` with `fixContext` exported from `react-activation`\n\n   ```javascript\n   ...\n   import { createContext } from 'react-activation'\n\n   const { Provider, Consumer } = createContext()\n   ...\n   // or\n   ...\n   import { createContext } from 'react'\n   import { fixContext } from 'react-activation'\n\n   const Context = createContext()\n   const { Provider, Consumer } = Context\n\n   fixContext(Context)\n   ...\n   ```\n\n3. Affects the functionality that depends on the level of the React component, as follows\n\n   - [x] [Fix `withRouter/hooks` of react-router](https://github.com/CJY0208/react-activation/issues/77)\n   - [x] ~~Error Boundaries~~ (Fixed)\n   - [x] ~~React.Suspense & React.lazy~~ (Fixed)\n   - [ ] React Synthetic Event Bubbling Failure\n   - [ ] Other undiscovered features\n\n---\n","publish_time":1570783260491,"_cnpm_publish_time":1570783260491,"dist-tags":{"beta":"0.8.0-beta.1","latest":"0.13.4"}}