├── .babelrc ├── .eslintrc ├── .github └── armin_logo.png ├── .gitignore ├── LICENSE ├── README.md ├── __tests__ └── index.js ├── example ├── .babelrc ├── counter.js ├── helper.js ├── index.html ├── simple.js └── todos.js ├── package-lock.json ├── package.json ├── rollup.config.js └── src ├── armin.js └── core ├── Machine.js ├── Store.js ├── init.js └── utils ├── Reducer.js ├── constants.js └── index.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "env", 5 | { 6 | "modules": false, 7 | "loose": true, 8 | "exclude": ["transform-async-to-generator", "transform-regenerator"], 9 | "targets": { 10 | "browsers": ["last 2 versions"] 11 | } 12 | } 13 | ], 14 | "flow", 15 | "react", 16 | "stage-0" 17 | ], 18 | "plugins": ["transform-class-properties"], 19 | "env": { 20 | "cjs": { 21 | "plugins": ["transform-es2015-modules-commonjs"] 22 | }, 23 | "test" :{ 24 | "presets" : ["env","stage-0","react"], 25 | }, 26 | "example" :{ 27 | "plugins" : [ 28 | ["transform-runtime", { 29 | "polyfill" : false, 30 | "regenerator" : true 31 | }] 32 | ] 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "node":true, 5 | "es6":true, 6 | "jest":true 7 | }, 8 | "globals": { 9 | "require": true, 10 | "module":true, 11 | "window":true 12 | }, 13 | "extends": ["eslint:recommended","plugin:react/recommended"], 14 | "parser": "babel-eslint", 15 | "rules": { 16 | "semi": [0], 17 | "no-constant-condition":[2], 18 | "no-undef" : [2], 19 | "no-dupe-args":[2], 20 | "no-unreachable":[1], 21 | "no-cond-assign":[2], 22 | "no-dupe-keys":[1], 23 | "prefer-const":[1], 24 | "no-const-assign":[2], 25 | "no-duplicate-imports":[2], 26 | "no-useless-constructor":[1], 27 | "no-class-assign":[2], 28 | "no-confusing-arrow":[2], 29 | "constructor-super":[2], 30 | "prefer-spread":[1], 31 | "no-lonely-if":[1], 32 | "no-continue":[1], 33 | "no-redeclare":[0], 34 | "comma-dangle":[0], 35 | "no-extra-semi":[0], 36 | "no-console":[0], 37 | "no-mixed-spaces-and-tabs":[0], 38 | "react/react-in-jsx-scope":[0], 39 | "react/display-name":[0] 40 | }, 41 | "plugins": [ 42 | "react" 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /.github/armin_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/imbhargav5/armin/26953fa52c92803f8147abaefdfcf0d918b2254e/.github/armin_logo.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (http://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # Typescript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | 61 | # Distribution 62 | 63 | lib 64 | .cache 65 | dist 66 | es 67 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Bhargav Ponnapalli 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 | 4 |

5 | 6 |

Declarative state machines for React!

7 | 8 |
9 |

10 | React Component state is a powerful way of managing state within a component, but can we do more? Can we create and maintain state which is more readable and self-explantory and powerful at the same time? 11 |

12 |
13 | 14 | 15 | ## Quick Example 16 | 17 | ```javascript 18 | import {createMachine} from "armin" 19 | 20 | const ViewToggler = createMachine({ 21 | allStates: ["visible", "hidden"], 22 | state : "visible", 23 | reducers : { 24 | hide : { 25 | from : ["visible"], 26 | setState : () => "hidden" 27 | }, 28 | show : { 29 | from : ["hidden"], 30 | setState : () => "visible" 31 | } 32 | } 33 | }) 34 | 35 | // In your component's render method 36 | 37 | 38 | ... 39 | 40 | {toggler => <> 41 | 42 | 43 | } 44 | 45 | ... 46 | 47 | 48 | ``` 49 | 50 | So what is going on there? 51 | 52 | The configuration for a state machine like above means that, 53 | 54 | - All your states have names 55 | - Reducers describe how state can be updated using `from` and `setState` keywords. 56 | - `allStates` defines all the valid states your state machine can take. 57 | - When you create a state machine you get a `Provider` and `Consumer` and the `Consumer` is able to expose a `controller` which is capable of performing actions and manipulate state of your machine. You can create as many consumers as you like and they all talk to each other through the `Provider`. 58 | 59 | Is that all `Armin` can do? Nope. Let's take a slightly larger example. 60 | 61 | 62 | ### Single State Machine -> An async counter example with armin 63 | 64 | 1. Create a machine 65 | 66 | ```javascript 67 | import {createMachine} from "armin" 68 | 69 | const { Provider, Consumer } = createMachine({ 70 | allStates: ["ready", "running", "stopped"], 71 | state: "ready", 72 | value: 0, 73 | reducers: { 74 | increment: { 75 | setValue: ({ value, state }, payload = 1) => value + payload, 76 | setState: () => "running" 77 | }, 78 | decrement: { 79 | from: ["running"], 80 | setValue: ({ value, state }, payload = 1) => value - payload, 81 | setState: (opts, setValue) => 82 | setValue <= 0 ? "stopped" : "running" 83 | // setState function has access to the newValue that was generated in setValue as the second argument. Opts 84 | // contains current value and current state. 85 | }, 86 | stop: { 87 | from: ["ready", "running"], 88 | setValue: ({ value }) => value, 89 | setState: () => "stopped" 90 | } 91 | }, 92 | effects: { 93 | async incrementAsync() { 94 | console.log("waiting"); 95 | await new Promise(resolve => 96 | setTimeout(() => { 97 | console.log("done waiting"); 98 | resolve(); 99 | }, 1000) 100 | ); 101 | this.increment(5); 102 | } 103 | } 104 | }); 105 | 106 | ``` 107 | 108 | So in the example above, we also use the `value` property to give the machine a value to keep track of. This can be any javascript value including strings, numbers, objects and functions. 109 | 110 | The `effects` key is where we define `async` actions for our state machine. All async actions have access to the reducers defined in the `reducers` key. They are bound to the controller hence, `this.increment` is perfectly valid inside an async action. This means that, while all reducers are synchronous, you can create async actions and call the reducers within them as and when needed. This was inspired from Rematch. 111 | 112 | 113 | 2. Using the machine inside React 114 | 115 | ```javascript 116 | 117 | 118 | {machineController => { 119 | return ( 120 |
121 |

122 | 128 |

129 |

Value is {machineController.value}

130 |

131 | 137 |

138 |

139 | 145 |

146 |

147 | 153 |

154 |
155 | ); 156 | }} 157 |
158 |
159 | 160 | ``` 161 | 162 | Here our machineController object has two special keys `can` and `is`. `can` tells us whether a particular `reducer` action is valid for the state the controller is in. This is automatic and is derived from the reducer configuration given during machine creation. `is` just tells us if the machine is in a particular state or not. For eg: `machineController.is.stopped` etc. 163 | 164 | These are handy when you want to control the views by disabling/enabling input, permissions etc. 165 | 166 | Now, let's take a more complex example. 167 | 168 | 169 | 170 | ### Multiple state machines 171 | 172 | Just like above, but we can create multiple machines at once and then subscribe to only the ones we need to ensure maximum performance during rerenders on update. 173 | 174 | ```javascript 175 | 176 | import {init} from "armin" 177 | 178 | // create a an object with state machine config as above 179 | const toggler = { 180 | allStates: ["showing", "hiding"], 181 | state: "hiding", 182 | reducers: { 183 | show: { 184 | from: ["hiding"], 185 | setState: () => "showing" 186 | }, 187 | hide: { 188 | from: ["showing"], 189 | setState: () => "hiding" 190 | } 191 | } 192 | } 193 | 194 | const counter = { 195 | ... 196 | } 197 | 198 | const user = { 199 | ... 200 | } 201 | 202 | const { store, Provider, createConsumer } = init({ 203 | toggler, 204 | counter, 205 | user 206 | }); 207 | 208 | const Consumer = createConsumer(["toggler","counter"]); 209 | 210 | class MyChildComponent extends Component{ 211 | render(){ 212 | return 213 | {([toggler,counter]) => } 214 | 215 | } 216 | } 217 | 218 | 219 | class MyRootComponent extends Component{ 220 | render(){ 221 | return 222 | 223 | 224 | } 225 | } 226 | 227 | 228 | ``` 229 | 230 | Almost everything above is the same as in previous examples. Except here, we are able to combine multiple machines together for a component using the `init` function and subscribe to all or a subset of those using the `createConsumer` utility. This means that we can subscribe to only those machines that we need and prevent unnecessary renders when an update occurs. 231 | 232 | 233 | ## Motivation 234 | 235 | Let's compare these two examples. 236 | 237 | ```javascript 238 | 243 | ``` 244 | 245 | vs 246 | 247 | ```javascript 248 | 253 | ``` 254 | 255 | The first one is extremely readable and you can immeditately tell what the developer is trying to do in this code. It hardly requires comments. That is the motivation for this project. 256 | State machines in Arminjs with meaningful names for states have great potential to make developer experience great for building applications with React. 257 | 258 | 259 | ## Features : 260 | 261 | - State machine creation is similar to the api of Rematch 262 | - Uses the new 16.3 React Context API for data flow across components 263 | - Async actions are supported 264 | - Multiple state machines are supported but you can subscribe to only the ones you need 265 | within a component 266 | 267 | 268 | ### License 269 | 270 | MIT 271 | 272 | -------------------------------------------------------------------------------- /__tests__/index.js: -------------------------------------------------------------------------------- 1 | import { init } from "../"; 2 | 3 | describe("init type check", () => { 4 | test("init is a defined function", () => { 5 | expect(init).toBeDefined(); 6 | expect(init).toBeInstanceOf(Function); 7 | }); 8 | }); 9 | -------------------------------------------------------------------------------- /example/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "env", 5 | { 6 | "modules": false, 7 | "loose": true, 8 | "targets": { 9 | "browsers": ["last 1 version"] 10 | } 11 | } 12 | ], 13 | "flow", 14 | "react", 15 | "stage-0" 16 | ], 17 | "plugins": ["transform-class-properties"] 18 | } 19 | -------------------------------------------------------------------------------- /example/counter.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { render } from "react-dom"; 3 | import { createMachine } from "../src/armin"; 4 | 5 | const { Provider, Consumer } = createMachine({ 6 | allStates: ["ready", "running", "stopped"], 7 | state: "ready", 8 | value: 0, 9 | reducers: { 10 | increment: { 11 | setValue: ({ value, state }, payload = 1) => value + payload, 12 | setState: () => "running" 13 | }, 14 | decrement: { 15 | from: ["running"], 16 | setValue: ({ value, state }, payload = 1) => value - payload, 17 | setState: (opts, setValue) => 18 | setValue <= 0 ? "stopped" : "running" 19 | }, 20 | stop: { 21 | from: ["ready", "running"], 22 | setValue: ({ value }) => value, 23 | setState: () => "stopped" 24 | } 25 | }, 26 | effects: { 27 | async incrementAsync() { 28 | console.log("waiting"); 29 | await new Promise(resolve => 30 | setTimeout(() => { 31 | console.log("done waiting"); 32 | resolve(); 33 | }, 1000) 34 | ); 35 | this.increment(5); 36 | } 37 | } 38 | }); 39 | 40 | export default class Counter extends Component { 41 | render() { 42 | return ( 43 | 44 | 45 | {machineController => { 46 | console.log(machineController); 47 | return ( 48 |
49 |

