|
| 1 | +import * as React from 'react'; |
| 2 | +import dayjs from 'dayjs'; |
| 3 | +import { useRifm } from 'rifm'; |
| 4 | +import TextField from '@mui/material/TextField'; |
| 5 | +import useControlled from '@mui/utils/useControlled'; |
| 6 | +import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; |
| 7 | +import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; |
| 8 | +import { DatePicker } from '@mui/x-date-pickers/DatePicker'; |
| 9 | +import { useSplitFieldProps, useParsedFormat } from '@mui/x-date-pickers/hooks'; |
| 10 | +import { useValidation, validateDate } from '@mui/x-date-pickers/validation'; |
| 11 | + |
| 12 | +const MASK_USER_INPUT_SYMBOL = '_'; |
| 13 | +const ACCEPT_REGEX = /[\d]/gi; |
| 14 | + |
| 15 | +const staticDateWith2DigitTokens = dayjs('2019-11-21T11:30:00.000'); |
| 16 | +const staticDateWith1DigitTokens = dayjs('2019-01-01T09:00:00.000'); |
| 17 | + |
| 18 | +function getValueStrFromValue(value, format) { |
| 19 | + if (value == null) { |
| 20 | + return ''; |
| 21 | + } |
| 22 | + |
| 23 | + return value.isValid() ? value.format(format) : ''; |
| 24 | +} |
| 25 | + |
| 26 | +function MaskedField(props) { |
| 27 | + const { slots, slotProps, ...other } = props; |
| 28 | + |
| 29 | + const { forwardedProps, internalProps } = useSplitFieldProps(other, 'date'); |
| 30 | + |
| 31 | + const { |
| 32 | + format, |
| 33 | + value: valueProp, |
| 34 | + defaultValue, |
| 35 | + onChange, |
| 36 | + timezone, |
| 37 | + onError, |
| 38 | + } = internalProps; |
| 39 | + |
| 40 | + const [value, setValue] = useControlled({ |
| 41 | + controlled: valueProp, |
| 42 | + default: defaultValue ?? null, |
| 43 | + name: 'MaskedField', |
| 44 | + state: 'value', |
| 45 | + }); |
| 46 | + |
| 47 | + // Control the input text |
| 48 | + const [inputValue, setInputValue] = React.useState(() => |
| 49 | + getValueStrFromValue(value, format), |
| 50 | + ); |
| 51 | + |
| 52 | + React.useEffect(() => { |
| 53 | + if (value && value.isValid()) { |
| 54 | + const newDisplayDate = getValueStrFromValue(value, format); |
| 55 | + setInputValue(newDisplayDate); |
| 56 | + } |
| 57 | + }, [format, value]); |
| 58 | + |
| 59 | + const parsedFormat = useParsedFormat(internalProps); |
| 60 | + |
| 61 | + const { hasValidationError, getValidationErrorForNewValue } = useValidation({ |
| 62 | + value, |
| 63 | + timezone, |
| 64 | + onError, |
| 65 | + props: internalProps, |
| 66 | + validator: validateDate, |
| 67 | + }); |
| 68 | + |
| 69 | + const handleValueStrChange = (newValueStr) => { |
| 70 | + setInputValue(newValueStr); |
| 71 | + |
| 72 | + const newValue = dayjs(newValueStr, format); |
| 73 | + setValue(newValue); |
| 74 | + |
| 75 | + if (onChange) { |
| 76 | + onChange(newValue, { |
| 77 | + validationError: getValidationErrorForNewValue(newValue), |
| 78 | + }); |
| 79 | + } |
| 80 | + }; |
| 81 | + |
| 82 | + const rifmFormat = React.useMemo(() => { |
| 83 | + const formattedDateWith1Digit = staticDateWith1DigitTokens.format(format); |
| 84 | + const inferredFormatPatternWith1Digits = formattedDateWith1Digit.replace( |
| 85 | + ACCEPT_REGEX, |
| 86 | + MASK_USER_INPUT_SYMBOL, |
| 87 | + ); |
| 88 | + const inferredFormatPatternWith2Digits = staticDateWith2DigitTokens |
| 89 | + .format(format) |
| 90 | + .replace(ACCEPT_REGEX, '_'); |
| 91 | + |
| 92 | + if (inferredFormatPatternWith1Digits !== inferredFormatPatternWith2Digits) { |
| 93 | + throw new Error( |
| 94 | + `Mask does not support numbers with variable length such as 'M'.`, |
| 95 | + ); |
| 96 | + } |
| 97 | + |
| 98 | + const maskToUse = inferredFormatPatternWith1Digits; |
| 99 | + |
| 100 | + return function formatMaskedDate(valueToFormat) { |
| 101 | + let outputCharIndex = 0; |
| 102 | + return valueToFormat |
| 103 | + .split('') |
| 104 | + .map((character, characterIndex) => { |
| 105 | + ACCEPT_REGEX.lastIndex = 0; |
| 106 | + |
| 107 | + if (outputCharIndex > maskToUse.length - 1) { |
| 108 | + return ''; |
| 109 | + } |
| 110 | + |
| 111 | + const maskChar = maskToUse[outputCharIndex]; |
| 112 | + const nextMaskChar = maskToUse[outputCharIndex + 1]; |
| 113 | + |
| 114 | + const acceptedChar = ACCEPT_REGEX.test(character) ? character : ''; |
| 115 | + const formattedChar = |
| 116 | + maskChar === MASK_USER_INPUT_SYMBOL |
| 117 | + ? acceptedChar |
| 118 | + : maskChar + acceptedChar; |
| 119 | + |
| 120 | + outputCharIndex += formattedChar.length; |
| 121 | + |
| 122 | + const isLastCharacter = characterIndex === valueToFormat.length - 1; |
| 123 | + if ( |
| 124 | + isLastCharacter && |
| 125 | + nextMaskChar && |
| 126 | + nextMaskChar !== MASK_USER_INPUT_SYMBOL |
| 127 | + ) { |
| 128 | + // when cursor at the end of mask part (e.g. month) prerender next symbol "21" -> "21/" |
| 129 | + return formattedChar ? formattedChar + nextMaskChar : ''; |
| 130 | + } |
| 131 | + |
| 132 | + return formattedChar; |
| 133 | + }) |
| 134 | + .join(''); |
| 135 | + }; |
| 136 | + }, [format]); |
| 137 | + |
| 138 | + const rifmProps = useRifm({ |
| 139 | + value: inputValue, |
| 140 | + onChange: handleValueStrChange, |
| 141 | + format: rifmFormat, |
| 142 | + }); |
| 143 | + |
| 144 | + return ( |
| 145 | + <TextField |
| 146 | + placeholder={parsedFormat} |
| 147 | + error={!!hasValidationError} |
| 148 | + {...rifmProps} |
| 149 | + {...forwardedProps} |
| 150 | + /> |
| 151 | + ); |
| 152 | +} |
| 153 | + |
| 154 | +function MaskedFieldDatePicker(props) { |
| 155 | + return <DatePicker slots={{ ...props.slots, field: MaskedField }} {...props} />; |
| 156 | +} |
| 157 | + |
| 158 | +export default function MaskedMaterialTextField() { |
| 159 | + return ( |
| 160 | + <LocalizationProvider dateAdapter={AdapterDayjs}> |
| 161 | + <MaskedFieldDatePicker /> |
| 162 | + </LocalizationProvider> |
| 163 | + ); |
| 164 | +} |
0 commit comments