-
Notifications
You must be signed in to change notification settings - Fork 0
/
reducer.ts
94 lines (78 loc) · 2.01 KB
/
reducer.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
import { validate } from '../schema/validate';
import {
defaultSchema, stateFromSchema,
} from './state';
import { FormGeneratorAction, IFormGeneratorState, IFormGeneratorAction } from './types';
const safeParseJson = (text: string) => {
try {
const schema = JSON.parse(text);
return { schema, error: null };
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
return { schema: null, error: message };
}
};
const safeValidateText = (text: string) => {
const { schema, error } = safeParseJson(text);
if (error) {
return { schema, error };
}
const result = validate(schema);
const validateError = result.errors ? result.errors.join('. ') : '';
return { schema, error: validateError };
};
export function reducer(
state: IFormGeneratorState,
action: IFormGeneratorAction,
): IFormGeneratorState {
if (action.type === FormGeneratorAction.update) {
const text = action.payload.text.trim();
if (text.trim().length === 0) {
return {
...state,
text,
error: '',
};
}
const { schema, error } = safeValidateText(text);
if (error) {
return {
...state,
text,
error,
};
}
return {
schema,
text,
lastValidText: text,
error: '',
};
}
if (action.type === FormGeneratorAction.clear) {
return {
schema: { items: [], actions: [] },
lastValidText: state.lastValidText,
text: '',
error: '',
};
}
if (action.type === FormGeneratorAction.reset) {
return stateFromSchema(defaultSchema);
}
if (action.type === FormGeneratorAction.rollback) {
const { schema, error } = safeValidateText(state.lastValidText);
if (!error) {
return {
schema,
text: state.lastValidText,
lastValidText: state.lastValidText,
error: '',
};
}
}
if (action.type === FormGeneratorAction.prettify && !state.error) {
return stateFromSchema(state.schema);
}
return state;
}