-
Notifications
You must be signed in to change notification settings - Fork 219
/
index.tsx
259 lines (226 loc) · 7.1 KB
/
index.tsx
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
import React, {
createContext,
FormEvent,
PropsWithChildren,
useContext,
useState,
} from 'react';
import { v4 as uuid } from 'uuid';
import { useRouter } from 'next/router';
import { OK } from '#app/lib/statusCodes.const';
import getEnvironment from '#app/routes/utils/getEnvironment';
import {
Field,
FieldData,
FileData,
FormScreen,
OnChangeHandler,
OnChangeInputName,
OnChangeInputValue,
OnFocusOutHandler,
} from '../types';
import UGCSendError from '../UGCSendError';
import validateFunctions from './utils/validateFunctions';
type SubmissionError = {
message: string;
code?: string;
status: number;
isRecoverable?: boolean;
} | null;
export type ContextProps = {
formState: Record<OnChangeInputName, FieldData>;
handleChange: OnChangeHandler;
handleFocusOut: OnFocusOutHandler;
handleSubmit: (event: FormEvent) => Promise<void>;
submissionError?: SubmissionError;
submitted: boolean;
attemptedSubmitCount: number;
hasValidationErrors: boolean;
progress: string;
screen: FormScreen;
submissionID: string | null;
};
export const FormContext = createContext({} as ContextProps);
const getInitialFormState = (
fields: Field[],
): Record<OnChangeInputName, FieldData> =>
fields?.reduce(
(acc, field) => ({
...acc,
[field.id]: {
...(field.validation && field.validation),
isValid: true,
required: field.validation.mandatory ?? false,
wordLimit: field.validation.wordLimit ?? undefined,
value: field.htmlType === 'file' ? [] : '',
htmlType: field.htmlType,
messageCode: null,
wasInvalid: false,
},
}),
{},
);
const validateFormState = (state: Record<OnChangeInputName, FieldData>) => {
const formEntries = new Map(Object.entries(state));
formEntries.forEach((data, key, map) => {
const validateFunction = validateFunctions[data.htmlType];
const validatedData = validateFunction ? validateFunction(data) : data;
map.set(key, validatedData);
});
return Object.fromEntries(formEntries);
};
const isFormStateValid = (state: Record<OnChangeInputName, FieldData>) => {
const formInvalidErrors = Object.values(state).filter(
item => item.isValid === false,
).length;
const isValid = formInvalidErrors === 0;
return isValid;
};
export const FormContextProvider = ({
initialScreen = 'form',
fields,
children,
}: PropsWithChildren<{ initialScreen?: FormScreen; fields: Field[] }>) => {
const {
query: { id },
asPath,
} = useRouter();
const [formState, setFormState] = useState(getInitialFormState(fields));
const [submitted, setSubmitted] = useState(false);
const [progress, setProgress] = useState('0');
const [screen, setScreen] = useState<FormScreen>(initialScreen);
const [submissionError, setSubmissionError] = useState<SubmissionError>(null);
const [attemptedSubmitCount, setAttemptedSubmitCount] = useState(0);
const [hasValidationErrors, setHasValidationErrors] = useState(false);
const [submissionID, setSubmissionID] = useState(null);
const handleChange = (name: OnChangeInputName, value: OnChangeInputValue) => {
const prevState = formState[name];
const currState = { ...prevState, value };
let validatedData = currState;
if (currState.htmlType === 'file') {
const validateFunction = validateFunctions.file;
validatedData = validateFunction
? validateFunction(currState)
: currState;
}
const updatedState = { [name]: { ...validatedData } };
const newFormState = { ...formState, ...updatedState };
setFormState(newFormState);
if (currState.htmlType === 'file') {
const isFormValid = isFormStateValid(newFormState);
setHasValidationErrors(!isFormValid);
}
};
const handleFocusOut = (name: OnChangeInputName) => {
const currState = formState[name];
const validateFunction = validateFunctions[currState.htmlType];
const validatedData = validateFunction
? validateFunction(currState)
: currState;
const updatedState = { [name]: { ...validatedData } };
const newFormState = { ...formState, ...updatedState };
const isFormValid = isFormStateValid(newFormState);
setHasValidationErrors(!isFormValid);
setFormState(newFormState);
};
const handleSubmit = async (event: FormEvent) => {
event.preventDefault();
setAttemptedSubmitCount(prevCount => prevCount + 1);
// Reset error state
setSubmissionError(null);
const validatedFormData = validateFormState(formState);
setFormState(validatedFormData);
const isFormValid = isFormStateValid(validatedFormData);
if (!isFormValid) {
setHasValidationErrors(true);
return;
}
setSubmitted(true);
const formData = new FormData();
Object.entries(formState).forEach(([key, item]) => {
const fieldValue = item.value;
const isFileHtmlType = item.htmlType === 'file';
if (fieldValue === '') return;
if (isFileHtmlType) {
const fileList = fieldValue as FileData[];
fileList.forEach(({ file }: FileData) => {
formData.append(key, file);
});
return;
}
if (typeof fieldValue === 'boolean') {
if (fieldValue) formData.append(key, 'true');
return;
}
formData.append(key, fieldValue as string);
});
try {
const environment = getEnvironment(asPath);
const domain = `https://www.${environment === 'test' ? 'test.' : ''}bbc.com`;
const url = `${domain}/ugc/send/${id}?said=${uuid()}`;
const req = new XMLHttpRequest();
req.responseType = 'json';
req.open('POST', url, true);
req.upload.onloadstart = () => {
setScreen('uploading');
};
req.upload.onprogress = e => {
setProgress(((e.loaded / e.total) * 100).toFixed(0));
};
req.onreadystatechange = () => {
if (req.readyState === XMLHttpRequest.DONE) {
setSubmitted(false);
if (req.status === OK) {
setSubmissionID(req.response.submissionId);
setTimeout(() => {
setScreen('success');
}, 3000);
}
if (req.status !== OK) {
const { message, code, status, isRecoverable } = new UGCSendError(
req,
);
setSubmissionError({
message,
code,
status,
isRecoverable,
});
setTimeout(() => {
setScreen('error');
}, 3000);
}
}
};
req.send(formData);
} catch (error) {
const { message, status } = error as UGCSendError;
setSubmissionError({ message, status });
setTimeout(() => {
setScreen('error');
}, 3000);
}
};
return (
<FormContext.Provider
value={{
formState,
handleChange,
handleFocusOut,
handleSubmit,
submissionError,
submitted,
progress,
attemptedSubmitCount,
hasValidationErrors,
screen,
submissionID,
}}
>
{children}
</FormContext.Provider>
);
};
export function useFormContext() {
return useContext(FormContext);
}