-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
44 lines (34 loc) · 1.1 KB
/
index.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
/// <reference path='types.d.ts' />
/** @type {Create} */
export function createMachine(graph, state, opts) {
const ENTER = opts?.enter || 'ENTER';
const LEAVE = opts?.leave || 'LEAVE';
/** @type {Machine} */
const machine = {
get graph() {
return graph;
},
get state() {
return state;
},
handleEvent(event) {
if (event.type === ENTER || event.type === LEAVE) return;
const node = /** @type {Edge | null} */ (graph[state]);
const edge = node && node[event.type];
if (edge == null) return;
const res = edge.call(machine, edge.to, event);
const nextState = 0 <= edge.to.indexOf(res) ? res : state;
if (nextState === state) return;
const nodeOut = /** @type {EdgeOut | null} */ (graph[state]);
nodeOut &&
nodeOut[LEAVE] &&
nodeOut[LEAVE](machine, [nextState], { type: LEAVE });
const nodeIn = /** @type {EdgeIn | null} */ (graph[nextState]);
nodeIn &&
nodeIn[ENTER] &&
nodeIn[ENTER](machine, [nextState], { type: ENTER });
state = nextState;
},
};
return machine;
}