50 | 56 |

57 |

Value is {machineController.value}

58 |

59 | 65 |

66 |

67 | 73 |

74 |

75 | 81 |

82 |
83 | ); 84 | }} 85 |
86 |
87 | ); 88 | } 89 | } 90 | render(, window.counter); 91 | -------------------------------------------------------------------------------- /example/helper.js: -------------------------------------------------------------------------------- 1 | import "babel-polyfill" 2 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |

Store

9 |
10 |

Todos

11 |
12 |

Counter

13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /example/simple.js: -------------------------------------------------------------------------------- 1 | import React, {Component} from "react"; 2 | import { render } from "react-dom"; 3 | import { init } from "../src/armin"; 4 | 5 | const toggler = { 6 | allStates: ["showing", "hiding"], 7 | state: "hiding", 8 | reducers: { 9 | show: { 10 | from: ["hiding"], 11 | setState: () => "showing" 12 | }, 13 | hide: { 14 | from: ["showing"], 15 | setState: () => "hiding" 16 | } 17 | } 18 | }; 19 | 20 | const counter = { 21 | allStates: ["ready", "running", "stopped"], 22 | state: "ready", 23 | value: 0, 24 | reducers: { 25 | increment: { 26 | from: ["ready", "running"], 27 | setState: () => "running", 28 | setValue: ({ value }) => value + 1 29 | }, 30 | stop: { 31 | from: ["ready", "running"], 32 | setState: () => "stopped" 33 | }, 34 | restart: { 35 | from: ["stopped"], 36 | setState: () => "ready", 37 | setValue: ({ value }) => 0 38 | } 39 | }, 40 | effects: { 41 | incrementAsync() { 42 | return setInterval(() => { 43 | this.increment(); 44 | }, 100); 45 | } 46 | } 47 | }; 48 | 49 | const { store, Provider, createConsumer } = init({ 50 | toggler, 51 | counter 52 | }); 53 | 54 | class Counter extends React.Component { 55 | timers = []; 56 | startIncrementAsync = () => { 57 | this.timers.push(this.props.counter.incrementAsync()); 58 | }; 59 | 60 | stop = () => { 61 | this.timers.forEach(timer => clearInterval(timer)); 62 | this.timers = []; 63 | this.props.counter.stop(); 64 | }; 65 | 66 | render() { 67 | const { counter } = this.props; 68 | return ( 69 |
70 |

71 | {" "} 72 | {" "} 75 | {" "} 81 |

82 |

{counter.value}

83 |

84 | {" "} 85 | {" "} 88 | {" "} 91 |

92 |
93 | ); 94 | } 95 | } 96 | 97 | const Consumer = createConsumer(["toggler", "counter"]); 98 | 99 | export default class Home extends React.Component { 100 | render() { 101 | return ( 102 | 103 | 104 | {([toggler, counter]) => { 105 | return ( 106 |
107 |

State {toggler.state}

108 |

Value {toggler.value}

109 |

110 | 113 | 116 |

117 |
118 | 119 |
120 | ); 121 | }} 122 |
123 |
124 | ); 125 | } 126 | } 127 | 128 | render(, window.store); 129 | -------------------------------------------------------------------------------- /example/todos.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { render } from "react-dom"; 3 | import { createMachine } from "../src/armin"; 4 | 5 | const { Provider, Consumer } = createMachine({ 6 | allStates: ["ready", "editing"], 7 | state: "ready", 8 | value: { 9 | list: [ 10 | { 11 | text: "Finish visa process", 12 | isCompleted: false 13 | } 14 | ], 15 | editingTodoId: null 16 | }, 17 | reducers: { 18 | editTodo: { 19 | from: ["ready"], 20 | setState: () => "editing" 21 | }, 22 | finishEditing: { 23 | from: ["editing"], 24 | setState: () => "ready" 25 | }, 26 | toggleIsCompleted: { 27 | setValue: ({ value }, index, isCompleted) => ({ 28 | ...value, 29 | list: [ 30 | ...value.list.slice(0, index), 31 | { 32 | ...value.list[index], 33 | isCompleted 34 | }, 35 | ...value.list.slice(index + 1) 36 | ] 37 | }) 38 | }, 39 | addTodo: { 40 | setValue: ({ value }, { text, isCompleted }) => { 41 | return { 42 | ...value, 43 | list: [...value.list, { text, isCompleted }] 44 | }; 45 | } 46 | } 47 | } 48 | }); 49 | 50 | class TodoForm extends Component { 51 | state = { 52 | text: "", 53 | isCompleted: false 54 | }; 55 | handleSubmit = e => { 56 | e.preventDefault(); 57 | if (this.state.text) { 58 | this.props.onSubmit({ 59 | text: this.state.text, 60 | isCompleted: this.state.isCompleted 61 | }); 62 | this.setState({ 63 | text: "", 64 | isCompleted: false 65 | }); 66 | } 67 | }; 68 | changeText = e => this.setState({ text: e.target.value }); 69 | changeIsCompleted = e => this.setState({ isCompleted: e.target.checked }); 70 | render() { 71 | const { canSubmit } = this.props; 72 | return ( 73 |
74 | 80 | 85 | 88 |
89 | ); 90 | } 91 | } 92 | 93 | class DisplayTodo extends Component { 94 | changeIsCompleted = e => { 95 | this.props.onToggleIsCompleted(this.props.index, e.target.checked); 96 | }; 97 | render() { 98 | const { canToggleIsCompleted, todo } = this.props; 99 | return ( 100 |

101 | 107 | {todo.text} 108 |

109 | ); 110 | } 111 | } 112 | 113 | export default class Todos extends Component { 114 | attemptAddTodo = fn => e => { 115 | e.preventDefault(); 116 | }; 117 | render() { 118 | return ( 119 | 120 | 121 | {todosController => { 122 | console.log(todosController); 123 | return ( 124 |
125 | {todosController.value.list.map((todo, index) => ( 126 | 133 | ))} 134 | 138 |
139 | ); 140 | }} 141 |
142 |
143 | ); 144 | } 145 | } 146 | render(, window.todos); 147 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "armin", 3 | "version": "0.0.2", 4 | "description": "Declarative state machines for React!", 5 | "main": "lib/armin.js", 6 | "module": "lib/armin.es.js", 7 | "watch": { 8 | "build": "{src,demo}/**/*.js" 9 | }, 10 | "files": [ 11 | "dist", 12 | "lib", 13 | "es", 14 | "src" 15 | ], 16 | "scripts": { 17 | "build": "rollup -c", 18 | "clean": "rimraf lib dist es", 19 | "lint": "eslint {__tests__,src}/*.js", 20 | "example": "BABEL_ENV=example parcel example/index.html", 21 | "watch": "npm-watch", 22 | "test:watch": "cross-env BABEL_ENV=test NODE_ENV=test jest --watchAll", 23 | "test": "cross-env BABEL_ENV=test jest", 24 | "pretty": "prettier --write '{__tests__,src}/*.js'", 25 | "prebuild": "npm run clean", 26 | "prepublish": "npm run pretty && npm run lint && npm run test && npm run build", 27 | "postpublish": "git push origin master --tags" 28 | }, 29 | "repository": { 30 | "type": "git", 31 | "url": "git+https://github.com/imbhargav5/armin.git" 32 | }, 33 | "keywords": [ 34 | "armin", 35 | "state-management", 36 | "finite-state-machine" 37 | ], 38 | "author": "Bhargav Ponnapalli (https://github.com/imbhargav5)", 39 | "license": "MIT", 40 | "bugs": { 41 | "url": "https://github.com/imbhargav5/armin/issues" 42 | }, 43 | "homepage": "https://github.com/imbhargav5/armin#readme", 44 | "devDependencies": { 45 | "babel-core": "^6.26.0", 46 | "babel-eslint": "8.2.3", 47 | "babel-jest": "22.4.3", 48 | "babel-plugin-external-helpers": "6.22.0", 49 | "babel-plugin-transform-async-to-generator": "6.24.1", 50 | "babel-plugin-transform-class-properties": "^6.24.1", 51 | "babel-plugin-transform-runtime": "6.23.0", 52 | "babel-polyfill": "6.26.0", 53 | "babel-preset-env": "^1.6.1", 54 | "babel-preset-flow": "^6.23.0", 55 | "babel-preset-react": "^6.24.1", 56 | "babel-preset-stage-0": "6.24.1", 57 | "babel-register": "^6.26.0", 58 | "cross-env": "5.1.3", 59 | "eslint": "4.16.0", 60 | "eslint-plugin-react": "7.6.1", 61 | "immer": "1.2.1", 62 | "isomorphic-fetch": "2.2.1", 63 | "jest": "22.4.3", 64 | "npm-watch": "0.3.0", 65 | "parcel-bundler": "1.5.1", 66 | "prettier": "1.10.2", 67 | "prop-types": "15.6.0", 68 | "react-dom": "16.3.0", 69 | "rimraf": "2.6.2", 70 | "rollup": "0.55.3", 71 | "rollup-plugin-babel": "^3.0.3", 72 | "styled-components": "3.1.4" 73 | }, 74 | "dependencies": { 75 | "core-js": "2.5.5", 76 | "create-react-context": "0.2.2", 77 | "lodash": "4.17.5" 78 | }, 79 | "peerDependencies": { 80 | "prop-types": "^15.5.0", 81 | "react": "^15.0.0 || ^16.0.0" 82 | }, 83 | "npmName": "armin", 84 | "npmFileMap": [ 85 | { 86 | "basePath": "/dist/", 87 | "files": [ 88 | "*.js" 89 | ] 90 | } 91 | ], 92 | "jest": { 93 | "testRegex": "(/__tests__/.*\\.js)$" 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from "rollup-plugin-babel"; 2 | import pkg from "./package.json"; 3 | 4 | export default { 5 | input: "src/armin.js", 6 | output: [ 7 | { 8 | file: pkg.main, 9 | format: "cjs" 10 | }, 11 | { 12 | file: pkg.module, 13 | format: "es" 14 | } 15 | ], 16 | external: [ 17 | ...Object.keys(pkg.dependencies || {}), 18 | ...Object.keys(pkg.peerDependencies || {}) 19 | ], 20 | plugins: [babel()] 21 | }; 22 | -------------------------------------------------------------------------------- /src/armin.js: -------------------------------------------------------------------------------- 1 | import Store from "./core/Store"; 2 | import { createMachine } from "./core/Machine"; 3 | import init from "./core/init" 4 | 5 | export { Store }; 6 | export { createMachine }; 7 | export { init }; 8 | export default init; 9 | -------------------------------------------------------------------------------- /src/core/Machine.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import PropTypes from "prop-types"; 3 | 4 | import createReactContext from "create-react-context"; 5 | import { createMachineConfigWithDefaults } from "./utils/index"; 6 | 7 | export const ALL_STATES = Symbol("ALL_STATES"); 8 | export const INTERNAL_STATE = Symbol("INTERNAL_STATE"); 9 | export const INTERNAL_VALUE = Symbol("INTERNAL_VALUE"); 10 | export const REDUCERS = Symbol("REDUCERS"); 11 | export const EFFECTS = Symbol("EFFECTS"); 12 | export const LISTENERS = Symbol("LISTENERS"); 13 | export const MACHINE_NAME = Symbol("NAME"); 14 | 15 | // This function will add reducers 16 | // as methods on to the controller 17 | export function createControllerMembersFromReducers() { 18 | const reducers = this[REDUCERS]; 19 | const members = {}; 20 | for (const key in reducers) { 21 | // Create a function that has access to 22 | // value and state as the first argument 23 | // pass the original args in order 24 | members[key] = (...args) => { 25 | // invoke the original function inside 26 | // reducers 27 | const currentState = this.getState(); 28 | const currentValue = this.getValue(); 29 | try { 30 | const reducer = reducers[key]; 31 | // can the reducer dispatch? 32 | if (reducer.canDispatch(currentState)) { 33 | const { nextValue, nextState } = reducer.dispatch( 34 | { 35 | value: currentValue, 36 | state: currentState 37 | }, 38 | ...args 39 | ); 40 | // Update internal value 41 | this.setValue(nextValue); 42 | this.setState(nextState); 43 | // Broadcast changes to listeners 44 | this.broadcast(); 45 | return nextValue; 46 | } else { 47 | // No valid action 48 | console.warn( 49 | `${reducer.getName()} has no valid action for state ${currentState}. Aborting.` 50 | ); 51 | return currentValue; 52 | } 53 | } catch (err) { 54 | console.error(err); 55 | } 56 | }; 57 | } 58 | return members; 59 | } 60 | 61 | export function createControllerMembersFromEffects() { 62 | const effects = this[EFFECTS]; 63 | const members = {}; 64 | for (const key in effects) { 65 | // Create a function that has access to 66 | // value and state as the first argument 67 | // pass the original args in order 68 | const machine = this; 69 | members[key] = function(...args) { 70 | console.log("effects", this); 71 | // we want the controller to be able to call it's members 72 | // from it's effects 73 | // hence we call it with the this reference 74 | // we do not update values here; 75 | return effects[key].call( 76 | this, 77 | { 78 | value: machine.getValue(), 79 | state: machine.getState() 80 | }, 81 | ...args 82 | ); 83 | }; 84 | } 85 | return members; 86 | } 87 | 88 | // this function will tell whether a particular reducer 89 | // can dispatch in the current state or not 90 | export function getReducerDispatchablities() { 91 | const reducers = this[REDUCERS]; 92 | const currentState = this.getState(); 93 | const members = {}; 94 | for (const reducerName in reducers) { 95 | members[reducerName] = reducers[reducerName].canDispatch(currentState); 96 | } 97 | return members; 98 | } 99 | 100 | // this function will tell whether the machine is 101 | // in a particular state or not 102 | // basically controller.is.ready 103 | // or controller.is.stopped etc 104 | export function getControllerIsAttribute() { 105 | const currentState = this.getState(); 106 | const members = {}; 107 | this[ALL_STATES].reduce((acc, nextValue) => { 108 | acc[nextValue] = nextValue === currentState; 109 | return acc; 110 | }, members); 111 | return members; 112 | } 113 | 114 | export default class Machine { 115 | constructor(machineConfig) { 116 | const { 117 | name, 118 | allStates, 119 | initialState, 120 | initialValue, 121 | reducers, 122 | effects 123 | } = createMachineConfigWithDefaults(machineConfig); 124 | this[ALL_STATES] = allStates; 125 | this[INTERNAL_STATE] = initialState; 126 | this[INTERNAL_VALUE] = initialValue; 127 | this[REDUCERS] = reducers; 128 | this[EFFECTS] = effects; 129 | this[MACHINE_NAME] = name; 130 | this[LISTENERS] = []; 131 | } 132 | setState(nextState) { 133 | this[INTERNAL_STATE] = nextState; 134 | return nextState; 135 | } 136 | setValue(nextValue) { 137 | this[INTERNAL_VALUE] = nextValue; 138 | return nextValue; 139 | } 140 | getState() { 141 | return this[INTERNAL_STATE]; 142 | } 143 | getValue() { 144 | return this[INTERNAL_VALUE]; 145 | } 146 | getName() { 147 | return this[MACHINE_NAME]; 148 | } 149 | getController() { 150 | return { 151 | value: this.getValue(), 152 | state: this.getState(), 153 | ...createControllerMembersFromReducers.call(this), 154 | ...createControllerMembersFromEffects.call(this), 155 | can: getReducerDispatchablities.call(this), 156 | is: getControllerIsAttribute.call(this) 157 | }; 158 | } 159 | broadcast() { 160 | this[LISTENERS].forEach(listener => listener()); 161 | } 162 | subscribe(fn) { 163 | this[LISTENERS] = [...this[LISTENERS], fn]; 164 | return () => { 165 | this.unsubscribe(fn); 166 | }; 167 | } 168 | unsubscribe(fn) { 169 | this[LISTENERS] = this[LISTENERS].filter(func => func !== fn); 170 | } 171 | } 172 | 173 | 174 | /** 175 | * createMachine - creates Machine and returns a Provider and Consumer 176 | * 177 | * @param {type} machineConfig description 178 | * @return {type} description 179 | */ 180 | export function createMachine(machineConfig) { 181 | const MachineContext = createReactContext(null); 182 | const machine = new Machine(machineConfig); 183 | class Provider extends React.Component { 184 | static propTypes = { 185 | children : PropTypes.any 186 | } 187 | constructor(props) { 188 | super(props); 189 | this.unsubscribe = machine.subscribe(() => { 190 | this.setState({ 191 | value: machine.getController() 192 | }); 193 | }); 194 | this.state = { 195 | value: machine.getController() 196 | }; 197 | } 198 | componentWillUnmount() { 199 | this.unsubscribe(); 200 | } 201 | render() { 202 | return ( 203 | 204 | {this.props.children} 205 | 206 | ); 207 | } 208 | } 209 | 210 | class Consumer extends React.Component { 211 | static propTypes = { 212 | children : PropTypes.any 213 | } 214 | render() { 215 | return ( 216 | 217 | {machineController => this.props.children(machineController)} 218 | 219 | ); 220 | } 221 | } 222 | return { 223 | Provider, 224 | Consumer 225 | }; 226 | } 227 | -------------------------------------------------------------------------------- /src/core/Store.js: -------------------------------------------------------------------------------- 1 | import _ from "lodash"; 2 | import Machine from "./Machine"; 3 | 4 | export const MACHINES = Symbol("MACHINES"); 5 | 6 | function createMachinesFromConfiguration(machineConfiguration) { 7 | const entries = _.entries(machineConfiguration); 8 | const machines = _.reduce( 9 | entries, 10 | (acc, currentValue) => { 11 | const [machineName, machineConfiguration] = currentValue; 12 | return { 13 | ...acc, 14 | [machineName]: new Machine({ 15 | ...machineConfiguration, 16 | name: machineName 17 | }) 18 | }; 19 | }, 20 | {} 21 | ); 22 | return machines; 23 | } 24 | 25 | export default class Store { 26 | constructor(machineConfiguration) { 27 | this[MACHINES] = createMachinesFromConfiguration(machineConfiguration); 28 | } 29 | getMachines() { 30 | return this[MACHINES]; 31 | } 32 | getData() { 33 | const result = {}; 34 | for (const machineName in this[MACHINES]) { 35 | const machine = this[MACHINES][machineName]; 36 | result[machine.getName()] = { 37 | value: machine.getValue(), 38 | state: machine.getState() 39 | }; 40 | } 41 | return result; 42 | } 43 | getMachinesFromMachineNames(machineNamesList) { 44 | return machineNamesList.map(name => this[MACHINES][name]); 45 | } 46 | subscribeTo(machineNamesList) { 47 | console.log(this[MACHINES], machineNamesList); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/core/init.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import PropTypes from "prop-types"; 3 | import createReactContext from "create-react-context"; 4 | import Store from "./Store"; 5 | 6 | export default function init(storeConfig) { 7 | const StoreContext = createReactContext(null); 8 | const store = new Store(storeConfig); 9 | 10 | class Provider extends React.Component { 11 | static propTypes = { 12 | children : PropTypes.any 13 | } 14 | state = { 15 | value: store 16 | }; 17 | render() { 18 | return ( 19 | 20 | {this.props.children} 21 | 22 | ); 23 | } 24 | } 25 | 26 | function createConsumer(to) { 27 | const DUMMY_STATE = {}; 28 | return class Consumer extends React.Component { 29 | static propTypes = { 30 | children : PropTypes.any 31 | } 32 | subscriptions = []; 33 | onUpdate = cb => { 34 | this.setState(DUMMY_STATE, cb); 35 | }; 36 | unsubscribe = () => { 37 | this.subscriptions.forEach(subscription => subscription()); 38 | }; 39 | subscribe = machines => { 40 | this.unsubscribe(); 41 | this.subscriptions = machines.map(machine => 42 | machine.subscribe(this.onUpdate) 43 | ); 44 | }; 45 | componentWillUnmount() { 46 | this.unsubscribe(); 47 | } 48 | render() { 49 | return ( 50 | 51 | {store => { 52 | const machines = store.getMachinesFromMachineNames(to); 53 | this.subscribe(machines); 54 | const machineControllers = machines.map(machine => 55 | machine.getController() 56 | ); 57 | return this.props.children(machineControllers); 58 | }} 59 | 60 | ); 61 | } 62 | }; 63 | } 64 | 65 | return { 66 | store, 67 | createConsumer, 68 | Provider 69 | }; 70 | } 71 | -------------------------------------------------------------------------------- /src/core/utils/Reducer.js: -------------------------------------------------------------------------------- 1 | import _ from "lodash"; 2 | 3 | export const NAME = Symbol("NAME"); 4 | export const FOR_STATES = Symbol("FOR_STATES"); 5 | export const COMPUTE_NEXT_VALUE = Symbol("COMPUTE_NEXT_VALUE"); 6 | export const COMPUTE_NEXT_STATE = Symbol("COMPUTE_NEXT_STATE"); 7 | 8 | export const NOOP_COMPUTE_NEXT_STATE = ({ state }) => state; 9 | export const NOOP_COMPUTE_NEXT_VALUE = ({ value }) => value; 10 | 11 | export default class Reducer { 12 | static getMembersFromConfiguration(configuration, allStates) { 13 | let forStates = allStates, 14 | computeNextValue = NOOP_COMPUTE_NEXT_VALUE, 15 | computeNextState = NOOP_COMPUTE_NEXT_STATE; 16 | if (_.isFunction(configuration)) { 17 | // generate forStates and computeNextState 18 | // configuration is computeNextValue 19 | computeNextValue = configuration; 20 | } else if (_.isObject(configuration)) { 21 | const { 22 | from: _forStates = allStates, 23 | setValue: _computeNextValue = NOOP_COMPUTE_NEXT_VALUE, 24 | setState: _computeNextState = NOOP_COMPUTE_NEXT_STATE 25 | } = configuration; 26 | if ( 27 | !_.isFunction(computeNextValue) || 28 | !_.isFunction(computeNextState) || 29 | !Array.isArray(forStates) 30 | ) { 31 | throw new Error("Invalid config"); 32 | } 33 | forStates = _forStates; 34 | computeNextValue = _computeNextValue; 35 | computeNextState = _computeNextState; 36 | } else { 37 | throw new Error("Expected an object or a function"); 38 | } 39 | return { 40 | forStates, 41 | computeNextValue, 42 | computeNextState 43 | }; 44 | } 45 | constructor(name, configuration, allStates) { 46 | const { 47 | forStates, 48 | computeNextValue, 49 | computeNextState 50 | } = Reducer.getMembersFromConfiguration(configuration, allStates); 51 | this[NAME] = name; 52 | this[FOR_STATES] = forStates; 53 | this[COMPUTE_NEXT_STATE] = computeNextState; 54 | this[COMPUTE_NEXT_VALUE] = computeNextValue; 55 | } 56 | getName() { 57 | return this[NAME]; 58 | } 59 | canDispatch(state) { 60 | return this[FOR_STATES].includes(state); 61 | } 62 | dispatch(opts, ...restArgs) { 63 | const nextValue = this[COMPUTE_NEXT_VALUE](opts, ...restArgs); 64 | const nextState = this[COMPUTE_NEXT_STATE](opts, nextValue, ...restArgs); 65 | return { 66 | nextValue, 67 | nextState 68 | }; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/core/utils/constants.js: -------------------------------------------------------------------------------- 1 | export const ALL_STATES_KEY = "*"; 2 | export const SAME_STATE_KEY = "_"; 3 | -------------------------------------------------------------------------------- /src/core/utils/index.js: -------------------------------------------------------------------------------- 1 | import Reducer from "./Reducer"; 2 | 3 | export function createReducersFromConfig(reducersConfig = {}, allStates) { 4 | const members = {}; 5 | for (const reducerName in reducersConfig) { 6 | members[reducerName] = new Reducer( 7 | reducerName, 8 | reducersConfig[reducerName], 9 | allStates 10 | ); 11 | } 12 | return members; 13 | } 14 | 15 | export function createMachineConfigWithDefaults(machineConfig) { 16 | const { 17 | name = "localMachine", 18 | allStates = [], 19 | state: initialState = "start", 20 | value: initialValue = null, 21 | reducers: reducersConfig = {}, 22 | stateTransitions = {}, 23 | effects = {} 24 | } = machineConfig; 25 | return { 26 | name, 27 | allStates, 28 | initialState, 29 | initialValue, 30 | reducers: createReducersFromConfig(reducersConfig, allStates), 31 | stateTransitions, 32 | effects 33 | }; 34 | } 35 | --------------------------------------------------------------------------------