Skip to content

Commit

Permalink
useStream
Browse files Browse the repository at this point in the history
  • Loading branch information
ArthurClemens committed Feb 27, 2020
0 parents commit a7501e8
Show file tree
Hide file tree
Showing 18 changed files with 514 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
node_modules
.DS_Store
npm-debug.log*
*.log
*.lock
package-lock.json
.rpt2_cache
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Arthur Clemens

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
159 changes: 159 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
# useStream

A React hook to work with streams.

Motivation: [Hooks and Streams](https://james-forbes.com/#!/posts/hooks-and-streams) by James Forbes. While the example code in this article uses [Mithril](https://mithril.js.org), `useStream` allows you to use streams in React applications.

## Features

* Enables React rendering whenever streams are updated
* `onMount` callback function for creating side effects
* `onDestroy` callback function for cleaning up (for example stopping streams)

Streams are memoized so that they are initialized only once.


## Usage

`npm install use-stream`

You can use any stream library. In these examples we'll use the lightweight stream module from Mithril, which comes separate from Mithril core code.

`npm install mithril`


## API

`useStream({ model, onMount?, onDestroy? }) => model`

`model` is a POJO object with streams as values:

```js
const count = useStream({
model: {
count: stream(0),
}
})
```

`onMount` is an optional callback function to be called at mount:

```
onMount: (model) => {
// any side effects
}
```

`onDestroy` is an optional callback function to be called when the stream gets out of scope:

```
onDestroy: (model) => {
// cleanup, for example:
// model.count.end(true)
}
```

## Examples

### Simple counter

[Live code example](https://flems.io/#0=N4IgtglgJlA2CmIBcAWAnAOgAwFYA0IAxgPYB2AzsQskVbAIYAO58UIB5hATncgNpY8WALoEAZhATl+oUvTCIkIDAAsALmFjtapNfF00APFAgA3AATQAvAB0QTRnYB8hgPQnTT7SwSE1EMmklLCQAJiwQAF88WXlFZQAraQISXX01GlTyNXNsrnh5cytzAHcIUihiEowwDDyCsBtSCDBGYi4c4HMAVxYAZTV8wsjzMR4wczsMV174AaHGkCamrJywYih4WCLzAAoASiKnJvMe-sGG3eAT0-N1zdgkc2vSW9uSbt0n+vldrH28DdTpEbpF9stSKtzAAFegAc3gO0YPGYR2eNyhXQ+unMI2Ks3mlxeb3uWyexLe5mxam+F1+-0Br1uIKZYJuN3yam6XFeuyB5mMZipDHI5AAcnFbCBGPD4M5+adDCoAIxOYDUg6RNwq45Mt6GRi6ym3QwAI26ajUZAVlLIAGFYBBCABrKzAA5ojUaw4AWnMyv2LONbxM5HopoQUDd3qKVmKWCDwacABF4Nx4ApdG5zZayEbg2aLVbSDa3vbHS63R6rE4qcRPmpdjGANT+wOl8xOACSkPymbU2aLeZtbkN-LcHnz4NILJWgRyAEFGIwdtXaxTOdzXoZYQjzK5dbPSAAlAp+ZMAeQAshh8hV4FxdoYlyuD3hzA5p9oSK1JA+aKa4ZbN4Wxpv4gQ0KEADMSBQRE0SxAoNAEnStRJN+ZB6AYSgQvAAAebQdHWFA5ChCyrl0pKwO+ZBXvWug0aQqZ5MQACeuKHDW6JMlCCjrDsp70H4GCzKeYi7FR06nBepoJGBGDOvArHkBJGxbPsGBiO0ACiQkqLszpot0jBQPQeiqQ8fDOsI+xSTcgnCbM2liGIYF8nqeyceuNoQGIey0fRaiHBSxoBQ2EkZsQGCENyd5BTaiZvL5-lMfALGscFHabjynlomQzGDGxEXrNFsXpFJlKJbi758MINwVdlrx8VFMVcHFTRHq4ABUXVNF1MI8KY0BpR+rzGaZejmFa5gOTkJQqPo8CmA+H65Kh5gImo5A9CZZmsBgfWuHOJE7RNiLFD8ExcRSUJ8O+LBqAAavQsDdPAwgCWeagiece27KQ3SwLA072V9P3wM5rl+Lsa7cW8l01EwuwPc9r3wBV0TmLV04shhv4IFwAFAVoHCgX4AQUDQyohAA7FEMQgHISFKNFooYWk2EgKaGzsRSWm6D6YjyJIrHfPQFA+iwXC+QA3DcMowOUcJPNTjB4XLM4QhgMp7hSgEunCPCfFATwAMTwBbGunArJikMr5jhGrVt3PQXBwuUPpWowTyO+rHUQiqcOjJhPolPAEBwuoTw4FgWDO-zaiSxAABe8BPDTWBOzcYCu+7pBPHH-slqQObFuYral2QQc527HsIGINLmBgOAZhrkQgb44GU0oyoABxIMqdORKIICOqQzpBHwiHxEMwmbMtsDEIw-YYOhBDcloSjqGozBIK4MykIwzpwtFxBgK4s9qAAAsqABsGDKqE2AzGAUAX2D89bEvK9ryAaisYweInBpaMAyAhRmcQaCXx9JUWon9F7L3SKvZIIAN40G3rvfenwj4nx-O-ISidYE33vo-Z+3RX74L8DAs+GB4HfyQb-f+gCaDAIgKA+m08aCQDUCoaWsBJaoW0GgrelpMEHxwafc+3DeGSAEQsK+T8sDPwRowgBQDuBsIyKTTuFMgggEHigJAt9e4+gMUgXuUEogjyZvEWaa1yL4XkIwagkQgA)

```js
import stream from "mithril/stream"
import { useStream } from "use-stream"

const { count } = useStream({
model: {
count: stream(0),
}
})

return (
<div className="page">
<h1>{count()}</h1>
<p>
<button
onClick={() => count(count() - 1)}
disabled={count() === 0}
>Decrement</button>
<button
onClick={() => count(count() + 1)}
>Increment</button>
</p>
</div>
)
```

### Example with James Forbes' useInterval

[Live code example](https://flems.io/#0=N4IgtglgJlA2CmIBcAWAnAOgAwFYA0IAxgPYB2AzsQskVbAIYAO58UIB5hATncgNpY8WALoEAZhATl+oUvTCIkIDAAsALmFjtapNfF00APFAgA3AATQAvAB0QTRnYB8hgPQnTT7SwSE1EMmklLCQAJiwQAF88WXlFZQAraQISXX01GlTyNXNsrnh5cytzAHcIUihiEowwDDyCsBtSCDBGYi4c4HMAVxYAZTV8wsjzMR4wczsMV174AaHGkCam11dzAGFiKHhzEjAFXXJzehz1NWYkVYS48gBaMXaAI3hyDD3XAGIAQlc27PJXCpiMQANZ3egVW71eTkJpZHKzACSaS4pnosCK5gAFF1tgwAJ7mSIASiKTnMwCa5l2gRy0Ex0LAWOJVJpFBy-kIIIZgwazNZrLx9HxNSYWNZ1KFhKs5MppGpCt2CHoXGRelR6Kx0GZLPlissUCxLDUavgGtgWM5ILw5ilNqlxN1isirKdkz1Uow+igosY4r11OZZIpEoVhGVqpRaIt2sdoZderdrPyam6XHlVqaCbhtPMYC28AxxRxlmaagAIoXhTbyhA1JturoSWTWbN5ny5Yr83ikCGAwqpb3GVqy5WCcS8KHqSRG2oh7z5CO6w3dBP45P+2QALLEWe9ksz3T2quE5syvv6tnZcxWzFIqOa3EnoluxVW31YoPnw9qLE-oMANTmAAjHG-bRKGZCVnkxD4vuXQ-seBIvsGnb6p63qWlw3TwK+RKsiSyykPCPRlpiwFYFgObsqWdZjsKmI4JRREkQAgowjCYowPDMKhrIkQhu5Hraz4jMU3aFiWtYVievbSfR+I1mWK5zuYWAvgKeopmm8r+oqxhmEq9DkOQABycS2CAjD0AA5vAzhTuYhgqMBTjAP+xKRG4LlOI5hiME4Cm9sAUrMiMYDkG4AV+dF-b6Y83RqGoZCOYqZDrLAEBclYwBfuSoWhaStykXWnmpQOEDkPQjwIFAOWFUUVjFI2dYJpe1KBfA3DwAcahuAlSVkL5cUKoYA3JaQ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IuOac7gGKMgoOKegoIIBgKBJQEgOGAAOW4QqRViuRlUgghD4gT0XgscwFN5CMGoJEIAA)

```js
import stream from "mithril/stream"
import { useStream } from "use-stream"

// Code comments at https://james-forbes.com/#!/posts/hooks-and-streams
const useInterval = ({ delay }) => {
const id = stream()
const tick = stream()

delay.map(
delay => {
clearInterval(id())
id(setInterval(tick, delay, delay))
}
)

delay.end.map(
() => {
clearInterval(id())
}
)

return tick
}

const model = ({ initDelay, initCount}) =>
useStream({
model: {
delay: stream(initDelay),
count: stream(initCount),
},
onMount: ({ count, delay }) => {
const tick = useInterval({ delay })
tick.map(() => count(count() + 1))
},
onDestroy: ({ count, delay }) => {
// Clean up
delay.end(true)
}
})

const unit = 100
const initDelay = 500

const App = props => {
const { count, delay } = model({ initDelay: initDelay, initCount: 0 })

return (
<div className="page">
<h1>{count()}</h1>
<p>Delay: {delay()} ms</p>
<p>
<button
onClick={() => delay(delay() - unit)}
disabled={delay() === unit}
>Decrement</button>
<button
onClick={() => delay(delay() + unit)}
>Increment</button>
</p>
</div>
)
}
```

## Size

387 bytes gzipped
2 changes: 2 additions & 0 deletions dist/use-stream.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dist/use-stream.js.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions dist/use-stream.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useRef, useEffect, useState } from 'react';

const useStream = ({ model, onMount, onDestroy }) => {
const memo = useRef(model);
Object.keys(model).forEach(k => update(model[k]));
useEffect(() => {
if (onMount) {
onMount(memo.current);
}
if (onDestroy) {
return () => onDestroy(memo.current);
}
}, []);
return memo.current;
};
/**
* Provides an update to React whenever a stream gets updated.
*/
const update = (stream) => {
const [, setValue] = useState();
useEffect(() => {
stream.map(setValue);
}, []);
};

export { useStream };
12 changes: 12 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import "react";
import Stream from "mithril/stream";

type Model = {
[key:string]: Stream<any>;
}

export type UseStream = ({ model, onMount, onDestroy } : {
model: Model;
onMount?: (model: Model) => any;
onDestroy?: (model: Model) => any;
}) => Model;
42 changes: 42 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "use-stream",
"version": "0.1.0",
"description": "Enables React applications to work with streams.",
"main": "dist/use-stream",
"module": "dist/use-stream.mjs",
"scripts": {
"clean": "rm -rf dist/*",
"rollup": "MODULE_NAME=useStream TYPESCRIPT=1 ./node_modules/rollup/dist/bin/rollup -c ./scripts/rollup.umd.js && TYPESCRIPT=1 ./node_modules/rollup/dist/bin/rollup -c ./scripts/rollup.es.js ",
"build": "npm run clean && npm run rollup && npm run size",
"size": "gzip -c dist/use-stream.js | wc -c"
},
"files": [
"dist",
"index.d.ts",
"README.md"
],
"author": "Arthur Clemens <[email protected]> (http://visiblearea.com)",
"homepage": "https://github.com/ArthurClemens/use-stream",
"license": "MIT",
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.8.6",
"@babel/plugin-external-helpers": "^7.8.3",
"@babel/plugin-transform-arrow-functions": "^7.8.3",
"@babel/plugin-transform-object-assign": "^7.8.3",
"@babel/preset-env": "^7.8.6",
"@babel/preset-typescript": "^7.8.3",
"@babel/register": "^7.8.6",
"@types/mithril": "^2.0.2",
"@types/react": "^16.9.23",
"babel-core": "^7.0.0-bridge.0",
"react": "^16.13.0",
"rollup": "^1.31.1",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-node-resolve": "^5.2.0",
"rollup-plugin-terser": "^5.2.0",
"rollup-plugin-typescript2": "^0.26.0",
"typescript": "^3.8.2"
}
}
15 changes: 15 additions & 0 deletions scripts/babel.config.base.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports = api => {
const presets = []; // set in specific configs for es and umd
const plugins = [
"@babel/plugin-transform-arrow-functions",
"@babel/plugin-transform-object-assign",
"@babel/plugin-proposal-object-rest-spread"
];

api.cache(false);

return {
presets,
plugins,
};
};
17 changes: 17 additions & 0 deletions scripts/babel.config.es.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const plugins = require("./babel.config.base").plugins;

const presets = [
["@babel/preset-env",
{
"targets": {
"esmodules": true
}
}
],
"@babel/preset-react"
];

module.exports = {
presets,
plugins
};
23 changes: 23 additions & 0 deletions scripts/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module.exports = function (api) {

api.cache.forever();

const presets = [
"@babel/preset-typescript",
"@babel/preset-env",
"@babel/preset-react"
];
const plugins = [
"@babel/plugin-transform-arrow-functions",
"@babel/plugin-transform-object-assign",
"@babel/plugin-proposal-object-rest-spread",
["@babel/plugin-transform-react-jsx", {
"pragma": "jsx"
}]
];

return {
presets,
plugins,
};
};
11 changes: 11 additions & 0 deletions scripts/babel.config.umd.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const plugins = require("./babel.config.base").plugins;

const presets = [
"@babel/preset-env",
"@babel/preset-react"
];

module.exports = {
presets,
plugins
};
Loading

0 comments on commit a7501e8

Please sign in to comment.