on 2de2112 help sign in
200 lines 5.5 kB history raw
1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
4import Grid from 'components/Grid';
6import { compose } from 'lib/lib';
7import { kDefaultValidator } from 'lib/validators';
9function useInput({
10 validators = [],
11 transformers = [],
12 initialValue = '',
13 autoFocus = false,
14}) {
15 const [value, setValue] = useState(initialValue);
16 const [focused, setFocused] = useState(autoFocus);
17 const [hasBeenFocused, setHasBeenFocused] = useState(false);
19 // NB(shrugs)
20 // TL;DR: This is what we want, the exhaustive deps rule is being too nosy.
21 //
22 // Here we memo-construct the `validate` and `transform` functions
23 // based on the prop arguments. We explicitly disable the exhausive deps rule
24 // because eslint wants an inline array specifying our dependencies.
25 //
26 // If we were to place the array of validators or transformers into
27 // the dependency array like `[validators]`, we would end up creating a new
28 // `validate` function every render, since deps are shallow-compared with
29 // `Object.is`. Because the array of validators are constructed as part of
30 // a component's render() function like:
31 //
32 // export function MnemonicInput(props) {
33 // return (
34 // <Input
35 // type="text"
36 // autoComplete="off"
37 // placeholder={`e.g. ${kExampleMnemonic}`}
38 // validators={[validateMnemonic, validateNotEmpty]}
39 // {...props}
40 // />
41 // );
42 // }
43 //
44 // we create a new array, which shallowly compares as not-equal
45 // between renders.
46 //
47 // So, in this specific case, we disable the rule and pass the
48 // array of validators (and transformers) themselves as dependencies.
49 // This means that validators and transformers can change between renders
50 // and we will re-create the composed `validate` and `transform` functions
51 // as expected.
52 //
53 // For context, an alternative solution I tried was defining the array of
54 // validators as a constant array outside of the render method, but:
55 // 1. It wasn't as clean or useful as specifying them inline,
56 // 2. It would mean that validators could not be updated between renders,
57 // 3. And the situation we have now feels naturally more 'correct'.
58 //
59 /* eslint-disable react-hooks/exhaustive-deps */
60 const transform = useMemo(() => compose(...transformers), transformers);
61 const validate = useMemo(
62 () =>
63 compose(
64 ...validators,
65 kDefaultValidator
66 ),
67 validators
68 );
69 /* eslint-enable react-hooks/exhaustive-deps */
71 const onChange = useCallback(
72 e => setValue(transform(e.target.value)), //
73 [transform]
74 );
75 const onFocus = useCallback(
76 e => setFocused(true), //
77 [setFocused]
78 );
79 const onBlur = useCallback(
80 e => {
81 setFocused(false);
82 setHasBeenFocused(true);
83 },
84 [setFocused, setHasBeenFocused]
85 );
87 // memo-compute whether or not the current value is valid
88 const { pass, error: _error, data } = useMemo(
89 () => validate(value), //
90 [validate, value]
91 );
93 // only set error if it should be visible
94 const error = !pass && hasBeenFocused && !focused && _error;
95 // visibly tell the user that their input has passed if it has passed
96 // and they are or have interacted with the input before
97 const visiblyPassed = pass && (hasBeenFocused || focused);
99 return {
100 pass,
101 visiblyPassed,
102 error,
103 data,
104 focused,
105 bind: {
106 value,
107 onChange,
108 focused: focused ? 'true' : 'false',
109 // ^ dom wants string value for focused
110 onFocus,
111 onBlur,
112 },
113 };
116export default function Input({
117 name,
118 label,
119 initialValue = '',
120 className = '',
121 validators = [],
122 transformers = [],
123 onValue,
124 onPass,
125 onError,
126 onFocus,
127 disabled = false,
128 mono = false,
129 autoFocus = false,
130 ...rest
131}) {
132 const actuallyAutoFocus = autoFocus && !disabled;
133 const { focused, pass, visiblyPassed, error, data, bind } = useInput({
134 validators,
135 transformers,
136 initialValue,
137 autoFocus: actuallyAutoFocus,
138 });
140 // notify parent of value only when passing
141 useEffect(() => {
142 pass && onValue && onValue(data);
143 }, [pass, data, onValue]);
145 // notify parent of pass
146 useEffect(() => {
147 onPass && onPass(pass);
148 }, [pass, onPass]);
150 // notify parent of error whenever error changes
151 useEffect(() => {
152 onError && onError(error);
153 }, [error, onError]);
155 // notify parent of focus
156 useEffect(() => {
157 onFocus && onFocus(focused);
158 }, [focused, onFocus]);
160 return (
161 <Grid>
162 <Grid.Item full>
163 <label className="f6 lh-tall" htmlFor={name}>
164 {label}
165 </label>
166 </Grid.Item>
167 <Grid.Item full>
168 <input
169 {...rest}
170 className={cn(
171 'b b1 p3',
172 { mono },
173 {
174 'bg-white': !disabled,
175 'bg-gray1': disabled,
176 },
177 {
178 gray4: !focused,
179 black: focused,
180 },
181 {
182 'b-green3': visiblyPassed,
183 'b-black': focused && !visiblyPassed,
184 'b-yellow3': !focused && !visiblyPassed && error,
185 'b-gray3': !focused && !error && !visiblyPassed,
186 },
187 className
188 )}
189 style={{
190 ...(disabled && { pointerEvents: 'none', cursor: 'not-allowed' }),
191 }}
192 id={name}
193 name={name}
194 autoFocus={actuallyAutoFocus}
195 {...bind}
196 />
197 </Grid.Item>
198 </Grid>
199 );