on a850d7f help sign in
262 lines 7.5 kB history raw
1import { useCallback, useMemo } from 'react';
2import { isEqual, keyBy, get, every, some } from 'lodash';
4import { compose } from 'lib/lib';
5import { kDefaultValidator } from 'lib/validators';
6import useSetState from 'lib/useSetState';
7import usePreviousValue from 'lib/usePreviousValue';
9// interface InputConfig {
10// name: string;
11// validators: Function[];
12// transformers: Function[];
13// initialValue: string;
14// autoFocus: boolean;
15// disabled: boolean;
16// ...extra,
17// }
19const defaultsFor = (configs, mapper) =>
20 configs.reduce(
21 (memo, config) => ({ ...memo, [config.name]: mapper(config) }),
22 {}
23 );
25/**
26 * useForm manages a set of inputs for rendering them in a loop
27 */
28export default function useForm(inputConfigs = []) {
29 // track the old value of the config set
30 const previousConfigs = usePreviousValue(inputConfigs);
31 // then compare equality
32 const configsAreEqual = isEqual(inputConfigs, previousConfigs);
33 // if equality changes, give `configs` a new identity
34 // eslint-disable-next-line react-hooks/exhaustive-deps
35 const configs = useMemo(() => inputConfigs, [configsAreEqual]);
37 const byName = useMemo(() => keyBy(configs, 'name'), [configs]);
39 // track values
40 const [values, _setValues, clearValues] = useSetState(() =>
41 defaultsFor(configs, config =>
42 config.initialValue === undefined ? '' : config.initialValue
43 )
44 );
45 // ^ NB(shrugs): because we're not syncing the initialValue of _additional_
46 // configs that are added, we won't be able to set an initialValue for a
47 // dynamic form that then triggers validation. for initial configs,
48 // initialValue can be a validated string and everything will be happy,
49 // but for dynamically added input configs, we won't get validation, etc
50 // until there's a traditional state update.
52 // track focused states
53 const [focused, setFocused, clearFocused] = useSetState(() =>
54 defaultsFor(configs, config => config.autoFocus && !config.disabled)
55 );
56 const focuses = useMemo(
57 () => configs.map(config => focused[config.name] || false), //
58 [configs, focused]
59 );
61 // track whether or not input has been focused
62 const [hasBeenFocused, setHasBeenFocused, clearHasBeenFocused] = useSetState(
63 {}
64 );
66 // track whether or not the input has been touched
67 const [hasBeenTouched, setHasBeenTouched, clearHasBeenTouched] = useSetState(
68 {}
69 );
71 // build fn that transforms a value by input name
72 const transform = useCallback(
73 (name, value) => compose(...get(byName, [name, 'transformers'], []))(value),
74 [byName]
75 );
77 // set a value (and transform it)
78 const setValue = useCallback(
79 (name, value) => _setValues({ [name]: transform(name, value) }),
80 [_setValues, transform]
81 );
83 // reset the form
84 const reset = useCallback(() => {
85 clearFocused();
86 clearHasBeenFocused();
87 clearHasBeenTouched();
88 clearValues();
89 }, [clearFocused, clearHasBeenFocused, clearHasBeenTouched, clearValues]);
91 // build fn that validates a value by input name
92 const validate = useCallback(
93 (name, value) =>
94 compose(
95 ...get(byName, [name, 'validators'], []),
96 kDefaultValidator
97 )(value),
98 [byName]
99 );
101 const getValue = useCallback(
102 (name, e) => {
103 if (byName[name].type === 'checkbox') {
104 return e.target.checked;
105 }
107 return e.target.value;
108 },
109 [byName]
110 );
112 // on change, transform and set value
113 const onChange = useCallback(
114 name => e => {
115 setValue(name, getValue(name, e));
116 setHasBeenTouched({ [name]: true });
117 }, //
118 [setValue, getValue, setHasBeenTouched]
119 );
121 // on focus, update focus
122 const onFocus = useCallback(
123 name => e => setFocused({ [name]: true }), //
124 [setFocused]
125 );
127 // on blur, defocus and set has been focused
128 const onBlur = useCallback(
129 name => e => {
130 setFocused({ [name]: false });
131 setHasBeenFocused({ [name]: true });
132 },
133 [setFocused, setHasBeenFocused]
134 );
136 // memo-compute validations of curent values
137 const validations = useMemo(
138 () => configs.map(config => validate(config.name, values[config.name])), //
139 [configs, validate, values]
140 );
142 // memo-compute the set of (perhaps changed by validation) data
143 const datas = useMemo(() => validations.map(v => v.data), [validations]);
145 // the input has errored if it
146 // 1) did not pass validation and has an error text
147 // 2) or has a specific error from parent state
148 // and then we store that in errorTexts[i]
149 // <string | falsy>[]
150 const errorTexts = useMemo(
151 () =>
152 configs.map((config, i) => validations[i].error || config.error || false),
153 [configs, validations]
154 );
156 // we should hint at an error if it
157 // 1) has been focused before
158 // 2) and has an error
159 // boolean[]
160 const hintErrors = useMemo(
161 () =>
162 configs.map(
163 (config, i) => hasBeenFocused[config.name] && !!errorTexts[i]
164 ),
165 [configs, errorTexts, hasBeenFocused]
166 );
168 // we should block on error (with potential reflow) if it
169 // 1) has been touched
170 // 2) and has an error
171 // consumers should use this value to show error text and block on operations
172 // <string | falsy>[]
173 const errors = useMemo(
174 () =>
175 configs.map((config, i) => hasBeenTouched[config.name] && errorTexts[i]),
176 [configs, errorTexts, hasBeenTouched]
177 );
179 // this input has passed if
180 // 1) it has passed local validation
181 // 2) there are no errors
182 const passes = useMemo(
183 () => validations.map((v, i) => v.pass && !errorTexts[i]),
184 [validations, errorTexts]
185 );
187 // visibly tell the user that their input has passed if
188 // 1) they are or have interacted with the input before
189 // 2) and it has passed as defined above
190 const visiblePasses = useMemo(
191 () =>
192 configs.map(
193 (config, i) =>
194 (focused[config.name] || hasBeenFocused[config.name]) && //
195 passes[i]
196 ),
197 [configs, hasBeenFocused, focused, passes]
198 );
200 // generate the list of input states
201 const inputs = useMemo(
202 () =>
203 configs.map(
204 ({ name, error, autoFocus, disabled, initialValue, ...rest }, i) => {
205 const value =
206 datas[i] !== undefined
207 ? datas[i]
208 : initialValue !== undefined
209 ? initialValue
210 : '';
211 return {
212 // Input props
213 name,
214 value: value,
215 data: passes[i] ? datas[i] : undefined,
216 pass: passes[i],
217 visiblyPassed: visiblePasses[i],
218 error: errors[i],
219 hintError: hintErrors[i],
220 focused: focuses[i],
221 autoFocus: autoFocus && !disabled,
222 disabled,
223 ...rest,
224 // DOM Properties for <input />
225 bind: {
226 value,
227 checked: !!datas[i],
228 onChange: onChange(name),
229 onFocus: onFocus(name),
230 onBlur: onBlur(name),
231 autoFocus: autoFocus && !disabled,
232 },
233 };
234 }
235 ),
236 [
237 configs,
238 datas,
239 passes,
240 visiblePasses,
241 errors,
242 hintErrors,
243 focuses,
244 onChange,
245 onFocus,
246 onBlur,
247 ]
248 );
250 // did all of the inputs pass validation?
251 const pass = useMemo(() => every(passes), [passes]);
252 // did any of the inputs error?
253 const error = useMemo(() => some(errors), [errors]);
255 return {
256 inputs,
257 pass,
258 error,
259 setValue,
260 reset,
261 };