envoc-form 4.0.1-8 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/README.md +5117 -12
  2. package/es/AddressInput/AddressInput.d.ts +15 -5
  3. package/es/AddressInput/AddressInput.js +10 -0
  4. package/es/ConfirmBaseForm/ConfirmBaseForm.d.ts +14 -0
  5. package/es/ConfirmBaseForm/ConfirmBaseForm.js +6 -0
  6. package/es/ConfirmDeleteForm/ConfirmDeleteForm.d.ts +13 -0
  7. package/es/ConfirmDeleteForm/ConfirmDeleteForm.js +5 -0
  8. package/es/DatePicker/DatePickerGroup.d.ts +7 -2
  9. package/es/DatePicker/DatePickerGroup.js +16 -6
  10. package/es/DatePicker/StringDateOnlyPickerGroup.d.ts +6 -1
  11. package/es/DatePicker/StringDateOnlyPickerGroup.js +5 -0
  12. package/es/DatePicker/StringDatePickerGroup.d.ts +6 -1
  13. package/es/DatePicker/StringDatePickerGroup.js +5 -0
  14. package/es/Field/Field.d.ts +9 -3
  15. package/es/Field/Field.js +9 -4
  16. package/es/Field/FieldErrorScrollTarget.d.ts +1 -0
  17. package/es/Field/FieldErrorScrollTarget.js +1 -0
  18. package/es/Field/StandAloneInput.d.ts +4 -0
  19. package/es/Field/StandAloneInput.js +1 -0
  20. package/es/Field/useStandardField.d.ts +6 -0
  21. package/es/Field/useStandardField.js +8 -9
  22. package/es/FieldArray/FieldArray.d.ts +11 -2
  23. package/es/FieldArray/FieldArray.js +7 -2
  24. package/es/File/FileGroup.d.ts +3 -1
  25. package/es/File/FileGroup.js +4 -3
  26. package/es/File/FileList.d.ts +2 -2
  27. package/es/Form/FocusError.d.ts +2 -0
  28. package/es/Form/FocusError.js +1 -0
  29. package/es/Form/Form.d.ts +6 -0
  30. package/es/Form/Form.js +1 -0
  31. package/es/Form/FormBasedPreventNavigation.d.ts +3 -1
  32. package/es/Form/FormBasedPreventNavigation.js +12 -45
  33. package/es/Form/LegacyFormBasedPreventNavigation.d.ts +17 -0
  34. package/es/Form/LegacyFormBasedPreventNavigation.js +69 -0
  35. package/es/Form/NewFormBasedPreventNavigation.d.ts +14 -0
  36. package/es/Form/NewFormBasedPreventNavigation.js +39 -0
  37. package/es/Form/ServerErrorContext.d.ts +1 -0
  38. package/es/Form/ServerErrorContext.js +1 -0
  39. package/es/FormActions.d.ts +6 -0
  40. package/es/FormActions.js +1 -0
  41. package/es/FormDefaults.d.ts +1 -0
  42. package/es/FormDefaults.js +1 -0
  43. package/es/Group.d.ts +7 -4
  44. package/es/Group.js +4 -3
  45. package/es/Input/IconInputGroup.d.ts +4 -1
  46. package/es/Input/IconInputGroup.js +3 -1
  47. package/es/Input/InputGroup.d.ts +4 -4
  48. package/es/Input/InputGroup.js +4 -4
  49. package/es/Input/MoneyInputGroup.d.ts +3 -1
  50. package/es/Input/MoneyInputGroup.js +1 -0
  51. package/es/Input/NumberInputGroup.d.ts +3 -1
  52. package/es/Input/NumberInputGroup.js +1 -0
  53. package/es/Input/StringInputGroup.d.ts +2 -1
  54. package/es/Input/StringInputGroup.js +3 -1
  55. package/es/Normalization/normalizers.d.ts +4 -2
  56. package/es/Normalization/normalizers.js +2 -0
  57. package/es/Select/BooleanSelectGroup.d.ts +2 -1
  58. package/es/Select/BooleanSelectGroup.js +1 -0
  59. package/es/Select/NumberSelectGroup.d.ts +4 -2
  60. package/es/Select/NumberSelectGroup.js +2 -0
  61. package/es/Select/SelectGroup.d.ts +8 -2
  62. package/es/Select/SelectGroup.js +5 -4
  63. package/es/Select/StringSelectGroup.d.ts +2 -0
  64. package/es/Select/StringSelectGroup.js +2 -0
  65. package/es/StandardFormActions.d.ts +5 -0
  66. package/es/StandardFormActions.js +1 -0
  67. package/es/SubmitFormButton.d.ts +4 -1
  68. package/es/SubmitFormButton.js +1 -0
  69. package/es/TextArea/TextAreaGroup.d.ts +2 -1
  70. package/es/TextArea/TextAreaGroup.js +5 -4
  71. package/es/Validation/validators.d.ts +11 -8
  72. package/es/Validation/validators.js +6 -2
  73. package/es/index.d.ts +4 -4
  74. package/es/setupTests.d.ts +1 -0
  75. package/es/setupTests.js +1 -0
  76. package/lib/AddressInput/AddressInput.d.ts +15 -5
  77. package/lib/AddressInput/AddressInput.js +10 -0
  78. package/lib/ConfirmBaseForm/ConfirmBaseForm.d.ts +14 -0
  79. package/lib/ConfirmBaseForm/ConfirmBaseForm.js +6 -0
  80. package/lib/ConfirmDeleteForm/ConfirmDeleteForm.d.ts +13 -0
  81. package/lib/ConfirmDeleteForm/ConfirmDeleteForm.js +5 -0
  82. package/lib/DatePicker/DatePickerGroup.d.ts +7 -2
  83. package/lib/DatePicker/DatePickerGroup.js +16 -6
  84. package/lib/DatePicker/StringDateOnlyPickerGroup.d.ts +6 -1
  85. package/lib/DatePicker/StringDateOnlyPickerGroup.js +5 -0
  86. package/lib/DatePicker/StringDatePickerGroup.d.ts +6 -1
  87. package/lib/DatePicker/StringDatePickerGroup.js +5 -0
  88. package/lib/Field/Field.d.ts +9 -3
  89. package/lib/Field/Field.js +9 -4
  90. package/lib/Field/FieldErrorScrollTarget.d.ts +1 -0
  91. package/lib/Field/FieldErrorScrollTarget.js +1 -0
  92. package/lib/Field/StandAloneInput.d.ts +4 -0
  93. package/lib/Field/StandAloneInput.js +1 -0
  94. package/lib/Field/useStandardField.d.ts +6 -0
  95. package/lib/Field/useStandardField.js +8 -9
  96. package/lib/FieldArray/FieldArray.d.ts +11 -2
  97. package/lib/FieldArray/FieldArray.js +7 -2
  98. package/lib/File/FileGroup.d.ts +3 -1
  99. package/lib/File/FileGroup.js +4 -3
  100. package/lib/File/FileList.d.ts +2 -2
  101. package/lib/Form/FocusError.d.ts +2 -0
  102. package/lib/Form/FocusError.js +1 -0
  103. package/lib/Form/Form.d.ts +6 -0
  104. package/lib/Form/Form.js +1 -0
  105. package/lib/Form/FormBasedPreventNavigation.d.ts +3 -1
  106. package/lib/Form/FormBasedPreventNavigation.js +13 -43
  107. package/lib/Form/LegacyFormBasedPreventNavigation.d.ts +17 -0
  108. package/lib/Form/LegacyFormBasedPreventNavigation.js +72 -0
  109. package/lib/Form/NewFormBasedPreventNavigation.d.ts +14 -0
  110. package/lib/Form/NewFormBasedPreventNavigation.js +42 -0
  111. package/lib/Form/ServerErrorContext.d.ts +1 -0
  112. package/lib/Form/ServerErrorContext.js +1 -0
  113. package/lib/FormActions.d.ts +6 -0
  114. package/lib/FormActions.js +1 -0
  115. package/lib/FormDefaults.d.ts +1 -0
  116. package/lib/FormDefaults.js +1 -0
  117. package/lib/Group.d.ts +7 -4
  118. package/lib/Group.js +4 -3
  119. package/lib/Input/IconInputGroup.d.ts +4 -1
  120. package/lib/Input/IconInputGroup.js +3 -1
  121. package/lib/Input/InputGroup.d.ts +4 -4
  122. package/lib/Input/InputGroup.js +4 -4
  123. package/lib/Input/MoneyInputGroup.d.ts +3 -1
  124. package/lib/Input/MoneyInputGroup.js +1 -0
  125. package/lib/Input/NumberInputGroup.d.ts +3 -1
  126. package/lib/Input/NumberInputGroup.js +1 -0
  127. package/lib/Input/StringInputGroup.d.ts +2 -1
  128. package/lib/Input/StringInputGroup.js +3 -1
  129. package/lib/Normalization/normalizers.d.ts +4 -2
  130. package/lib/Normalization/normalizers.js +2 -0
  131. package/lib/Select/BooleanSelectGroup.d.ts +2 -1
  132. package/lib/Select/BooleanSelectGroup.js +1 -0
  133. package/lib/Select/NumberSelectGroup.d.ts +4 -2
  134. package/lib/Select/NumberSelectGroup.js +2 -0
  135. package/lib/Select/SelectGroup.d.ts +8 -2
  136. package/lib/Select/SelectGroup.js +5 -4
  137. package/lib/Select/StringSelectGroup.d.ts +2 -0
  138. package/lib/Select/StringSelectGroup.js +2 -0
  139. package/lib/StandardFormActions.d.ts +5 -0
  140. package/lib/StandardFormActions.js +1 -0
  141. package/lib/SubmitFormButton.d.ts +4 -1
  142. package/lib/SubmitFormButton.js +1 -0
  143. package/lib/TextArea/TextAreaGroup.d.ts +2 -1
  144. package/lib/TextArea/TextAreaGroup.js +5 -4
  145. package/lib/Validation/validators.d.ts +11 -8
  146. package/lib/Validation/validators.js +6 -2
  147. package/lib/index.d.ts +4 -4
  148. package/lib/setupTests.d.ts +1 -0
  149. package/lib/setupTests.js +3 -0
  150. package/package.json +9 -6
  151. package/src/AddressInput/AddressInput.tsx +15 -5
  152. package/src/AddressInput/__snapshots__/AddressInput.test.tsx.snap +8 -4
  153. package/src/ConfirmBaseForm/ConfirmBaseForm.tsx +14 -0
  154. package/src/ConfirmDeleteForm/ConfirmDeleteForm.tsx +13 -0
  155. package/src/DatePicker/DatePicker.test.tsx +1 -1
  156. package/src/DatePicker/DatePickerGroup.tsx +18 -7
  157. package/src/DatePicker/StringDateOnlyPickerGroup.tsx +7 -2
  158. package/src/DatePicker/StringDatePickerGroup.tsx +7 -1
  159. package/src/Field/Field.tsx +20 -7
  160. package/src/Field/FieldErrorScrollTarget.tsx +1 -0
  161. package/src/Field/StandAloneInput.tsx +4 -0
  162. package/src/Field/useStandardField.ts +13 -9
  163. package/src/FieldArray/FieldArray.tsx +14 -5
  164. package/src/File/FileGroup.tsx +9 -3
  165. package/src/File/FileList.tsx +2 -2
  166. package/src/Form/FocusError.tsx +3 -0
  167. package/src/Form/Form.tsx +6 -0
  168. package/src/Form/FormBasedPreventNavigation.tsx +28 -46
  169. package/src/Form/LegacyFormBasedPreventNavigation.tsx +77 -0
  170. package/src/Form/NewFormBasedPreventNavigation.tsx +59 -0
  171. package/src/Form/ServerErrorContext.ts +1 -0
  172. package/src/FormActions.tsx +7 -0
  173. package/src/FormDefaults.ts +1 -0
  174. package/src/Group.tsx +12 -4
  175. package/src/Input/IconInputGroup.tsx +5 -2
  176. package/src/Input/InputGroup.tsx +13 -5
  177. package/src/Input/MoneyInputGroup.tsx +3 -1
  178. package/src/Input/NumberInputGroup.tsx +3 -1
  179. package/src/Input/StringInputGroup.tsx +3 -2
  180. package/src/Input/__Tests__/__snapshots__/IconInputGroup.test.tsx.snap +1 -0
  181. package/src/Input/__Tests__/__snapshots__/MoneyInputGroup.test.tsx.snap +1 -0
  182. package/src/Input/__Tests__/__snapshots__/NumberInputGroup.test.tsx.snap +1 -0
  183. package/src/Input/__Tests__/__snapshots__/StringInputGroup.test.tsx.snap +1 -0
  184. package/src/Normalization/normalizers.ts +4 -2
  185. package/src/Select/BooleanSelectGroup.tsx +2 -1
  186. package/src/Select/NumberSelectGroup.tsx +4 -2
  187. package/src/Select/SelectGroup.tsx +13 -2
  188. package/src/Select/StringSelectGroup.tsx +2 -0
  189. package/src/StandardFormActions.tsx +5 -0
  190. package/src/SubmitFormButton.tsx +5 -1
  191. package/src/TextArea/TextAreaGroup.tsx +6 -4
  192. package/src/Validation/validators.ts +19 -14
  193. package/src/__Tests__/FormTestBase.tsx +9 -8
  194. package/src/__Tests__/RealisticForm.test.tsx +82 -0
  195. package/src/index.ts +4 -4
  196. package/src/setupTests.ts +1 -0
  197. package/es/__Tests__/FormTestBase.d.ts +0 -27
  198. package/es/__Tests__/FormTestBase.js +0 -83
  199. package/es/__Tests__/index.d.ts +0 -2
  200. package/es/__Tests__/index.js +0 -2
  201. package/lib/__Tests__/FormTestBase.d.ts +0 -27
  202. package/lib/__Tests__/FormTestBase.js +0 -86
  203. package/lib/__Tests__/index.d.ts +0 -2
  204. package/lib/__Tests__/index.js +0 -8
