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 {
11// validators: Function[];
12// transformers: Function[];
13// initialValue: string;
19const defaultsFor = (configs, mapper) =>
21 (memo, config) => ({ ...memo, [config.name]: mapper(config) }),
26 * useForm manages a set of inputs for rendering them in a loop
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]);
40 const [values, _setValues, clearValues] = useSetState(() =>
41 defaultsFor(configs, config =>
42 config.initialValue === undefined ? '' : config.initialValue
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)
56 const focuses = useMemo(
57 () => configs.map(config => focused[config.name] || false), //
61 // track whether or not input has been focused
62 const [hasBeenFocused, setHasBeenFocused, clearHasBeenFocused] = useSetState(
66 // track whether or not the input has been touched
67 const [hasBeenTouched, setHasBeenTouched, clearHasBeenTouched] = useSetState(
71 // build fn that transforms a value by input name
72 const transform = useCallback(
73 (name, value) => compose(...get(byName, [name, 'transformers'], []))(value),
77 // set a value (and transform it)
78 const setValue = useCallback(
79 (name, value) => _setValues({ [name]: transform(name, value) }),
80 [_setValues, transform]
84 const reset = useCallback(() => {
86 clearHasBeenFocused();
87 clearHasBeenTouched();
89 }, [clearFocused, clearHasBeenFocused, clearHasBeenTouched, clearValues]);
91 // build fn that validates a value by input name
92 const validate = useCallback(
95 ...get(byName, [name, 'validators'], []),
101 const getValue = useCallback(
103 if (byName[name].type === 'checkbox') {
104 return e.target.checked;
107 return e.target.value;
112 // on change, transform and set value
113 const onChange = useCallback(
115 setValue(name, getValue(name, e));
116 setHasBeenTouched({ [name]: true });
118 [setValue, getValue, setHasBeenTouched]
121 // on focus, update focus
122 const onFocus = useCallback(
123 name => e => setFocused({ [name]: true }), //
127 // on blur, defocus and set has been focused
128 const onBlur = useCallback(
130 setFocused({ [name]: false });
131 setHasBeenFocused({ [name]: true });
133 [setFocused, setHasBeenFocused]
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]
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(
152 configs.map((config, i) => validations[i].error || config.error || false),
153 [configs, validations]
156 // we should hint at an error if it
157 // 1) has been focused before
158 // 2) and has an error
160 const hintErrors = useMemo(
163 (config, i) => hasBeenFocused[config.name] && !!errorTexts[i]
165 [configs, errorTexts, hasBeenFocused]
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(
175 configs.map((config, i) => hasBeenTouched[config.name] && errorTexts[i]),
176 [configs, errorTexts, hasBeenTouched]
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]
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(
194 (focused[config.name] || hasBeenFocused[config.name]) && //
197 [configs, hasBeenFocused, focused, passes]
200 // generate the list of input states
201 const inputs = useMemo(
204 ({ name, error, autoFocus, disabled, initialValue, ...rest }, i) => {
206 datas[i] !== undefined
208 : initialValue !== undefined
215 data: passes[i] ? datas[i] : undefined,
217 visiblyPassed: visiblePasses[i],
219 hintError: hintErrors[i],
221 autoFocus: autoFocus && !disabled,
224 // DOM Properties for <input />
228 onChange: onChange(name),
229 onFocus: onFocus(name),
230 onBlur: onBlur(name),
231 autoFocus: autoFocus && !disabled,
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]);
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list