{"name":"react-activation","version":"0.7.4","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"},"_id":"react-activation@0.7.4","dist":{"shasum":"c65f8617f089527c0b976f51580d9587b2eb667d","integrity":"sha512-go/UEuRW03jOaFM3NUc1doByzUBbrCyIHGEFNJ0tAqA2AKzmMyh0Ru8XVEY3PB1/ev9dYgRWfAiXeqyKn1kavg==","tarball":"http://registry-npm.ywwl.com/react-activation/download/react-activation-0.7.4.tgz","fileCount":11,"unpackedSize":175723,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJgE8+ACRA9TVsSAnZWagAAIb4P/2LJgOJfnviQa9LUvlIm\n8l1GI5fRRkFbN/ZXyVeQZVUnfUH81COxGIRkCnndQBRs+lhwGlfqGJNiGnVq\nkGJpbxGfEooaywUZOKPrtvMFHANjDIOksU+WXq8BMKmQymli7+23Zx5VpC/k\nd1C3WwVZCqeoBRh8GceRe51WGPjj3rxFvM5xWvRHTrsN1aaYW3Od6wF7uHEw\nJFTb/uT9vX3/BVcH2UsFwWJGsezjiUHvpQTT6TWPGDSudkfp/GTez/60jAsA\nXZSpg+onopPBmCgT7p8NAVguh/KemM79oY04cyEMgg/xUksvIV5uVuc4+nij\neeidWlEWqt6x/iyHDS78Lcanx5p9bI+P8LlN8biGTZyIrzImQjmWTqMiHncC\n7F63GwM7YZ4wQGL3apM9QknbfuRLLj0cVw02+seESq/5OMmmV/go/aeS5v6w\nPyy1Y4sjHlC5dwTfVVg56E+hWwCJtA0jcs0AJZ3lLMJOCQ4PmaFF3j3+2lA3\nrCyKHOJ/jFHdTqF84MHzlwHVaTWQVOs+9ZPZn05eTxrpwX+AdDGZJHoDHMSr\nGnH+S7TF9xnrMlkHPbvbVL1ZndBpMR3MRhLWTLTx5pmJws4OfO61SoxMAk5/\nycdsdGH0blwCI/aQvnILjyADeW3bc4dz+iuLv+MTOmmmyEJxKqHaEyEzJIPw\nwJWi\r\n=V0vs\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIBO+6AlhAXOo8nMsQMnSWL3UtaLix8I9M+ZTbOsxkiDYAiEAjeB43lPXXZ0pKZuiZNHwu3j2PBX8emgvI/EFt5Q+KbM="}],"size":48159,"noattachment":false,"key":"/react-activation/-/react-activation-0.7.4.tgz"},"_npmUser":{"name":"cjy0208","email":"fanluan058@gmail.com"},"directories":{},"maintainers":[{"name":"cjy0208","email":"fanluan058@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/react-activation_0.7.4_1611911040037_0.8368886519656729"},"_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":1611911040239,"_cnpm_publish_time":1611911040239,"dist-tags":{"beta":"0.8.0-beta.1","latest":"0.13.4"}}