@@ -4,6 +4,7 @@ import { InjectedFieldProps } from './InjectedFieldProps';
4
4
  import useStandardFormInput from './useStandardField';
5
5
  import { NormalizationFunction } from '../Normalization/NormalizationFunction';
6
6
  import { ValidationFunction } from '../Validation/ValidationFunction';
7
+ import { required as requiredValidator } from '../Validation/validators';
7
8
 
8
9
  // we attempted to support generic components but failed
9
10
  // so, we assume the actual TRenderComponent has no generic arguments
@@ -13,7 +14,7 @@ export type RenderComponent<
13
14
  TValue,
14
15
  TRenderComponent extends ElementType
15
16
  > = Partial<ComponentProps<TRenderComponent>> extends Partial<
16
- InjectedFieldProps<TValue>
17
+ InjectedFieldProps<TValue | undefined | null>
17
18
  >
18
19
  ? TRenderComponent
19
20
  : never;
@@ -22,7 +23,7 @@ export type RenderComponentProps<
22
23
  TValue,
23
24
  TRenderComponent extends ElementType
24
25
  > = Partial<ComponentProps<TRenderComponent>> extends Partial<
25
- InjectedFieldProps<TValue>
26
+ InjectedFieldProps<TValue | undefined | null>
26
27
  >
