-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidatedForm.tsx
More file actions
481 lines (401 loc) · 13.1 KB
/
ValidatedForm.tsx
File metadata and controls
481 lines (401 loc) · 13.1 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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import React, {
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import {
NativeScrollEvent,
NativeSyntheticEvent,
Platform,
} from "react-native";
import useBufferedState from "./hooks/useBufferedState";
import { ScrollableComponent } from "./types";
import { ScrollView } from "react-native";
import { getScrollableNode, scrollTo } from "./utils";
interface IValidatedFormProps {
/** If set, ValidatedForm will not automatically validate fields when their state is updated. Default is `false` */
disableValidateFieldOnChange?: boolean;
}
export type ScrollEvent = Pick<
NativeSyntheticEvent<Pick<NativeScrollEvent, "contentOffset">>,
"nativeEvent"
>;
export type ValidatedFormFields = {
[fieldName: string]: ValidatedFieldState | undefined;
};
type ValidatedFieldState = {
valid: boolean;
yOffset: number;
measureYOffset: () => Promise<number>;
validateCallback: () => boolean;
};
type ValidatorState = {
ready: boolean;
fields: ValidatedFormFields;
};
export type FormContext = {
readonly state: ValidatorState;
readonly removeField: (fieldName: string) => void;
readonly addField: (
fieldName: string,
valid: boolean,
validateCallback: () => boolean,
measureYOffset: () => Promise<number>
) => void;
readonly resetValidations: () => void;
readonly validateField: (fieldName: string) => void;
readonly updateFieldOffsetY: (fieldName: string, yOffset: number) => void;
readonly validateForm: () => boolean;
readonly _internal_setScrollViewRef: (
ref:
| React.RefObject<
ScrollView | ScrollableComponent<any, any> | undefined | null
>
| undefined
) => void;
readonly _internal_setExtraScrollHeight: (value: number) => void;
readonly _internal_extraScrollHeight: number;
readonly _internal_setScrollY: (value: number | undefined) => void;
readonly _internal_scrollViewRef:
| React.RefObject<
ScrollView | ScrollableComponent<any, any> | undefined | null
>
| undefined;
readonly _internal_disableValidateFieldOnChange: boolean | undefined;
};
const DEFAULT_VALIDATOR_STATE: ValidatorState = {
ready: false,
fields: {},
};
let ctx = React.createContext<FormContext>(null as any);
export default function ValidatedForm(
props: React.PropsWithChildren<IValidatedFormProps>
) {
/** useBufferedState to avoid lag spikes when initializing large forms */
const [validatorState, setValidatorState] = useBufferedState<ValidatorState>(
DEFAULT_VALIDATOR_STATE
);
useEffect(() => {
// Initialize the form by setting ready to true
// This state change will happen at the same time as we set all initially rendered fields
// into state if any exist
/**
* We use this to ensure that we never return true in validateForm() until all
* fields have been added to state, but also without requiring us to have any
* fields in the form to begin with.
*/
setValidatorState((prevState) => ({
...prevState,
ready: true,
}));
}, [setValidatorState]);
const scrollYRef = useRef<number | undefined>(undefined);
const scrollViewRef = useRef<
ScrollView | ScrollableComponent<any, any> | undefined | null
>(undefined);
const [extraScrollHeight, setExtraScrollHeight] = useState(0);
const setScrollViewRef = useCallback(
(
ref:
| React.RefObject<
ScrollView | ScrollableComponent<any, any> | undefined | null
>
| undefined
): void => {
if (!ref?.current) {
scrollViewRef.current = undefined;
return;
}
scrollViewRef.current = ref.current;
},
[]
);
const updateFieldOffsetY = useCallback(
(name: string, yOffset: number) => {
setValidatorState((prevState) => {
const newState = { ...prevState };
const field = newState.fields[name];
if (field) field.yOffset = yOffset;
return newState;
});
},
[setValidatorState]
);
const addField = useCallback(
(
name: string,
valid: boolean,
validateCallback: () => boolean,
mesaureYOffset: () => Promise<number>
) => {
if (validatorState.fields[name]) {
// If we are adding a field that already exists, user has created two
// or more fields with the same name, which is illegal
console.warn(
`Found two or more fields with name ${name}. This will cause unexpected behavior when validating form.`
);
return;
}
// Update validatorState and validatorCallbacks
setValidatorState((prevState) => {
const newField: ValidatedFormFields[string] = {
valid,
measureYOffset: mesaureYOffset,
yOffset: 0,
validateCallback,
};
return {
...prevState,
fields: {
...prevState.fields,
[name]: newField,
},
};
});
},
[setValidatorState, validatorState.fields]
);
const removeField = useCallback(
(name: string) => {
setValidatorState((prevState) => {
// Remove from fields
const newState = { ...prevState };
delete newState.fields[name];
return newState;
});
},
[setValidatorState]
);
const validateField = useCallback(
(name: string) => {
const field = validatorState.fields[name];
if (!field) {
console.log("Trying to validate non-existing field!");
return;
}
// If `valid` has not changed, do nothing
if (field.valid === field.validateCallback()) return;
setValidatorState((prevState) => {
const newState = { ...prevState };
const isValid = field.validateCallback();
const targetField = newState.fields[name];
if (targetField) targetField.valid = isValid;
return newState;
});
},
[validatorState.fields, setValidatorState]
);
const measureYOffsets = useCallback(() => {
Object.entries(validatorState.fields).forEach(([name, field]) => {
if (!field) return;
field.measureYOffset().then((yOffset) => {
/** `measureYOffset` works differently in react-native-web. We have to account for the
* current scroll position in order to get the correct yOffset */
const webAdjustment =
Platform.OS === "web" ? scrollYRef.current ?? 0 : 0;
updateFieldOffsetY(name, yOffset + webAdjustment);
});
});
}, [updateFieldOffsetY, validatorState.fields]);
/**
* Updates validator state calling validate() for each field
* @returns boolean - True if form is valid, false otherwise
*/
const validateForm = useCallback(() => {
if (validatorState.ready === false) return false;
let isFormValid = true;
measureYOffsets();
const newState = { ...validatorState };
Object.keys(newState.fields).forEach((fieldName) => {
const isValid = newState.fields[fieldName]?.validateCallback();
// console.log(`${fieldName} is valid?`, isValid);
// If we encounter an invalid field, set isFormValid to false
if (!isValid) isFormValid = false;
const field = newState.fields[fieldName];
// If `valid` is unchanged, skip to next field
if (isValid === field?.valid) return;
if (field) field.valid = !!isValid;
});
setValidatorState(() => newState);
return isFormValid;
}, [validatorState, measureYOffsets, setValidatorState]);
const resetValidations = useCallback(() => {
setValidatorState((prevState) => {
const newState = { ...prevState };
Object.keys(newState.fields).forEach((fieldName) => {
const field = newState.fields[fieldName];
if (field) field.valid = true;
});
return newState;
});
}, [setValidatorState]);
/** Works around scroll event not firing on react-native-web under certain conditions */
const setScrollY = useCallback((value: number | undefined) => {
scrollYRef.current = value;
}, []);
return (
<ctx.Provider
value={{
addField,
removeField,
validateField,
validateForm,
resetValidations,
updateFieldOffsetY,
_internal_setScrollY: setScrollY,
_internal_setScrollViewRef: setScrollViewRef,
_internal_setExtraScrollHeight: setExtraScrollHeight,
_internal_extraScrollHeight: extraScrollHeight,
_internal_scrollViewRef: scrollViewRef,
_internal_disableValidateFieldOnChange:
props.disableValidateFieldOnChange,
state: validatorState,
}}
>
{props.children}
</ctx.Provider>
);
}
export { ctx as ValidatedFormContext };
export type UseFormValidationContextReturns = {
/** Scrolls to first invalid field */
scrollToInvalidFields: () => void;
/** Validates all fields */
validateForm: (scrollIfInvalid?: boolean) => boolean;
/** Resets all fields to valid */
resetValidations: () => void;
/** Returns all fields in form */
fields: Partial<ValidatedFormFields>;
};
/** Hook for form validation actions */
export const useFormValidationContext = (): UseFormValidationContextReturns => {
const _context = useContext(ctx);
if (!_context) {
throw new Error(
"[ValidatedForm] useFormValidationContext hook was called but no context could be found. Make sure you are wrapping your component in withFormValidation or <ValidatedForm />"
);
}
const {
state,
validateForm: _validate,
_internal_extraScrollHeight,
_internal_scrollViewRef,
} = _context;
const queueScrollToInvalidFields = useRef(false);
/** Scrolls to invalid field with lowest y-offset value */
const scrollToInvalidFields = useCallback(
function () {
const _scrollView = _internal_scrollViewRef?.current;
const scrollableNode = getScrollableNode(_scrollView as any);
if (!scrollableNode) return;
let shouldScroll = false,
shouldScrollToOffset: number | undefined;
/** DEBUG */
// console.log('scrolling, fields:', state.fields);
Object.entries(state.fields ?? {}).forEach(([, field]) => {
if (!field) return;
if (!field.valid) {
shouldScroll = true;
if (
typeof shouldScrollToOffset !== "number" ||
field.yOffset < shouldScrollToOffset
) {
shouldScrollToOffset = field.yOffset;
}
}
});
if (shouldScroll && typeof shouldScrollToOffset === "number") {
// Add padding to scroll position
shouldScrollToOffset = Math.max(
shouldScrollToOffset - _internal_extraScrollHeight,
0
);
// Use the scrollTo utility function
scrollTo(scrollableNode, {
y: shouldScrollToOffset,
animated: true,
});
}
},
[_internal_scrollViewRef, _internal_extraScrollHeight, state.fields]
);
useEffect(() => {
if (queueScrollToInvalidFields.current) {
scrollToInvalidFields();
queueScrollToInvalidFields.current = false;
}
}, [scrollToInvalidFields, state]);
/**
* Validate all form fields.
* @param scrollIfInvalid If form is invalid, scrolls to first invalid field. Default is `true`.
* @returns boolean - True if form is valid, false otherwise.
*/
const validateForm = (scrollIfInvalid = true) => {
const isValid = _validate();
if (!isValid && scrollIfInvalid) {
queueScrollToInvalidFields.current = true;
}
return isValid;
};
return {
scrollToInvalidFields,
validateForm,
resetValidations: _context.resetValidations,
fields: state.fields as Partial<ValidatedFormFields>,
};
};
type UseValidatedFormAutoscrollReturns = {
/** Use for dynamic forms. Makes sure correct y-offset measurement
* for fields added after scrolling */
onScroll: (e: ScrollEvent) => void;
};
export const useValidatedFormAutoscroll = ({
scrollViewRef,
extraScrollHeight = 40,
}: {
/** Required for scrolling to invalid fields. If this is not provided, scrolling
* will be disabled.
*/
scrollViewRef?: React.RefObject<
ScrollView | ScrollableComponent<any, any> | undefined | null
>;
/** Default is `40` */
extraScrollHeight?: number;
}): UseValidatedFormAutoscrollReturns => {
const _context = useContext(ctx);
if (!_context) {
throw new Error(
"[ValidatedForm] useValidatedFormAutoscroll hook was called but no context could be found. Make sure you are wrapping your component in withFormValidation or <ValidatedForm />"
);
}
const {
_internal_setExtraScrollHeight,
_internal_setScrollY,
_internal_setScrollViewRef,
} = _context;
useEffect(() => {
if (typeof extraScrollHeight === "number") {
_internal_setExtraScrollHeight(extraScrollHeight);
}
}, [extraScrollHeight, _internal_setExtraScrollHeight]);
/** This side effect handles updating scrollViewNodeHandle */
useEffect(() => {
if (scrollViewRef?.current) {
_internal_setScrollViewRef(scrollViewRef);
} else {
_internal_setScrollViewRef(undefined);
}
}, [scrollViewRef, _internal_setScrollViewRef]);
const onScroll = useCallback(
(e: ScrollEvent) => {
const { contentOffset } = e.nativeEvent;
_internal_setScrollY(contentOffset.y);
},
[_internal_setScrollY]
);
return {
onScroll,
};
};