1import { useCallback, useMemo } from 'react';
2import { keyBy, get, every, some } from 'lodash';
4import { compose } from 'lib/lib';
5import { kDefaultValidator } from 'lib/validators';
6import useSetState from 'lib/useSetState';
7import useDeepEqualReference from 'lib/useDeepEqualReference';
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 const configs = useDeepEqualReference(inputConfigs);
31 const byName = useMemo(() => keyBy(configs, 'name'), [configs]);
34 const [values, _setValues, clearValues] = useSetState(() =>
35 defaultsFor(configs, config =>
36 config.initialValue === undefined ? '' : config.initialValue
39 // ^ NB(shrugs): because we're not syncing the initialValue of _additional_
40 // configs that are added, we won't be able to set an initialValue for a
41 // dynamic form that then triggers validation. for initial configs,
42 // initialValue can be a validated string and everything will be happy,
43 // but for dynamically added input configs, we won't get validation, etc
44 // until there's a traditional state update.
46 // track focused states
47 const [focused, setFocused, clearFocused] = useSetState(() =>
48 defaultsFor(configs, config => config.autoFocus && !config.disabled)
50 const focuses = useMemo(
51 () => configs.map(config => focused[config.name] || false), //
55 // track whether or not input has been focused
56 const [hasBeenFocused, setHasBeenFocused, clearHasBeenFocused] = useSetState(
60 // track whether or not the input has been touched
61 const [hasBeenTouched, setHasBeenTouched, clearHasBeenTouched] = useSetState(
65 // build fn that transforms a value by input name
66 const transform = useCallback(
67 (name, value) => compose(...get(byName, [name, 'transformers'], []))(value),
71 // set a value (and transform it)
72 const setValue = useCallback(
73 (name, value) => _setValues({ [name]: transform(name, value) }),
74 [_setValues, transform]
78 const reset = useCallback(() => {
80 clearHasBeenFocused();
81 clearHasBeenTouched();
83 }, [clearFocused, clearHasBeenFocused, clearHasBeenTouched, clearValues]);
85 // build fn that validates a value by input name
86 const validate = useCallback(
89 ...get(byName, [name, 'validators'], []),
95 const getValue = useCallback(
97 if (byName[name].type === 'checkbox') {
98 return e.target.checked;
101 return e.target.value;
106 // on change, transform and set value
107 const onChange = useCallback(
109 setValue(name, getValue(name, e));
110 setHasBeenTouched({ [name]: true });
112 [setValue, getValue, setHasBeenTouched]
115 // on focus, update focus
116 const onFocus = useCallback(
117 name => e => setFocused({ [name]: true }), //
121 // on blur, defocus and set has been focused
122 const onBlur = useCallback(
124 setFocused({ [name]: false });
125 setHasBeenFocused({ [name]: true });
127 [setFocused, setHasBeenFocused]
130 // memo-compute validations of curent values
131 const validations = useMemo(
132 () => configs.map(config => validate(config.name, values[config.name])), //
133 [configs, validate, values]
136 // memo-compute the set of (perhaps changed by validation) data
137 const datas = useMemo(() => validations.map(v => v.data), [validations]);
138 const syncPasses = useMemo(
139 () => validations.map(v => v.pass, [validations]),
143 // the input has errored if it
144 // 1) did not pass validation and has an error text
145 // 2) or has a specific error from parent state
146 // and then we store that in errorTexts[i]
147 // <string | falsy>[]
148 const errorTexts = useMemo(
150 configs.map((config, i) => validations[i].error || config.error || false),
151 [configs, validations]
154 // we should hint at an error if it
155 // 1) has been focused before
156 // 2) and has an error
158 const hintErrors = useMemo(
161 (config, i) => hasBeenFocused[config.name] && !!errorTexts[i]
163 [configs, errorTexts, hasBeenFocused]
166 // we should block on error (with potential reflow) if it
167 // 1) has been touched
168 // 2) and has an error
169 // consumers should use this value to show error text and block on operations
170 // <string | falsy>[]
171 const errors = useMemo(
173 configs.map((config, i) => hasBeenTouched[config.name] && errorTexts[i]),
174 [configs, errorTexts, hasBeenTouched]
177 // this input has passed if
178 // 1) it has passed local validation
179 // 2) there are no errors
180 const passes = useMemo(
181 () => validations.map((v, i) => v.pass && !errorTexts[i]),
182 [validations, errorTexts]
185 // visibly tell the user that their input has passed if
186 // 1) they are or have interacted with the input before
187 // 2) and it has passed as defined above
188 const visiblePasses = useMemo(
192 (focused[config.name] || hasBeenFocused[config.name]) && //
195 [configs, hasBeenFocused, focused, passes]
198 // generate the list of input states
199 const inputs = useMemo(
202 ({ name, error, autoFocus, disabled, initialValue, ...rest }, i) => {
204 datas[i] !== undefined
206 : initialValue !== undefined
213 data: passes[i] ? datas[i] : undefined,
215 syncPass: syncPasses[i],
216 visiblyPassed: visiblePasses[i],
218 hintError: hintErrors[i],
220 touched: hasBeenTouched[name],
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,
252 // did all of the inputs pass validation?
253 const pass = useMemo(() => every(passes), [passes]);
254 // did any of the inputs error?
255 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