27
28
  ? ComponentProps<TRenderComponent>
28
29
  : never;
@@ -33,14 +34,19 @@ export type FieldProps<
33
34
  TProp extends keyof TForm,
34
35
  TRenderComponent extends ElementType
35
36
  > = {
37
+ /** Name of the field. Used on submission. */
36
38
  name: TProp; // somewhat duplicated from useStandardFormInputProps but better for autocomplete
39
+ /** Component to be rendered. Usually this is a type of input group e.g. `<StringInputGroup/>` */
37
40
  Component: RenderComponent<TForm[TProp], TRenderComponent>;
38
-
41
+ /** Id of the field. */
39
42
  id?: string;
43
+ /** Whether the field should be disabled. */
40
44
  disabled?: boolean;
45
+ /** Client side validation functions */
41
46
  validate?:
42
47
  | ValidationFunction<TForm[TProp]>
43
48
  | ValidationFunction<TForm[TProp]>[];
49
+ /** Function to modify the field value without making the form dirty. (e.g. phone number) */
44
50
  normalize?: NormalizationFunction<TForm[TProp]>;
45
51
  } & Omit<
46
52
  RenderComponentProps<TForm[TProp], TRenderComponent>,
@@ -60,9 +66,9 @@ function Field<
60
66
  name,
