1import { useCallback, useMemo, useState } from 'react';
2import { keyBy, get, every, some } from 'lodash';
4import { compose } from 'lib/lib';
5import { kDefaultValidator } from 'lib/validators';
6import useSetState from 'lib/useSetState';
8// interface InputConfig {
10// validators: Function[];
11// transformers: Function[];
12// initialValue: string;
18const defaultsFor = (configs, mapper) =>
20 (memo, config) => ({ ...memo, [config.name]: mapper(config) }),
25 * useForm manages a set of inputs for rendering them in a loop
27export default function useForm(configs = []) {
28 const byName = useMemo(() => keyBy(configs, 'name'), [configs]);
31 const [values, _setValues] = useState(() =>
32 defaultsFor(configs, config => config.initialValue || '')
34 // ^ NB(shrugs): because we're not syncing the initialValue of _additional_
35 // configs that are added, we won't be able to set an initialValue for a
36 // dynamic form that then triggers validation. for initial configs,
37 // initialValue can be a validated string and everything will be happy,
38 // but for dynamically added input configs, we won't get validation, etc
39 // until there's a traditional state update.
41 const setValue = useCallback(
42 (name, value) => _setValues(values => ({ ...values, [name]: value })),
46 // track focused states
47 const [focused, setFocused] = 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] = useSetState({});
58 // build fn that transforms a value by input name
59 const transform = useCallback(
60 (name, value) => compose(...get(byName, [name, 'transformers'], []))(value),
64 // build fn that validates a value by input name
65 const validate = useCallback(
68 ...get(byName, [name, 'validators'], []),
74 const getValue = useCallback(
76 if (byName[name].type === 'checkbox') {
77 return e.target.checked;
80 return e.target.value;
85 // on change, transform and set value
86 const onChange = useCallback(
87 name => e => setValue(name, transform(name, getValue(name, e))), //
88 [setValue, transform, getValue]
91 // on focus, update focus
92 const onFocus = useCallback(
93 name => e => setFocused({ [name]: true }), //
97 // on blur, defocus and set has been focused
98 const onBlur = useCallback(
100 setFocused({ [name]: false });
101 setHasBeenFocused({ [name]: true });
103 [setFocused, setHasBeenFocused]
106 // memo-compute validations of curent values
107 const validations = useMemo(
108 () => configs.map(config => validate(config.name, values[config.name])), //
109 [configs, validate, values]
112 // memo-compute the set of (perhaps changed by validation) data
113 const datas = useMemo(() => validations.map(v => v.data), [validations]);
115 // the input has errored if it
116 // 1) has been focused before
118 // a) did not pass validation and has an error text
119 // b) or has a specific error from parent state
120 // (and we implicitly return the error text at the end)
121 const errors = useMemo(
125 hasBeenFocused[config.name] && //
126 (validations[i].error || config.error)
128 [configs, validations, hasBeenFocused]
131 // this input has passed if
132 // 1) it has passed local validation
133 // 2) there are no errors
134 const passes = useMemo(
135 () => validations.map((v, i) => v.pass && !errors[i]),
136 [validations, errors]
139 // visibly tell the user that their input has passed if
140 // 1) they are or have interacted with the input before
141 // 2) and it has passed as defined above
142 const visiblePasses = useMemo(
146 (focused[config.name] || hasBeenFocused[config.name]) && //
149 [configs, hasBeenFocused, focused, passes]
152 // generate the list of input states
153 const inputs = useMemo(
156 ({ name, error, autoFocus, disabled, initialValue, ...rest }, i) => ({
161 visiblyPassed: visiblePasses[i],
164 autoFocus: autoFocus && !disabled,
167 // dom properties below:
169 value: values[name] || initialValue || '',
170 checked: !!values[name],
171 onChange: onChange(name),
172 onFocus: onFocus(name),
173 onBlur: onBlur(name),
174 autoFocus: autoFocus && !disabled,
192 // did all of the inputs pass validation?
193 const pass = useMemo(() => every(passes), [passes]);
194 // did any of the inputs error?
195 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