139 | );
140 | }}
141 |
142 |
143 | );
144 | }
145 | }
146 | render(, window.todos);
147 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------