61
67
  Component,
62
68
  id,
63
- normalize,
64
- validate,
65
69
  disabled,
70
+ validate,
71
+ normalize,
66
72
  ...rest
67
73
  }: FieldProps<TForm, TProp, TRenderComponent>,
68
74
  ref: LegacyRef<any>
@@ -70,11 +76,17 @@ function Field<
70
76
  const [input, meta] = useStandardFormInput<TForm[TProp]>({
71
77
  name: String(name),
72
78
  id: id,
73
- normalize: normalize,
74
- validate: validate,
75
79
  disabled: disabled,
80
+ validate: validate,
81
+ normalize: normalize,
76
82
  });
77
83
 
84
+ const isRequired =
85
+ rest?.required !== undefined
86
+ ? rest.required
87
+ : validate === requiredValidator ||
88
+ (Array.isArray(validate) && validate.includes(requiredValidator));
89
+
78
90
  // a bit of a hack so JSX is happy with us
79
91
  const Wrapped = Component as React.ComponentType<
80
92
  InjectedFieldProps<TForm[TProp]>
@@ -88,6 +100,7 @@ function Field<
88
100
  id={input.id}
89
101
  input={input}
90
102
  meta={meta}
103
+ required={isRequired}
91
104
  disabled={disabled}
92
105
  />
93
106
  </FieldNameContext.Provider>
@@ -1,6 +1,7 @@
1
1
  import { useContext } from 'react';
2
2
  import { FieldNameContext } from './FieldNameContext';
3
3
 
