{"name":"use-sidecar","version":"1.1.3","description":"Sidecar code splitting utils","module:es2019":"dist/es2019/index.js","main":"dist/es5/index.js","module":"dist/es2015/index.js","types":"dist/es5/index.d.ts","devDependencies":{"@size-limit/preset-small-lib":"^11.0.2","size-limit":"^11.0.2","@theuiteam/lib-builder":"^0.1.4","@types/enzyme-adapter-react-16":"^1.0.6","enzyme-adapter-react-16":"^1.15.6","react":"^16.8.6","react-dom":"^16.8.6"},"engines":{"node":">=10"},"scripts":{"dev":"lib-builder dev","test":"jest","test:ci":"jest --runInBand --coverage","build":"lib-builder build && yarn size:report","release":"yarn build && yarn test","size":"npx size-limit","size:report":"npx size-limit --json > .size.json","lint":"lib-builder lint","format":"lib-builder format","update":"lib-builder update","prepublish":"yarn build && yarn changelog","changelog":"conventional-changelog -p angular -i CHANGELOG.md -s","changelog:rewrite":"conventional-changelog -p angular -i CHANGELOG.md -s -r 0"},"peerDependencies":{"@types/react":"*","react":"^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc"},"sideEffects":["**/medium.js"],"keywords":["code spliting","react","sidecar"],"homepage":"https://github.com/theKashey/use-sidecar","author":{"name":"theKashey","email":"thekashey@gmail.com"},"license":"MIT","dependencies":{"detect-node-es":"^1.1.0","tslib":"^2.0.0"},"peerDependenciesMeta":{"@types/react":{"optional":true}},"repository":{"type":"git","url":"git+https://github.com/theKashey/use-sidecar.git"},"husky":{"hooks":{"pre-commit":"lint-staged"}},"lint-staged":{"*.{ts,tsx}":["prettier --write","eslint --fix","git add"],"*.{js,css,json,md}":["prettier --write","git add"]},"resolutions":{"@types/react":"^19.0.0"},"prettier":{"printWidth":120,"trailingComma":"es5","tabWidth":2,"semi":true,"singleQuote":true},"_id":"use-sidecar@1.1.3","gitHead":"0ceffd96208b62a66883fd472fa48a2ccd4acaa8","bugs":{"url":"https://github.com/theKashey/use-sidecar/issues"},"_nodeVersion":"20.15.1","_npmVersion":"10.7.0","dist":{"integrity":"sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==","shasum":"10e7fd897d130b896e2c546c63a5e8233d00efdb","tarball":"http://registry-npm.ywwl.com/use-sidecar/download/use-sidecar-1.1.3.tgz","fileCount":57,"unpackedSize":49637,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIFahq9050Rb6W4wiaYdlWW+y5zjzR2ubEnq/AD0T2lGFAiEA+80iLba7gUdKbi3Wq1RHDiEPvDSxjnwPYQgrFSXzo7I="}],"size":11241,"noattachment":false,"key":"/use-sidecar/-/use-sidecar-1.1.3.tgz"},"_npmUser":{"name":"kashey","email":"thekashey@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/use-sidecar_1.1.3_1734227359197_0.31381004526481737"},"_hasShrinkwrap":false,"readme":"<div align=\"center\">\n  <h1>🏎 side car</h1>\n  <br/>\n   Alternative way to code splitting\n  <br/>\n  \n  <a href=\"https://www.npmjs.com/package/use-sidecar\">\n    <img src=\"https://img.shields.io/npm/v/use-sidecar.svg?style=flat-square\" />\n  </a>\n    \n  <a href=\"https://travis-ci.org/theKashey/use-sidecar\">\n   <img src=\"https://img.shields.io/travis/theKashey/use-sidecar.svg?style=flat-square\" alt=\"Build status\">\n  </a> \n\n  <a href=\"https://www.npmjs.com/package/use-sidecar\">\n   <img src=\"https://img.shields.io/npm/dm/use-sidecar.svg\" alt=\"npm downloads\">\n  </a> \n\n  <a href=\"https://bundlephobia.com/result?p=use-sidecar\">\n   <img src=\"https://img.shields.io/bundlephobia/minzip/use-sidecar.svg\" alt=\"bundle size\">\n  </a>   \n  <br/>\n</div>\n\nUI/Effects code splitting pattern\n - [read the original article](https://dev.to/thekashey/sidecar-for-a-code-splitting-1o8g) to understand concepts behind.\n - [read how Google](https://medium.com/@cramforce/designing-very-large-javascript-applications-6e013a3291a3) split view and logic.\n - [watch how Facebook](https://developers.facebook.com/videos/2019/building-the-new-facebookcom-with-react-graphql-and-relay/) defers \"interactivity\" effects. \n\n## Terminology: \n- `sidecar` - non UI component, which may carry effects for a paired UI component.\n- `UI` - UI component, which interactivity is moved to a `sidecar`.\n\n`UI` is a _view_, `sidecar` is the _logic_ for it. Like Batman(UI) and his sidekick Robin(effects). \n\n## Concept\n- a `package` exposes __3 entry points__ using a [nested `package.json` format](https://github.com/theKashey/multiple-entry-points-example):\n  - default aka `combination`, and lets hope tree shaking will save you\n  - `UI`, with only UI part\n  - `sidecar`, with all the logic\n  - > `UI` + `sidecar` === `combination`. The size of `UI+sidecar` might a bit bigger than size of their `combination`.\n  Use [size-limit](https://github.com/ai/size-limit) to control their size independently. \n  \n\n- package uses a `medium` to talk with own sidecar, breaking explicit dependency.\n \n- if package depends on another _sidecar_ package:\n  - it shall export dependency side car among own sidecar.\n  - package imports own sidecar via `medium`, thus able to export multiple sidecars via one export. \n\n- final consumer uses `sidecar` or `useSidecar` to combine pieces together.  \n\n## Rules\n- `UI` components might use/import any other `UI` components\n- `sidecar` could use/import any other `sidecar`\n\nThat would form two different code branches, you may load separately - UI first, and effect sidecar later.\nThat also leads to a obvious consequence - __one sidecar may export all sidecars__.\n- to decouple `sidecars` from module exports, and be able to pick \"the right\" one at any point\nyou have to use `exportSidecar(medium, component)` to export it, and use the same `medium` to import it back.\n- this limitation is for __libraries only__, as long as in the usercode you might \ndynamically import whatever and whenever you want. \n\n- `useMedium` is always async - action would be executed in a next tick, or on the logic load.\n- `sidecar` is always async - is does not matter have you loaded logic or not - component would be \nrendered at least in the next tick.\n\n> except `medium.read`, which synchronously read the data from a medium, \nand `medium.assingSyncMedium` which changes `useMedium` to be sync. \n\n## SSR and usage tracking\nSidecar pattern is clear:\n- you dont need to use/render any `sidecars` on server.\n- you dont have to load `sidecars` prior main render.\n\nThus - no usage tracking, and literally no SSR. It's just skipped.\n\n\n# API\n\n## createMedium()\n- Type: Util. Creates shared effect medium for algebraic effect.\n- Goal: To decouple modules from each other.\n- Usage: `use` in UI side, and `assign` from side-car. All effects would be executed.\n- Analog: WeakMap, React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n```js\nconst medium = createMedium(defaultValue);\nconst cancelCb = medium.useMedium(someData);\n\n// like\nuseEffect(() => medium.useMedium(someData), []);\n\nmedium.assignMedium(someDataProcessor)\n\n// createSidecarMedium is a helper for createMedium to create a \"sidecar\" symbol\nconst effectCar = createSidecarMedium();\n```\n\n> ! For consistence `useMedium` is async - sidecar load status should not affect function behavior,\nthus effect would be always executed at least in the \"next tick\". You may alter\nthis behavior by using `medium.assingSyncMedium`.\n\n\n## exportSidecar(medium, component)\n- Type: HOC\n- Goal: store `component` inside `medium` and return external wrapper\n- Solving: decoupling module exports to support exporting multiple sidecars via a single entry point.\n- Usage: use to export a `sidecar`\n- Analog: WeakMap\n```js\nimport {effectCar} from './medium';\nimport {EffectComponent} from './Effect';\n// !!! - to prevent Effect from being imported\n// `effectCar` medium __have__ to be defined in another file\n// const effectCar = createSidecarMedium();\nexport default exportSidecar(effectCar, EffectComponent);\n```\n\n## sidecar(importer)\n- Type: HOC\n- Goal: React.lazy analog for code splitting, but does not require `Suspense`, might provide error failback.\n- Usage: like React.lazy to load a side-car component.\n- Analog: React.Lazy\n```js\nimport {sidecar} from \"use-sidecar\";\nconst Sidecar =  sidecar(() => import('./sidecar'), <span>on fail</span>);\n\n<>\n <Sidecar />\n <UI />\n</> \n```\n### Importing `exportedSidecar`\nWould require additional prop to be set - ```<Sidecar sideCar={effectCar} />```\n\n## useSidecar(importer)\n- Type: hook, loads a `sideCar` using provided `importer` which shall follow React.lazy API\n- Goal: to load a side car without displaying any \"spinners\".\n- Usage: load side car for a component\n- Analog: none\n```js\nimport {useSidecar} from 'use-sidecar';\n\nconst [Car, error] = useSidecar(() => import('./sideCar'));\nreturn (\n  <>\n    {Car ? <Car {...props} /> : null}\n    <UIComponent {...props}>\n  </>\n); \n```\n### Importing `exportedSideCar`\nYou have to specify __effect medium__ to read data from, as long as __export itself is empty__.\n```js\nimport {useSidecar} from 'use-sidecar';\n\n/* medium.js: */ export const effectCar = useMedium({});\n/* sideCar.js: */export default exportSidecar(effectCar, EffectComponent);\n\nconst [Car, error] = useSidecar(() => import('./sideCar'), effectCar); \nreturn (\n  <>\n    {Car ? <Car {...props} /> : null}\n    <UIComponent {...props}>\n  </>\n);\n```\n\n## renderCar(Component)\n- Type: HOC, moves renderProp component to a side channel\n- Goal: Provide render prop support, ie defer component loading keeping tree untouched.\n- Usage: Provide `defaults` and use them until sidecar is loaded letting you code split (non visual) render-prop component\n- Analog: - Analog: code split library like [react-imported-library](https://github.com/theKashey/react-imported-library) or [@loadable/lib](https://www.smooth-code.com/open-source/loadable-components/docs/library-splitting/).\n```js\nimport {renderCar, sidecar} from \"use-sidecar\";\nconst RenderCar = renderCar(\n  // will move side car to a side channel\n  sidecar(() => import('react-powerplug').then(imports => imports.Value)),\n  // default render props\n  [{value: 0}]  \n);\n\n<RenderCar>\n  {({value}) => <span>{value}</span>}\n</RenderCar>\n```\n\n## setConfig(config)\n```js\nsetConfig({\n  onError, // sets default error handler\n});\n```\n\n# Examples\n## Deferred effect\nLet's imagine - on element focus you have to do \"something\", for example focus anther element\n\n#### Original code\n```js\nonFocus = event => {\n  if (event.currentTarget === event.target) {\n    document.querySelectorAll('button', event.currentTarget)\n  }\n}\n```\n\n#### Sidecar code\n\n3. Use medium (yes, .3)\n```js\n// we are calling medium with an original event as an argument\nconst onFocus = event => focusMedium.useMedium(event);\n```\n2. Define reaction\n```js\n// in a sidecar\n\n// we are setting handler for the effect medium\n// effect is complicated - we are skipping event \"bubbling\", \n// and focusing some button inside a parent\nfocusMedium.assignMedium(event => {\n  if (event.currentTarget === event.target) {\n    document.querySelectorAll('button', event.currentTarget)\n  }\n});\n\n```\n1. Create medium\nHaving these constrains - we have to clone `event`, as long as React would eventually reuse SyntheticEvent, thus not\npreserve `target` and `currentTarget`. \n```js\n// \nconst focusMedium = createMedium(null, event => ({...event}));\n```\nNow medium side effect is ok to be async\n\n__Example__: [Effect for react-focus-lock](https://github.com/theKashey/react-focus-lock/blob/8c69c644ecfeed2ec9dc0dc4b5b30e896a366738/src/Lock.js#L48) - 1kb UI, 4kb sidecar\n\n### Medium callback\nLike a library level code splitting\n\n#### Original code\n```js\nimport {x, y} from './utils';\n\nuseEffect(() => {\n  if (x()) {\n    y()\n  }\n}, []);\n```\n\n#### Sidecar code\n\n```js\n// medium\nconst utilMedium = createMedium();\n\n// utils\nconst x = () => { /* ... */};\nconst y = () => { /* ... */};\n\n// medium will callback with exports exposed\nutilMedium.assignMedium(cb => cb({\n x, y\n}));\n\n\n// UI\n// not importing x and y from the module system, but would be given via callback\nuseEffect(() => {\n  utilMedium.useMedium(({x,y}) => {\n      if (x()) {\n        y()\n      }\n  })\n}, []);\n```\n\n- Hint: there is a easy way to type it\n```js\nconst utilMedium = createMedium<(cb: typeof import('./utils')) => void>();\n``` \n\n__Example__: [Callback API for react-focus-lock](https://github.com/theKashey/react-focus-lock/blob/8c69c644ecfeed2ec9dc0dc4b5b30e896a366738/src/MoveFocusInside.js#L12) \n\n### Split effects\nLets take an example from a Google - Calendar app, with view and logic separated.\nTo be honest - it's not easy to extract logic from application like calendar - usually it's tight coupled.\n\n#### Original code\n```js\nconst CalendarUI = () => { \n  const [date, setDate] = useState();\n  const onButtonClick = useCallback(() => setDate(Date.now), []);\n  \n  return (\n    <>\n     <input type=\"date\" onChange={setDate} value={date} />\n     <input type=\"button\" onClick={onButtonClick}>Set Today</button>\n    </>\n  )\n}\n```\n#### Sidecar code\n\n```js\nconst CalendarUI = () => {\n  const [events, setEvents] = useState({});\n  const [date, setDate] = useState();\n  \n  return (\n    <>\n     <Sidecar setDate={setDate} setEvents={setEvents}/>\n     <UILayout {...events} date={date}/>\n    </>\n  )\n}\n\nconst UILayout = ({onDateChange, onButtonClick, date}) => (\n  <>\n      <input type=\"date\" onChange={onDateChange} value={date} />\n      <input type=\"button\" onClick={onButtonClick}>Set Today</button>\n  </>\n);\n\n// in a sidecar\n// we are providing callbacks back to UI\nconst Sidecar = ({setDate, setEvents}) => {\n  useEffect(() => setEvents({\n      onDateChange:setDate,\n      onButtonClick: () => setDate(Date.now),\n  }), []);\n  \n  return null;\n}\n```  \n\nWhile in this example this looks a bit, you know, strange - there are 3 times more code\nthat in the original example - that would make a sense for a real Calendar, especially\nif some helper library, like `moment`, has been used.\n\n__Example__: [Effect for react-remove-scroll](https://github.com/theKashey/react-remove-scroll/blob/666472d5c77fb6c4e5beffdde87c53ae63ef42c5/src/SideEffect.tsx#L166) - 300b UI, 2kb sidecar\n\n# Licence\n\nMIT\n\n","publish_time":1734227359375,"maintainers":[{"name":"kashey","email":"thekashey@gmail.com"}],"_cnpm_publish_time":1734227359375,"dist-tags":{"latest":"1.1.3"}}