-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathfsm.js
64 lines (56 loc) · 2.16 KB
/
fsm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* @typedef {Object} StateDefinitions
* @property {{[event: string]: { target: string; actions?: Array<string> }}} [on]
*/
/**
* @typedef {Object} Options
* @property {{[state: string]: StateDefinitions}} states
* @property {object} context;
* @property {string} initial
*/
/**
* @typedef {Object} Implementation
* @property {{[actionName: string]: (ctx: object, event: any) => object}} actions
*/
/**
* A simplified `createMachine` from `@xstate/fsm` with the following differences:
*
* - the returned machine is technically a "service". No `interpret(machine).start()` is needed.
* - the state definition only support `on` and target must be declared with { target: 'nextState', actions: [] } explicitly.
* - event passed to `send` must be an object with `type` property.
* - actions implementation will be [assign action](https://xstate.js.org/docs/guides/context.html#assign-action) if you return any value.
* Do not return anything if you just want to invoke side effect.
*
* The goal of this custom function is to avoid installing the entire `'xstate/fsm'` package, while enabling modeling using
* state machine. You can copy the first parameter into the editor at https://stately.ai/viz to visualize the state machine.
*
* @param {Options} options
* @param {Implementation} implementation
*/
function createMachine({ states, context, initial }, { actions }) {
let currentState = initial;
let currentContext = context;
return {
send: (event) => {
const currentStateOn = states[currentState].on;
const transitionConfig = currentStateOn && currentStateOn[event.type];
if (transitionConfig) {
currentState = transitionConfig.target;
if (transitionConfig.actions) {
transitionConfig.actions.forEach((actName) => {
const actionImpl = actions[actName];
const nextContextValue =
actionImpl && actionImpl(currentContext, event);
if (nextContextValue) {
currentContext = {
...currentContext,
...nextContextValue,
};
}
});
}
}
},
};
}
export default createMachine;