on f1ff0cf help sign in
186 lines 5.1 kB history raw
1import { useCallback, useMemo, useState } from 'react';
2import { keyBy, get, every, some } from 'lodash';
4import { compose } from 'lib/lib';
5import { kDefaultValidator } from 'lib/validators';
7// interface InputConfig {
8// name: string;
9// validators: Function[];
10// transformers: Function[];
11// initialValue: string;
12// autoFocus: boolean;
13// disabled: boolean;
14// ...extra,
15// }
17const defaultsFor = (configs, mapper) =>
18 configs.reduce(
19 (memo, config) => ({ ...memo, [config.name]: mapper(config) }),
20 {}
21 );
23/**
24 * useForm managest a set of inputs for rendering them in a loop
25 */
26export default function useForm(configs = []) {
27 const byName = useMemo(() => keyBy(configs, 'name'), [configs]);
29 // track values
30 const [values, _setValues] = useState(() =>
31 defaultsFor(configs, config => config.initialValue)
32 );
33 const setValue = useCallback(
34 (name, value) => _setValues(values => ({ ...values, [name]: value })),
35 [_setValues]
36 );
37 // ^ NB(shrugs): because we're not syncing the initialValue of _additional_
38 // configs that are added, we won't be able to set an initialValue for a
39 // dynamic form that then triggers validation. for initial configs,
40 // initialValue can be a validated string and everything will be happy,
41 // but for dynamically added input configs, we won't get validation, etc
42 // until there's a traditional state update.
44 // track focused states
45 const [focused, _setFocused] = useState(() =>
46 defaultsFor(configs, config => config.autoFocus && !config.disabled)
47 );
48 const focuses = useMemo(
49 () => configs.map(config => focused[config.name] || false), //
50 [configs, focused]
51 );
53 const setFocused = useCallback(
54 (name, value) => _setFocused(values => ({ ...values, [name]: value })),
55 [_setFocused]
56 );
58 // track whether or not input has been focused
59 const [hasBeenFocused, _setHasBeenFocused] = useState({});
60 const setHasBeenFocused = useCallback(
61 (name, value) =>
62 _setHasBeenFocused(values => ({ ...values, [name]: value })),
63 [_setHasBeenFocused]
64 );
66 const transform = useCallback(
67 (name, value) => compose(...get(byName, [name, 'transformers'], []))(value),
68 [byName]
69 );
70 const validate = useCallback(
71 (name, value) =>
72 compose(
73 ...get(byName, [name, 'validators'], []),
74 kDefaultValidator
75 )(value),
76 [byName]
77 );
79 const onChange = useCallback(
80 name => e => setValue(name, transform(name, e.target.value)), //
81 [setValue, transform]
82 );
83 const onFocus = useCallback(
84 name => e => setFocused(name, true), //
85 [setFocused]
86 );
87 const onBlur = useCallback(
88 name => e => {
89 setFocused(name, false);
90 setHasBeenFocused(name, true);
91 },
92 [setFocused, setHasBeenFocused]
93 );
95 // memo-compute whether or not the current value is valid
96 const validations = useMemo(
97 () => configs.map(config => validate(config.name, values[config.name])), //
98 [configs, validate, values]
99 );
101 const datas = useMemo(() => validations.map(v => v.data), [validations]);
103 // the input has errored if it
104 // 1) has been focused before
105 // 2)
106 // a) did not pass validation and has an error text
107 // b) or has a specific error from parent state
108 // (and we implicitly return the error text at the end)
109 const errors = useMemo(
110 () =>
111 configs.map(
112 (config, i) =>
113 hasBeenFocused[config.name] && //
114 (validations[i].error || config.error)
115 ),
116 [configs, validations, hasBeenFocused]
117 );
119 // this input has passed if
120 // 1) it has passed local validation
121 // 2) there are no errors
122 const passes = useMemo(
123 () => validations.map((v, i) => v.pass && !errors[i]),
124 [validations, errors]
125 );
127 // visibly tell the user that their input has passed if
128 // 1) they are or have interacted with the input before
129 // 2) and it has passed as defined above
130 const visiblePasses = useMemo(
131 () =>
132 configs.map(
133 (config, i) =>
134 (focused[config.name] || hasBeenFocused[config.name]) && //
135 passes[i]
136 ),
137 [configs, hasBeenFocused, focused, passes]
138 );
140 const inputs = useMemo(
141 () =>
142 configs.map(
143 ({ name, error, autoFocus, disabled, initialValue, ...rest }, i) => ({
144 // Input props
145 name,
146 data: datas[i],
147 pass: passes[i],
148 visiblyPassed: visiblePasses[i],
149 error: errors[i],
150 focused: focuses[i],
151 autoFocus: autoFocus && !disabled,
152 disabled,
153 ...rest,
154 // dom properties below:
155 bind: {
156 value: values[name] || initialValue,
157 onChange: onChange(name),
158 onFocus: onFocus(name),
159 onBlur: onBlur(name),
160 autoFocus: autoFocus && !disabled,
161 },
162 })
163 ),
164 [
165 configs,
166 datas,
167 visiblePasses,
168 passes,
169 errors,
170 focuses,
171 values,
172 onBlur,
173 onChange,
174 onFocus,
175 ]
176 );
178 const pass = every(passes);
179 const error = some(errors);
181 return {
182 inputs,
183 pass,
184 error,
185 };