/
form-machine.ts
180 lines (166 loc) · 5.8 KB
/
form-machine.ts
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import {createMachine, send} from 'xstate';
export enum States {
dataEntry = 'dataEntry',
awaitingResponse = 'awaitingResponse',
dataEntryError = 'dataEntryError',
serviceError = 'serviceError',
success = 'success',
}
export enum Events {
ENTER_DATA = 'ENTER_DATA',
BLUR_DATA = 'BLUR_DATA',
SUBMIT = 'SUBMIT',
}
export enum Actions {
setField = 'setField',
}
export interface FormFieldConfigValidationResult {
result: boolean,
errorMessage?: string
}
export interface FormFieldConfig {
required: boolean,
field: string,
validator?: (value: any) => FormFieldConfigValidationResult
}
export interface FormErrors {
[field: string]: {
message: string
}
}
export type FormMachineContext = {
data: any,
dataEntryErrors: FormErrors,
serviceErrors: any,
fields: FormFieldConfig[],
canSubmit: boolean,
}
export interface FormMachineFactoryParams {
fields: FormFieldConfig[],
onSubmit: (context: FormMachineContext) => Promise<any>,
onDone: (data: any) => any
}
function canSubmit(context: FormMachineContext) {
if (Object.keys(context.fields).length === 0) {
return true
}
return context.fields.reduce((acc, val) => {
const fieldValue = context.data[val.field];
const reqPredicate = val.required ? !!fieldValue : true;
return acc &&
(typeof val.validator === 'function' ?
val.validator(context.data[val.field]).result : true) && reqPredicate
}, true)
}
export const formMachineFactory = ({
fields,
onSubmit, onDone,
}: FormMachineFactoryParams) => {
return createMachine({
id: 'login',
initial: States.dataEntry,
context: {
data: {},
dataEntryErrors: {} as FormErrors,
serviceErrors: {} as FormErrors,
fields,
canSubmit: false,
} as FormMachineContext,
states: {
[States.dataEntry]: {
on: {
[Events.ENTER_DATA]: {
actions: Actions.setField,
},
[Events.BLUR_DATA]: [
{cond: 'isInvalid', target: States.dataEntryError},
],
[Events.SUBMIT]: {
cond: 'canSubmitGuard',
target: States.awaitingResponse
},
},
},
[States.awaitingResponse]: {
id: 'submit',
invoke: {
src: (context) => {
return onSubmit(context);
},
onDone: {
target: States.success
},
onError: [
{
actions: (context, event) => {
context.serviceErrors[event.type] = event.data;
},
target: States.serviceError
}
]
}
},
[States.dataEntryError]: {
on: {
[Events.ENTER_DATA]: {
// При вводе данных при ошибке нам нужно как установить данные, так и переключить state
actions: Actions.setField,
target: States.dataEntry
},
}
},
[States.serviceError]: {
on: {
[Events.SUBMIT]: {
target: States.awaitingResponse
},
[Events.ENTER_DATA]: {
// При вводе данных при ошибке нам нужно как установить данные, так и переключить state
actions: Actions.setField,
target: States.dataEntry
},
}
},
[States.success]: {
//кидаем done event
type: 'final',
onDone: {
actions: onDone
},
},
},
},
{
actions: {
[Actions.setField]: (context, event) => {
context.data[event.data.field] = event.data.value;
delete context.dataEntryErrors[event.data.field];
context.canSubmit = canSubmit(context);
},
},
guards: {
isInvalid: (context, event) => {
if (!event.data.value) {
return false
}
const field = context.fields.find(f => f.field === event.data.field);
if (!field) {
return false
}
const result: FormFieldConfigValidationResult = field.validator ? field.validator(event.data.value) : {
result: true
};
if (!result.result) {
context.dataEntryErrors[event.data.field] = {
message: result.errorMessage,
};
}
return !result.result
},
canSubmitGuard: (context) => {
return context.canSubmit;
}
}
}
);
}