This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
78 lines (71 loc) · 2.01 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import Vue from 'vue';
import { interpret, State } from 'xstate';
const generateVueMachine = (machine, logState = false, logContext = false, persistState = false) => {
let storedStateName = null;
let storedState = null;
const storeState = window && window.localStorage && persistState;
if (storeState) {
storedStateName = `${machine.id} machine state - ${window.location.hostname}`;
storedState = JSON.parse(localStorage.getItem(storedStateName));
}
const startingState = State.create(storedState || machine.initialState);
const resolvedState = machine.resolveState(startingState);
return new Vue({
created() {
this.service
.onTransition(state => {
if (state.changed) {
this.current = state;
this.context = state.context;
if (storeState) {
try {
localStorage.setItem(storedStateName, JSON.stringify(this.current));
} catch (err) {
console.error('Local storage is unavailable.');
}
}
if (process.env.NODE_ENV === 'development') {
if (logState) {
console.log(
`%c [ ${machine.id.toUpperCase()} STATE ]`,
'color: #1989ac',
this.current.value
);
}
if (logContext) {
console.log(
`%c [ ${machine.id.toUpperCase()} CONTEXT ]`,
'color: #2b8528',
this.context
);
}
}
}
})
.start(resolvedState);
console.log(`${machine.id}Machine started`);
},
data() {
return {
current: resolvedState,
context: resolvedState.context,
service: interpret(machine)
};
},
methods: {
send(event) {
this.service.send(event);
}
}
});
};
export const VueStateMachine = {
install(Vue, machines) {
machines.forEach(machine => {
const { config, machineSuffix = "Machine", logState, logContext, persistState } = machine;
const machineName = `$${config.id}${machineSuffix}`;
console.log(`${machineName}`)
Vue.prototype[machineName] = generateVueMachine(config, logState, logContext, persistState);
});
}
};