├── .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 |