4
+ /** Hidden `<div/>` that acts as an anchor to scroll to when a form error occurs. */
4
5
  export default function FieldErrorScrollTarget() {
5
6
  const name = useContext(FieldNameContext);
6
7
  if (!name) {
@@ -9,8 +9,11 @@ export type StandAloneInputProps<
9
9
  TValue,
10
10
  TRenderComponent extends ElementType
11
11
  > = {
12
+ /** Component to render inside of the field. */
12
13
  Component: RenderComponent<TValue, TRenderComponent>;
14
+ /** Value of the field. */
13
15
  value: TValue;
16
+ /** Function to change the value of the field. */
14
17
  onChange: (arg: TValue) => void;
15
18
  } & Omit<
16
19
  RenderComponentProps<TValue, TRenderComponent>,
@@ -21,6 +24,7 @@ export type StandAloneInputProps<
21
24
  | 'validate'
22
25
  >;
23
26
 
27
+ /** The stand alone version of `<Field/>`. Can use a type of input component outside of a `<Form/>`. */
24
28
  export default function StandAloneInput<TValue, TComponent extends ElementType>(
25
29
  props: StandAloneInputProps<TValue, TComponent>
26
30
  ) {
@@ -8,14 +8,19 @@ import { NormalizationFunction } from '../Normalization/NormalizationFunction';
8
8
  import { ValidationFunction } from '../Validation/ValidationFunction';
9
9
 
10
10
  export interface useStandardFieldProps<TValue> {
11
+ /** Id of the field. */
11
12
  id?: string;
13
+ /** Name of the field. */
12
14
  name: string;
15
+ /** Whether the field should be disabled. */
13
16
  disabled?: boolean;
17
+ /** Function to validate the field. */
14
18
  validate?: ValidationFunction<TValue> | ValidationFunction<TValue>[];
19
+ /** Function to modify the field value without making the form dirty. (e.g. phone number) */
15
20
  normalize?: NormalizationFunction<TValue>;
16
21
  }
17
22
 
18
- // provides a consistent way to deal with all form fields (non array)
23
+ /** Provides a consistent way to deal with all form fields (non array). */
19
24
  export default function useStandardField<TValue>({
20
25
  id: providedId,
21
26
  name: providedName,
@@ -51,7 +56,7 @@ export default function useStandardField<TValue>({
51
56
  disabled: disabled,
52
57
  validate: callAllValidators,
53
58
  });
54
- const { setFieldValue, isSubmitting } = useFormikContext();
59
+ const { setFieldTouched, setFieldValue, isSubmitting } = useFormikContext();
55
60
 
56
61
  const touched =
57
62
  formikMeta.touched !== false && formikMeta.touched !== undefined;
@@ -59,14 +64,13 @@ export default function useStandardField<TValue>({
59
64
  if (!touched && isSubmitting) {
60
65
  // because we do not always register all fields up front.
61
66
  // e.g. formik expects even a 'create' form to have all fields given, at least, blank values
62
- // that seems to be how it touches on submit:
63
- // see: https://codesandbox.io/s/formik-example-4n7n8 vs https://codesandbox.io/s/formik-example-kttk5
64
- // note in particular the change in line 24
65
- // thus, we manually touch all fields here by calling onBlur
66
- // there is a "setFieldTouched" from useFormikContext but it doesn't appear to work on field arrays
67
- handleBlur();
67
+ // It looks like this was going to be a thing: https://github.com/jaredpalmer/formik/issues/691
68
+ // Formik appears to not have an active maintainer: https://github.com/jaredpalmer/formik/discussions/3526
69
+ // We previously had a different fix in place using handleBlur, but it was causing an infinite update cycle.
70
+ // This was noted as existing, but there was a note about it not working for FieldArray (this does appear to work in my testing with FieldArray)
71
+ setFieldTouched(name);
68
72
  }
69
- });
73
+ }, [isSubmitting, name, setFieldTouched, touched]);
70
74
 
71
75
  // these are the props we expect consumers of this hook to pass directly to the input (or other control)
72
76
  const resultInput: CustomFieldInputProps<TValue> = {
@@ -3,17 +3,21 @@ import classNames from 'classnames';
3
3
  import Field, { FieldProps } from '../Field/Field';
4
4
  import { FieldNameContext } from '../Field/FieldNameContext';
5
5
  import useStandardFormInput from '../Field/useStandardField';
6
- import { ValidationFunction } from '../Validation/ValidationFunction';
7
6
  import { FormDefaults } from '../FormDefaults';
7
+ import { ValidationFunction } from '../Validation/ValidationFunction';
8
8
 
9
9
  export type FieldArrayProps<
10
10
  TForm extends object,
11
11
  TProp extends keyof TForm
12
- > = TForm[TProp] extends Array<any> | undefined
12
+ > = TForm[TProp] extends Array<any> | undefined | null
13
13
  ? {
14
+ /** Name of the field, used on submission. If using codegen this must be the provided dto. */
14
15
  name: TProp;
16
+ /** Label of the field. */
15
17
  label?: string;
18
+ /** Whether the field should be disabled. */
16
19
  disabled?: boolean;
20
+ /** Function to validate the value. */
17
21
  validate?:
18
22
  | ValidationFunction<TForm[TProp]>
19
23
  | ValidationFunction<TForm[TProp]>[];
@@ -23,8 +27,8 @@ export type FieldArrayProps<
23
27
  }
24
28
  : never;
25
29
 
26
- export type ArrayFormBuilderProp<TValue extends Array<any> | undefined> =
27
- TValue extends Array<infer TForm> | undefined
30
+ export type ArrayFormBuilderProp<TValue extends Array<any> | undefined | null> =
31
+ TValue extends Array<infer TForm> | undefined | null
28
32
  ? TForm extends object
29
33
  ? {
30
34
  Field: <
@@ -41,6 +45,11 @@ export type ArrayFormBuilderProp<TValue extends Array<any> | undefined> =
41
45
  : never
42
46
  : never;
43
47
 
48
+ /**
49
+ * An array of fields that allows the user to add multiple instances of the same field.
50
+ *
51
+ * Includes "Add Item" and "Remove Item" buttons to allow the user to speicify the number of fields.
52
+ */
44
53
  export default function FieldArray<
45
54
  TForm extends object,
46
55
  TProp extends keyof TForm
@@ -52,7 +61,7 @@ export default function FieldArray<
52
61
  children,
53
62
  ...rest
54
63
  }: FieldArrayProps<TForm, TProp>) {
55
- const [input, meta] = useStandardFormInput<TForm[TProp]>({
64
+ const [input] = useStandardFormInput<TForm[TProp]>({
56
65
  name: String(name),
57
66
  validate: validate,
58
67
  disabled: disabled,
@@ -2,17 +2,18 @@ import React, { ComponentType, LegacyRef } from 'react';
2
2
  import classNames from 'classnames';
3
3
  import FileList from './FileList';
4
4
  import { InjectedFieldProps } from '../Field/InjectedFieldProps';
5
- import Group, { GroupProps } from '../Group';
6
5
  import { FormDefaults } from '../FormDefaults';
6
+ import Group, { GroupProps } from '../Group';
7
7
 
8
8
  export interface FileGroupProps
9
9
  // note: file props are of type "any" with the current type generation
10
- extends InjectedFieldProps<any | undefined>,
10
+ extends InjectedFieldProps<any | undefined | null>,
11
11
  Omit<GroupProps, keyof InjectedFieldProps<any> | 'children'>,
12
12
  Omit<
13
13
  React.HTMLProps<HTMLInputElement>,
14
14
  keyof InjectedFieldProps<any> | 'children' | 'className' | 'label'
15
15
  > {
16
+ /** Allow multiple files to be uploaded. */
16
17
  multiple?: boolean | undefined;
17
18
  }
18
19
 
@@ -23,6 +24,8 @@ function FileGroup(
23
24
  label,
24
25
  helpText,
25
26
  className,
27
+ required,
28
+ disabled,
26
29
  multiple,
27
30
  ...rest
28
31
  }: FileGroupProps,
@@ -38,7 +41,9 @@ function FileGroup(
38
41
  className,
39
42
  { [FormDefaults.cssClassPrefix + 'multiple']: multiple },
40
43
  FormDefaults.cssClassPrefix + 'file-group'
41
- )}>
44
+ )}
45
+ required={required}
46
+ disabled={disabled}>
42
47
  <input
43
48
  {...input}
44
49
  {...rest}
@@ -72,6 +77,7 @@ function FileGroup(
72
77
  );
73
78
  }
74
79
 
80
+ /** File upload input group. */
75
81
  const FileGroupWithRef = React.forwardRef(
76
82
  FileGroup
77
83
  ) as ComponentType<FileGroupProps>;
@@ -1,8 +1,8 @@
1
1
  import { FormDefaults } from '../FormDefaults';
2
2
 
3
3
  export interface FileListProps {
4
- files?: File | File[] | undefined;
5
- rejectedFiles?: File | File[] | undefined;
4
+ files?: File | File[] | undefined | null;
5
+ rejectedFiles?: File | File[] | undefined | null;
6
6
  }
7
7
  export default function FileList({ files, rejectedFiles }: FileListProps) {
8
8
  return (
@@ -4,8 +4,11 @@ import smoothscroll from 'smoothscroll-polyfill';
4
4
  import { ServerErrorContextProps } from './ServerErrorContext';
5
5
 
6
6
  export interface FocusErrorProps {
7
+ /** Validation errors that have been received from the server. */
7
8
  serverErrors: ServerErrorContextProps;
8
9
  }
10
+
11
+ /** Function to scroll to the field that has an error. */
9
12
  export default function FocusError(props: FocusErrorProps) {
10
13
  const { errors, isSubmitting, isValidating } = useFormikContext();
11
14
  smoothscroll.polyfill();
package/src/Form/Form.tsx CHANGED
@@ -41,18 +41,23 @@ export type FormBuilderProp<TForm extends object> = {
41
41
  };
42
42
 
43
43
  export interface FullFormProps<TForm extends object> {
44
+ /** The `<Field/>` and `<FieldArray/>` components. */
44
45
  children: (formBuilder: FormBuilderProp<TForm>) => JSX.Element;
46
+ /** Submission handler */
45
47
  onSubmit: (
46
48
  formValues: TForm,
47
49
  formikBag: FormikHelpers<TForm>
48
50
  ) => Promise<ValidatedApiResult>;
51
+ /** Submission handler for forms that use [FormData](https://developer.mozilla.org/en-US/docs/Web/API/FormData).*/
49
52
  onFormDataSubmit: (
50
53
  formValues: FormData,
51
54
  formikBag: FormikHelpers<TForm>
52
55
  ) => Promise<ValidatedApiResult>;
53
56
  className?: string;
54
57
  style?: CSSProperties;
58
+ /** Prevent the user from leaving the form if they have edited any field. This is presented as a JS `alert()`. */
55
59
  ignoreLostChanges?: boolean;
60
+ /** The intitial values of the form. */
56
61
  initialValues?: TForm;
57
62
  }
58
63
 
@@ -69,6 +74,7 @@ export type FormProps<TForm extends object> = RequireAtLeastOne<
69
74
  'onSubmit' | 'onFormDataSubmit'
70
75
  >;
71
76
 
77
+ /** Define a form. Uses [formik](https://formik.org/docs/overview). Usually contains many `<Field/>` components. */
72
78
  export default function Form<TForm extends object>({
73
79
  children,
74
80
  className,
@@ -1,16 +1,18 @@
1
- import type { History, Blocker, Transition } from 'history';
2
- import { ContextType, useContext, useEffect } from 'react';
3
- // see: https://gist.github.com/rmorse/426ffcc579922a82749934826fa9f743
1
+ import type { History } from 'history';
2
+ import { ContextType, useContext } from 'react';
4
3
  import {
5
4
  Navigator as BaseNavigator,
6
5
  UNSAFE_NavigationContext as NavigationContext,
7
6
  } from 'react-router-dom';
8
7
  import { useFormikContext } from 'formik';
8
+ import LegacyFormBasedPreventNavigation from './LegacyFormBasedPreventNavigation';
9
+ import NewFormBasedPreventNavigation from './NewFormBasedPreventNavigation';
9
10
 
10
11
  interface Navigator extends BaseNavigator {
11
- block: History['block'];
12
+ block?: History['block'];
13
+ location: Location;
12
14
  }
13
- // see: https://github.com/remix-run/react-router/issues/8139#issuecomment-1023105785
15
+
14
16
  type NavigationContextWithBlock = ContextType<typeof NavigationContext> & {
15
17
  navigator: Navigator;
16
18
  };
@@ -19,6 +21,8 @@ export interface FormBasedPreventNavigationProps {
19
21
  ignoreLostChanges?: boolean;
20
22
  promptMessage?: string;
21
23
  }
24
+
25
+ /** Prevent the user from navigating away from a form if there are any changes. */
22
26
  export default function FormBasedPreventNavigation({
23
27
  ignoreLostChanges,
24
28
  promptMessage = 'Changes you made may not be saved.',
@@ -30,45 +34,23 @@ export default function FormBasedPreventNavigation({
30
34
  NavigationContext
31
35
  ) as NavigationContextWithBlock;
32
36
 
33
- useEffect(() => {
34
- if (!preventNavigate) {
35
- return;
36
- }
37
-
38
- // TODO: https://reactrouter.com/docs/en/v6/upgrading/v5#prompt-is-not-currently-supported
39
- // this is a workaround until we get native support for prompt on navigate
40
-
41
- const blocker: Blocker = (tx) => {
42
- if (window.confirm(promptMessage)) {
43
- tx.retry();
44
- }
45
- };
46
- const unblock = navigator.block((tx: Transition) => {
47
- const autoUnblockingTx = {
48
- ...tx,
49
- retry() {
50
- // Automatically unblock the transition so it can play all the way
51
- // through before retrying it. TODO: Figure out how to re-enable
52
- // this block if the transition is cancelled for some reason.
53
- unblock();
54
- tx.retry();
55
- },
56
- };
57
-
58
- blocker(autoUnblockingTx);
59
- });
60
-
61
- window.addEventListener('beforeunload', beforeUnload);
62
- return () => {
63
- unblock();
64
- window.removeEventListener('beforeunload', beforeUnload);
65
- };
66
-
67
- function beforeUnload(e: BeforeUnloadEvent) {
68
- e.preventDefault();
69
- e.returnValue = promptMessage;
70
- }
71
- }, [preventNavigate, promptMessage, navigator]);
72
-
73
- return null;
37
+ const isUsingDataRouter = navigator.location === undefined;
38
+
39
+ if (isUsingDataRouter) {
40
+ return (
41
+ <NewFormBasedPreventNavigation
42
+ promptMessage={promptMessage}
43
+ preventNavigate={preventNavigate}
44
+ navigator={navigator}
45
+ />
46
+ );
47
+ } else {
48
+ return (
49
+ <LegacyFormBasedPreventNavigation
50
+ promptMessage={promptMessage}
51
+ preventNavigate={preventNavigate}
52
+ navigator={navigator}
53
+ />
54
+ );
55
+ }
74
56
  }
@@ -0,0 +1,77 @@
1
+ import type { History, Blocker, Transition } from 'history';
2
+ import { useEffect } from 'react';
3
+ // see: https://gist.github.com/rmorse/426ffcc579922a82749934826fa9f743
4
+ import { Navigator as BaseNavigator } from 'react-router-dom';
5
+
6
+ interface Navigator extends BaseNavigator {
7
+ block?: History['block'];
8
+ }
9
+
10
+ export interface FormBasedPreventNavigationProps {
11
+ promptMessage?: string;
12
+ preventNavigate: boolean;
13
+ navigator: Navigator;
14
+ }
15
+ /** Only use this if the project uses `<BrowserRouter/>` or any router that does not support the new
16
+ * [react-router Data API](https://reactrouter.com/en/main/routers/picking-a-router#using-v64-data-apis)
17
+ *
18
+ * Legacy function to prevent the user from navigating away from a form if there are any changes.
19
+ */
20
+ export default function LegacyFormBasedPreventNavigation({
21
+ promptMessage = 'Changes you made may not be saved.',
22
+ preventNavigate,
23
+ navigator,
24
+ }: FormBasedPreventNavigationProps) {
25
+ useEffect(() => {
26
+ if (!preventNavigate) {
27
+ return;
28
+ }
29
+ let unblock = () => {};
30
+ const push = navigator.push;
31
+
32
+ // TODO: https://reactrouter.com/docs/en/v6/upgrading/v5#prompt-is-not-currently-supported
33
+ // this is a workaround until we get native support for prompt on navigate
34
+ if (navigator.block) {
35
+ const blocker: Blocker = (tx) => {
36
+ if (window.confirm(promptMessage)) {
37
+ tx.retry();
38
+ }
39
+ };
40
+ unblock = navigator.block((tx: Transition) => {
41
+ const autoUnblockingTx = {
42
+ ...tx,
43
+ retry() {
44
+ // Automatically unblock the transition so it can play all the way
45
+ // through before retrying it. TODO: Figure out how to re-enable
46
+ // this block if the transition is cancelled for some reason.
47
+ unblock();
48
+ tx.retry();
49
+ },
50
+ };
51
+
52
+ blocker(autoUnblockingTx);
53
+ });
54
+ } else {
55
+ //https://gist.github.com/MarksCode/64e438c82b0b2a1161e01c88ca0d0355
56
+ navigator.push = (...args: Parameters<typeof push>) => {
57
+ if (window.confirm(promptMessage)) {
58
+ push(...args);
59
+ }
60
+ };
61
+ }
62
+
63
+ window.addEventListener('beforeunload', beforeUnload);
64
+ return () => {
65
+ unblock();
66
+ navigator.push = push;
67
+ window.removeEventListener('beforeunload', beforeUnload);
68
+ };
69
+
70
+ function beforeUnload(e: BeforeUnloadEvent) {
71
+ e.preventDefault();
72
+ e.returnValue = promptMessage;
73
+ }
74
+ }, [preventNavigate, promptMessage, navigator]);
75
+
76
+ return null;
77
+ }
@@ -0,0 +1,59 @@
1
+ import type { History, Blocker, Transition } from 'history';
2
+ import { useEffect } from 'react';
3
+ import {
4
+ Navigator as BaseNavigator,
5
+ unstable_usePrompt as usePrompt,
6
+ } from 'react-router-dom';
7
+
8
+ interface Navigator extends BaseNavigator {
9
+ block?: History['block'];
10
+ location: Location;
11
+ }
12
+
13
+ interface FormBasedPreventNavigationProps {
14
+ promptMessage?: string;
15
+ preventNavigate: boolean;
16
+ navigator: Navigator;
17
+ }
18
+
19
+ /** Temporary function to allow backwards compatibility with routers that do not use the new Data API */
20
+ export default function NewFormBasedPreventNavigation({
21
+ promptMessage = 'Changes you made may not be saved.',
22
+ preventNavigate,
23
+ navigator,
24
+ }: FormBasedPreventNavigationProps) {
25
+ usePrompt({
26
+ when: preventNavigate,
27
+ message: promptMessage,
28
+ });
29
+
30
+ // TODO: Once react-router fully supports usePrompt and when we do not want to support routers
31
+ // that do not support the react-router Data API we can remove this.
32
+ useEffect(() => {
33
+ if (!preventNavigate) {
34
+ return;
35
+ }
36
+ let unblock = () => {};
37
+ const push = navigator.push;
38
+
39
+ navigator.push = (...args: Parameters<typeof push>) => {
40
+ if (window.confirm(promptMessage)) {
41
+ push(...args);
42
+ }
43
+ };
44
+
45
+ window.addEventListener('beforeunload', beforeUnload);
46
+ return () => {
47
+ unblock();
48
+ navigator.push = push;
49
+ window.removeEventListener('beforeunload', beforeUnload);
50
+ };
51
+
52
+ function beforeUnload(e: BeforeUnloadEvent) {
53
+ e.preventDefault();
54
+ e.returnValue = promptMessage;
55
+ }
56
+ }, [preventNavigate, promptMessage, navigator]);
57
+
58
+ return null;
59
+ }
@@ -8,6 +8,7 @@ export interface ServerErrorContextProps {
8
8
  getError: (path: string) => string | undefined;
9
9
  setError: (path: string, errorMessage: string | undefined) => void;
10
10
  }
11
+ /** Context to store the API errors from the server for the form. */
11
12
  export const ServerErrorContext = React.createContext<ServerErrorContextProps>({
12
13
  errors: {},
13
14
  getError: (path: string) => {
@@ -3,10 +3,17 @@ import { useFormikContext } from 'formik';
3
3
  import SubmitFormButton from './SubmitFormButton';
4
4
 
5
5
  export interface FormActionsProps {
6
+ /** Allow the form to be submitted without any changes. By default this is not allowed. */
6
7
  allowPristineSubmit?: boolean;
8
+ /** The cancel button's `onClick`.
9
+ * @defaultValue `window.history.back()`
10
+ */
7
11
  handleCancel?: () => void;
12
+ /** Whether both buttons should be disabled. */
8
13
  disabled?: boolean;
9
14
  }
15
+
16
+ /** Standard cancel and submit buttons. */
10
17
  export default function FormActions({
11
18
  allowPristineSubmit,
12
19
  handleCancel,
@@ -1 +1,2 @@
1
+ /** `envoc-form-` CSS class prefix */
1
2
  export const FormDefaults = { cssClassPrefix: 'envoc-form-' };
package/src/Group.tsx CHANGED
@@ -4,20 +4,24 @@ import FieldErrorScrollTarget from './Field/FieldErrorScrollTarget';
4
4
  import { InjectedFieldProps } from './Field/InjectedFieldProps';
5
5
 
6
6
  export interface GroupProps extends InjectedFieldProps<any> {
7
+ /** Extra class names to apply. */
7
8
  className?: string;
8
9
 
9
10
  children: React.ReactNode;
10
11
 
11
- /** simple text label before the input */
12
+ /** Simple text label before the input. */
12
13
  label?: string;
13
14
 
14
- /** simple helper text after the input*/
15
+ /** Simple helper text after the input. */
15
16
  helpText?: string | React.ReactNode;
16
17
 
18
+ /** Whether the field should be disabled. */
17
19
  disabled?: boolean;
20
+
21
+ required?: boolean;
18
22
  }
19
23
 
20
- /** contains standard field bits like a label, helper text, error scroll target, validation message container, etc */
24
+ /** Contains standard field bits like a label, helper text, error scroll target, validation message container, etc. */
21
25
  export default function Group({
22
26
  className,
23
27
  children,
@@ -26,12 +30,14 @@ export default function Group({
26
30
  meta,
27
31
  input,
28
32
  disabled,
33
+ required,
29
34
  }: GroupProps) {
30
35
  return (
31
36
  <div
32
37
  className={classNames(className, FormDefaults.cssClassPrefix + 'group', {
33
38
  [FormDefaults.cssClassPrefix + 'invalid']: meta.error,
34
39
  [FormDefaults.cssClassPrefix + 'disabled']: disabled,
40
+ [FormDefaults.cssClassPrefix + 'required']: required,
35
41
  })}>
36
42
  <FieldErrorScrollTarget />
37
43
  {meta.warning && (
@@ -42,7 +48,9 @@ export default function Group({
42
48
  <label htmlFor={input.id}>{label}</label>
43
49
  {children}
44
50
  {meta.error && (
45
- <div className={FormDefaults.cssClassPrefix + 'error'}>
51
+ <div
52
+ id={`${input.id}-error`}
53
+ className={FormDefaults.cssClassPrefix + 'error'}>
46
54
  {meta.error}
47
55
  </div>
48
56
  )}