forked from ToolJet/ToolJet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm.jsx
More file actions
324 lines (300 loc) · 11 KB
/
Form.jsx
File metadata and controls
324 lines (300 loc) · 11 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import React, { useRef, useState, useEffect } from 'react';
import { SubCustomDragLayer } from '@/Editor/SubCustomDragLayer';
import { SubContainer } from '@/Editor/SubContainer';
// eslint-disable-next-line import/no-unresolved
import { diff } from 'deep-object-diff';
import _, { debounce, omit } from 'lodash';
import { Box } from '@/Editor/Box';
import { generateUIComponents } from './FormUtils';
import { useMounted } from '@/_hooks/use-mount';
import {
onComponentClick,
onComponentOptionChanged,
onComponentOptionsChanged,
removeFunctionObjects,
} from '@/_helpers/appUtils';
import { useAppInfo } from '@/_stores/appDataStore';
import { deepClone } from '@/_helpers/utilities/utils.helpers';
export const Form = function Form(props) {
const {
id,
component,
width,
height,
removeComponent,
styles,
setExposedVariable,
setExposedVariables,
darkMode,
currentState,
fireEvent,
properties,
resetComponent,
onEvent,
dataCy,
paramUpdated,
currentLayout,
mode,
getContainerProps,
containerProps,
childComponents,
} = props;
const { events: allAppEvents } = useAppInfo();
const formEvents = allAppEvents.filter((event) => event.target === 'component' && event.sourceId === id);
const { visibility, disabledState, borderRadius, borderColor, boxShadow } = styles;
const { buttonToSubmit, loadingState, advanced, JSONSchema } = properties;
const backgroundColor =
['#fff', '#ffffffff'].includes(styles.backgroundColor) && darkMode ? '#232E3C' : styles.backgroundColor;
const computedStyles = {
backgroundColor,
borderRadius: borderRadius ? parseFloat(borderRadius) : 0,
border: `1px solid ${borderColor}`,
height,
display: visibility ? 'flex' : 'none',
position: 'relative',
overflow: 'hidden auto',
boxShadow,
};
const parentRef = useRef(null);
const childDataRef = useRef({});
const [childrenData, setChildrenData] = useState({});
const [isValid, setValidation] = useState(true);
const [uiComponents, setUIComponents] = useState([]);
const mounted = useMounted();
useEffect(() => {
setExposedVariable('resetForm', async function () {
resetComponent();
});
setExposedVariable('submitForm', async function () {
if (isValid) {
onEvent('onSubmit', formEvents).then(() => resetComponent());
} else {
fireEvent('onInvalid');
}
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const extractData = (data) => {
const result = {};
for (const key in data) {
const item = data[key];
if (item.name === 'Text') {
const textKey = item?.formKey ?? item?.text;
const nextItem = data[parseInt(key) + 1];
if (nextItem && nextItem.name !== 'Text') {
result[textKey] = { ...nextItem };
delete result[textKey].name;
}
}
}
return result;
};
useEffect(() => {
if (mounted) resetComponent();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [JSON.stringify(JSONSchema)]);
useEffect(() => {
advanced && setExposedVariable('children', []);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [advanced]);
useEffect(() => {
setUIComponents(generateUIComponents(JSONSchema, advanced, component.name));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [JSON.stringify(JSONSchema), advanced]);
const checkJsonChildrenValidtion = () => {
const isValid = Object.values(childrenData).every((item) => item?.isValid !== false);
return isValid;
};
useEffect(() => {
let formattedChildData = {};
let childValidation = true;
if (!childComponents) {
const exposedVariables = {
data: formattedChildData,
isValid: childValidation,
...(!advanced && { children: formattedChildData }),
};
setExposedVariables(exposedVariables);
return setValidation(childValidation);
}
if (advanced) {
formattedChildData = extractData(childrenData);
childValidation = checkJsonChildrenValidtion();
} else {
Object.keys(childComponents ?? {}).forEach((childId) => {
if (childrenData[childId]?.name) {
const componentName = childComponents?.[childId]?.component?.name;
formattedChildData[componentName] = { ...omit(childrenData[childId], 'name'), id: childId };
childValidation = childValidation && (childrenData[childId]?.isValid ?? true);
}
});
}
formattedChildData = Object.fromEntries(
// eslint-disable-next-line no-unused-vars
Object.entries(formattedChildData).map(([key, { formKey, ...rest }]) => [key, rest]) // removing formkey from final exposed data
);
const formattedChildDataClone = deepClone(formattedChildData);
const exposedVariables = {
...(!advanced && { children: formattedChildDataClone }),
data: removeFunctionObjects(formattedChildData),
isValid: childValidation,
};
setValidation(childValidation);
setExposedVariables(exposedVariables);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [childrenData, childComponents, advanced, JSON.stringify(JSONSchema)]);
useEffect(() => {
const childIds = Object.keys(childrenData);
Object.entries(currentState.components).forEach(([name, value]) => {
if (childIds.includes(value.id) && name !== childrenData[value.id]?.name) {
childDataRef.current = {
...childDataRef.current,
[value.id]: { ...childDataRef.current[value.id], name: name },
};
}
});
if (Object.keys(diff(childrenData, childDataRef.current).length !== 0)) {
setChildrenData(childDataRef.current);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentState.components]);
useEffect(() => {
document.addEventListener('submitForm', handleFormSubmission);
return () => document.removeEventListener('submitForm', handleFormSubmission);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [buttonToSubmit, isValid, advanced, JSON.stringify(uiComponents), formEvents]);
const handleSubmit = (event) => {
event.preventDefault();
};
const fireSubmissionEvent = () => {
if (isValid) {
onEvent('onSubmit', formEvents).then(() => {
debounce(() => resetComponent(), 100)();
});
} else {
fireEvent('onInvalid');
}
};
const handleFormSubmission = ({ detail: { buttonComponentId } }) => {
if (!advanced) {
if (buttonToSubmit === buttonComponentId) {
fireSubmissionEvent();
}
} else if (buttonComponentId == uiComponents.length - 1 && JSONSchema.hasOwnProperty('submitButton')) {
fireSubmissionEvent();
}
};
//for custom json
function onComponentOptionChangedForSubcontainer(component, optionName, value, componentId = '') {
if (typeof value === 'function' && _.findKey({}, optionName)) {
return Promise.resolve();
}
onOptionChange({ component, optionName, value, componentId });
return onComponentOptionChanged(component, optionName, value);
}
const onOptionChange = ({ component, optionName, value, componentId }) => {
const optionData = {
...(childDataRef.current[componentId] ?? {}),
name: component.name,
[optionName]: value,
formKey: component?.formKey, //adding this to use as exposed key
};
childDataRef.current = { ...childDataRef.current, [componentId]: optionData };
setChildrenData(childDataRef.current);
};
return (
<form
className={`jet-container ${advanced && 'jet-container-json-form'}`}
id={id}
data-cy={dataCy}
ref={parentRef}
style={computedStyles}
onSubmit={handleSubmit}
onClick={(e) => {
if (e.target.className === 'real-canvas') onComponentClick(id, component);
}} //Hack, should find a better solution - to prevent losing z index+1 when container element is clicked
>
{loadingState ? (
<div className="p-2" style={{ margin: '0px auto' }}>
<center>
<div className="spinner-border mt-5" role="status"></div>
</center>
</div>
) : (
<fieldset disabled={disabledState}>
{!advanced && (
<div className={'json-form-wrapper-disabled'}>
<SubContainer
parentComponent={component}
containerCanvasWidth={width}
parent={id}
parentRef={parentRef}
removeComponent={removeComponent}
onOptionChange={function ({ component, optionName, value, componentId }) {
if (componentId) {
onOptionChange({ component, optionName, value, componentId });
}
}}
currentPageId={props.currentPageId}
{...props}
{...containerProps}
height={'100%'} // This height is required since Subcontainer has a issue if height is provided, it stores it in the ref and never updates that ref
/>
<SubCustomDragLayer
containerCanvasWidth={width}
parent={id}
parentRef={parentRef}
currentLayout={currentLayout}
/>
</div>
)}
{advanced &&
uiComponents?.map((item, index) => {
return (
<div
//check to avoid labels for these widgets as label is already present for them
className={
![
'Checkbox',
'StarRating',
'Multiselect',
'DropDown',
'RadioButton',
'ToggleSwitch',
'ToggleSwitchV2',
].includes(uiComponents?.[index + 1]?.component)
? `json-form-wrapper json-form-wrapper-disabled`
: `json-form-wrapper json-form-wrapper-disabled form-label-restricted`
}
key={index}
>
<Box
{...props}
component={item}
id={index}
width={width}
height={item.defaultSize.height}
mode={mode}
inCanvas={true}
paramUpdated={paramUpdated}
onEvent={onEvent}
onComponentClick={onComponentClick}
darkMode={darkMode}
removeComponent={removeComponent}
// canvasWidth={width}
// readOnly={readOnly}
// customResolvables={customResolvables}
parentId={id}
getContainerProps={getContainerProps}
onOptionChanged={onComponentOptionChangedForSubcontainer}
onOptionsChanged={onComponentOptionsChanged}
isFromSubContainer={true}
/>
</div>
);
})}
</fieldset>
)}
</form>
);
};