-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathuseMaskedInput.tsx
169 lines (146 loc) · 5.33 KB
/
useMaskedInput.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
import * as React from 'react';
import { useRifm } from 'rifm';
import { useUtils } from './useUtils';
import { DateInputProps, MuiTextFieldProps } from '../components/PureDateInput';
import {
maskedDateFormatter,
getDisplayDate,
checkMaskIsValidForCurrentFormat,
getMaskFromCurrentFormat,
} from '../utils/text-field-helper';
type MaskedInputProps<TInputDate, TDate> = Omit<
DateInputProps<TInputDate, TDate>,
| 'adornmentPosition'
| 'disableOpenPicker'
| 'getOpenDialogAriaText'
| 'InputAdornmentProps'
| 'InputProps'
| 'open'
| 'openPicker'
| 'OpenPickerButtonProps'
| 'renderInput'
> & { inputProps?: Partial<React.HTMLProps<HTMLInputElement>> };
export const useMaskedInput = <TInputDate, TDate>({
acceptRegex = /[\d]/gi,
disabled,
disableMaskedInput,
ignoreInvalidInputs,
inputFormat,
inputProps,
label,
mask,
onChange,
rawValue,
readOnly,
rifmFormatter,
TextFieldProps,
validationError,
}: MaskedInputProps<TInputDate, TDate>): MuiTextFieldProps => {
const utils = useUtils<TDate>();
const formatHelperText = utils.getFormatHelperText(inputFormat);
const { shouldUseMaskedInput, maskToUse } = React.useMemo(() => {
// formatting of dates is a quite slow thing, so do not make useless .format calls
if (disableMaskedInput) {
return { shouldUseMaskedInput: false, maskToUse: '' };
}
const computedMaskToUse = getMaskFromCurrentFormat(mask, inputFormat, acceptRegex, utils);
return {
shouldUseMaskedInput: checkMaskIsValidForCurrentFormat(
computedMaskToUse,
inputFormat,
acceptRegex,
utils,
),
maskToUse: computedMaskToUse,
};
}, [acceptRegex, disableMaskedInput, inputFormat, mask, utils]);
const formatter = React.useMemo(
() =>
shouldUseMaskedInput && maskToUse
? maskedDateFormatter(maskToUse, acceptRegex)
: (st: string) => st,
[acceptRegex, maskToUse, shouldUseMaskedInput],
);
// TODO: Implement with controlled vs uncontrolled `rawValue`
const parsedValue = rawValue === null ? null : utils.date(rawValue);
// Track the value of the input
const [innerInputValue, setInnerInputValue] = React.useState<TDate | null>(parsedValue);
// control the input text
const [innerDisplayedInputValue, setInnerDisplayedInputValue] = React.useState<string>(
getDisplayDate(utils, rawValue, inputFormat),
);
// Inspired from autocomplete: https://github.com/mui/material-ui/blob/2c89d036dc2e16f100528f161600dffc83241768/packages/mui-base/src/AutocompleteUnstyled/useAutocomplete.js#L185:L201
const prevRawValue = React.useRef<TInputDate>();
const prevLocale = React.useRef<Locale | string>(utils.locale);
const prevInputFormat = React.useRef<string>(inputFormat);
React.useEffect(() => {
const rawValueHasChanged = rawValue !== prevRawValue.current;
const localeHasChanged = utils.locale !== prevLocale.current;
const inputFormatHasChanged = inputFormat !== prevInputFormat.current;
prevRawValue.current = rawValue;
prevLocale.current = utils.locale;
prevInputFormat.current = inputFormat;
if (!rawValueHasChanged && !localeHasChanged && !inputFormatHasChanged) {
return;
}
const newParsedValue = rawValue === null ? null : utils.date(rawValue);
const isAcceptedValue = rawValue === null || utils.isValid(newParsedValue);
let innerEqualsParsed = innerInputValue === null && newParsedValue === null; // equal by being both null
if (innerInputValue !== null && newParsedValue !== null) {
const areEqual = utils.isEqual(innerInputValue, newParsedValue);
if (areEqual) {
innerEqualsParsed = true;
} else {
const diff = Math.abs(utils.getDiff(innerInputValue, newParsedValue)); // diff in ms
innerEqualsParsed =
diff === 0
? areEqual // if no diff, use equal to test the time-zone
: diff < 1000; // accept a difference bellow 1s
}
}
if (!localeHasChanged && !inputFormatHasChanged && (!isAcceptedValue || innerEqualsParsed)) {
return;
}
// When dev set a new valid value, we trust them
const newDisplayDate = getDisplayDate(utils, rawValue, inputFormat);
setInnerInputValue(newParsedValue);
setInnerDisplayedInputValue(newDisplayDate);
}, [utils, rawValue, inputFormat, innerInputValue]);
const handleChange = (text: string) => {
const finalString = text === '' || text === mask ? '' : text;
setInnerDisplayedInputValue(finalString);
const date = finalString === null ? null : utils.parse(finalString, inputFormat);
if (ignoreInvalidInputs && !utils.isValid(date)) {
return;
}
setInnerInputValue(date);
onChange(date, finalString || undefined);
};
const rifmProps = useRifm({
value: innerDisplayedInputValue,
onChange: handleChange,
format: rifmFormatter || formatter,
});
const inputStateArgs = shouldUseMaskedInput
? rifmProps
: {
value: innerDisplayedInputValue,
onChange: (event: React.ChangeEvent<HTMLInputElement>) => {
handleChange(event.currentTarget.value);
},
};
return {
label,
disabled,
error: validationError,
inputProps: {
...inputStateArgs,
disabled,
placeholder: formatHelperText,
readOnly,
type: shouldUseMaskedInput ? 'tel' : 'text',
...inputProps,
},
...TextFieldProps,
};
};