-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumberAndDateInputs.tsx
242 lines (224 loc) · 7.57 KB
/
NumberAndDateInputs.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Typography, TextField } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import { DARKEST_GRAY, MEDIUM_GRAY } from '../../constants/colors';
import { NumberOrDate } from '../../types/general';
import { debounce } from 'lodash';
import { warning } from '@veupathdb/coreui/lib/definitions/colors';
type BaseProps<M extends NumberOrDate> = {
/** Externally controlled value. */
value?: M;
/** Minimum allowed value (inclusive) */
minValue?: M;
/** Maximum allowed value (inclusive) */
maxValue?: M;
/** If true, warn about empty value. Default is false. */
required?: boolean;
/** Optional validator function. Should return {validity: true, message: ''} if value is allowed.
* If provided, minValue and maxValue and required will have no effect.
*/
validator?: (newValue?: NumberOrDate) => {
validity: boolean;
message: string;
};
/** Function to invoke when value changes. */
onValueChange: (newValue?: NumberOrDate) => void;
/** UI Label for the widget. Optional */
label?: string;
/** Additional styles for component container. Optional. */
containerStyles?: React.CSSProperties;
/** Do not flag up value range violations */
displayRangeViolationWarnings?: boolean;
/** Disabled? Default is false */
disabled?: boolean;
/** Style the Text Field with the warning color and bold stroke */
applyWarningStyles?: boolean;
/** specify the height of the input element */
inputHeight?: number;
};
export type NumberInputProps = BaseProps<number> & { step?: number };
export function NumberInput(props: NumberInputProps) {
return <BaseInput {...props} valueType="number" />;
}
export type DateInputProps = BaseProps<string>;
export function DateInput(props: DateInputProps) {
return <BaseInput {...props} valueType="date" />;
}
type BaseInputProps =
| (NumberInputProps & {
valueType: 'number';
})
| (DateInputProps & {
valueType: 'date'; // another possibility is 'datetime-local', but the Material UI TextField doesn't provide a date picker
});
/**
* Input field taking a value we can do < > <= => comparisons with
* i.e. number or date.
* Not currently exported. But could be if needed.
*
* This component will allow out-of-range and empty values, but it will only
* call `onValueChange` when the new value is valid. An error message will be
* displayed when the value is invalid, but the consumer of this component will
* not be notified of the invalid state. It's possible we will want to add a
* callback to allow observing invalid states, in the future.
*
* The `onValueChange` callback is debounced at 500ms. This allows the user to
* type a value at a reasonable pace, without invoking the callback for
* intermediate values. We use a local state variable to track the input's
* actual value.
*/
function BaseInput({
value,
minValue,
maxValue,
validator,
required = false,
onValueChange,
label,
valueType,
containerStyles,
displayRangeViolationWarnings = true,
disabled = false,
applyWarningStyles = false,
// default value is 36.5
inputHeight = 36.5,
...props
}: BaseInputProps) {
if (validator && (required || minValue != null || maxValue != null))
console.log(
'WARNING: NumberInput or DateInput will ignore props required, minValue and/or maxValue because validator was provided.'
);
const [localValue, setLocalValue] = useState<NumberOrDate | undefined>(value);
const [focused, setFocused] = useState(false);
const [errorState, setErrorState] = useState({
error: false,
helperText: '',
});
const classes = makeStyles({
root: {
height: inputHeight, // default height is 56 and is waaaay too tall
// 34.5 is the height of the reset button, but 36.5 lines up better
// set width for date
width: valueType === 'date' ? 165 : '',
},
notchedOutline: applyWarningStyles
? {
borderColor: warning[500],
borderWidth: 3,
}
: {},
})();
const debouncedOnChange = useMemo(
() => debounce(onValueChange, 500),
[onValueChange]
);
// Cancel pending onChange request when this component is unmounted.
useEffect(() => debouncedOnChange.cancel, []);
const _validator =
validator ??
useCallback(
(newValue?: NumberOrDate): { validity: boolean; message: string } => {
if (newValue == null) {
return {
validity: !required,
message: required ? `Please enter a ${valueType}.` : '',
};
}
if (minValue != null && newValue < minValue) {
return {
validity: false,
message: `Sorry, value can't go below ${minValue}!`,
};
} else if (maxValue != null && newValue > maxValue) {
return {
validity: false,
message: `Sorry, value can't go above ${maxValue}!`,
};
} else if (
minValue != null &&
newValue === minValue &&
maxValue != null &&
newValue === maxValue
) {
return {
validity: false,
message: `Sorry, min and max values can't be the same!`,
};
} else {
return { validity: true, message: '' };
}
},
[required, minValue, maxValue]
);
const boundsCheckedValue = useCallback(
(newValue?: NumberOrDate) => {
const { validity, message } = _validator(newValue);
setErrorState({ error: message !== '', helperText: message });
return validity;
},
[_validator]
);
// Handle incoming value changes (including changes in minValue/maxValue, which affect boundsCheckedValue)
useEffect(() => {
boundsCheckedValue(value);
if (value !== localValue) setLocalValue(value);
}, [value, boundsCheckedValue]);
const handleChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const newValue =
event.target.value === ''
? undefined
: valueType === 'number'
? Number(event.target.value)
: String(event.target.value);
setLocalValue(newValue);
const isValid = boundsCheckedValue(newValue);
if (isValid) {
debouncedOnChange(newValue);
} else {
// immediately send the last valid value to onChange
debouncedOnChange.flush();
}
},
[boundsCheckedValue, debouncedOnChange]
);
const step =
valueType === 'number' && 'step' in props ? props.step : undefined;
return (
<div
// containerStyles is not used here - but bin control uses this!
style={{ ...containerStyles }}
onMouseOver={() => setFocused(true)}
onMouseOut={() => setFocused(false)}
>
{label && (
<Typography
variant="button"
style={{ color: disabled ? MEDIUM_GRAY : DARKEST_GRAY }}
>
{label}
</Typography>
)}
<div style={{ display: 'flex', flexDirection: 'row' }}>
<TextField
InputProps={{ classes }}
inputProps={{ step }}
value={
localValue == null
? ''
: valueType === 'number'
? localValue
: (localValue as string)?.substr(0, 10) // MUI date picker can't handle date-times
}
type={valueType}
variant="outlined"
onChange={handleChange}
onFocus={(event) => event.currentTarget.select()}
error={errorState.error}
helperText={displayRangeViolationWarnings && errorState.helperText}
disabled={disabled}
/>
</div>
</div>
);
}