on 14e3c13 help sign in
214 lines 6.0 kB history raw
1import React, { useCallback, useEffect, useMemo, useState } from 'react';
2import cn from 'classnames';
4import { Flex } from 'indigo-react';
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 onEnter,
128 accessory,
129 disabled = false,
130 mono = false,
131 autoFocus = false,
132 ...rest
133}) {
134 const actuallyAutoFocus = autoFocus && !disabled;
135 const { focused, pass, visiblyPassed, error, data, bind } = useInput({
136 validators,
137 transformers,
138 initialValue,
139 autoFocus: actuallyAutoFocus,
140 });
142 // notify parent of enter keypress iff not disabled
143 const onKeyPress = useCallback(
144 e => !disabled && e.key === 'Enter' && onEnter && onEnter(),
145 [disabled, onEnter]
146 );
148 // notify parent of value only when passing
149 useEffect(() => {
150 pass && onValue && onValue(data);
151 }, [pass, data, onValue]);
153 // notify parent of pass
154 useEffect(() => {
155 onPass && onPass(pass);
156 }, [pass, onPass]);
158 // notify parent of error whenever error changes
159 useEffect(() => {
160 onError && onError(error);
161 }, [error, onError]);
163 // notify parent of focus
164 useEffect(() => {
165 onFocus && onFocus(focused);
166 }, [focused, onFocus]);
168 return (
169 <Flex col>
170 <Flex.Item as="label" className="f6 lh-tall" htmlFor={name}>
171 {label}
172 </Flex.Item>
173 <Flex row>
174 <Flex.Item
175 as="input"
176 {...rest}
177 cols={[1, accessory ? 11 : 13]}
178 className={cn(
179 'b b1 p3',
180 { mono },
181 {
182 'bg-white': !disabled,
183 'bg-gray1': disabled,
184 },
185 {
186 gray4: !focused,
187 black: focused,
188 },
189 {
190 'b-green3': visiblyPassed,
191 'b-black': focused && !visiblyPassed,
192 'b-yellow3': !focused && !visiblyPassed && error,
193 'b-gray3': !focused && !error && !visiblyPassed,
194 },
195 className
196 )}
197 style={{
198 ...(disabled && { pointerEvents: 'none', cursor: 'not-allowed' }),
199 }}
200 onKeyPress={onKeyPress}
201 id={name}
202 autoFocus={actuallyAutoFocus}
203 {...bind}
204 flex
205 />
206 {accessory && (
207 <Flex.Item style={{ height: '45px', overflow: 'hidden' }}>
208 {accessory}
209 </Flex.Item>
210 )}
211 </Flex>
212 </Flex>
213 );