-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[docs] Create Pickers masked field recipe (#13515)
Signed-off-by: Flavien DELANGLE <flaviendelangle@gmail.com> Co-authored-by: Michel Engelen <32863416+michelengelen@users.noreply.github.com>
- Loading branch information
1 parent
bc0674a
commit 58682ef
Showing
6 changed files
with
352 additions
and
0 deletions.
There are no files selected for viewing
164 changes: 164 additions & 0 deletions
164
docs/data/date-pickers/custom-field/custom-behavior/MaskedMaterialTextField.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,164 @@ | ||
import * as React from 'react'; | ||
import dayjs from 'dayjs'; | ||
import { useRifm } from 'rifm'; | ||
import TextField from '@mui/material/TextField'; | ||
import useControlled from '@mui/utils/useControlled'; | ||
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; | ||
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; | ||
import { DatePicker } from '@mui/x-date-pickers/DatePicker'; | ||
import { useSplitFieldProps, useParsedFormat } from '@mui/x-date-pickers/hooks'; | ||
import { useValidation, validateDate } from '@mui/x-date-pickers/validation'; | ||
|
||
const MASK_USER_INPUT_SYMBOL = '_'; | ||
const ACCEPT_REGEX = /[\d]/gi; | ||
|
||
const staticDateWith2DigitTokens = dayjs('2019-11-21T11:30:00.000'); | ||
const staticDateWith1DigitTokens = dayjs('2019-01-01T09:00:00.000'); | ||
|
||
function getValueStrFromValue(value, format) { | ||
if (value == null) { | ||
return ''; | ||
} | ||
|
||
return value.isValid() ? value.format(format) : ''; | ||
} | ||
|
||
function MaskedField(props) { | ||
const { slots, slotProps, ...other } = props; | ||
|
||
const { forwardedProps, internalProps } = useSplitFieldProps(other, 'date'); | ||
|
||
const { | ||
format, | ||
value: valueProp, | ||
defaultValue, | ||
onChange, | ||
timezone, | ||
onError, | ||
} = internalProps; | ||
|
||
const [value, setValue] = useControlled({ | ||
controlled: valueProp, | ||
default: defaultValue ?? null, | ||
name: 'MaskedField', | ||
state: 'value', | ||
}); | ||
|
||
// Control the input text | ||
const [inputValue, setInputValue] = React.useState(() => | ||
getValueStrFromValue(value, format), | ||
); | ||
|
||
React.useEffect(() => { | ||
if (value && value.isValid()) { | ||
const newDisplayDate = getValueStrFromValue(value, format); | ||
setInputValue(newDisplayDate); | ||
} | ||
}, [format, value]); | ||
|
||
const parsedFormat = useParsedFormat(internalProps); | ||
|
||
const { hasValidationError, getValidationErrorForNewValue } = useValidation({ | ||
value, | ||
timezone, | ||
onError, | ||
props: internalProps, | ||
validator: validateDate, | ||
}); | ||
|
||
const handleValueStrChange = (newValueStr) => { | ||
setInputValue(newValueStr); | ||
|
||
const newValue = dayjs(newValueStr, format); | ||
setValue(newValue); | ||
|
||
if (onChange) { | ||
onChange(newValue, { | ||
validationError: getValidationErrorForNewValue(newValue), | ||
}); | ||
} | ||
}; | ||
|
||
const rifmFormat = React.useMemo(() => { | ||
const formattedDateWith1Digit = staticDateWith1DigitTokens.format(format); | ||
const inferredFormatPatternWith1Digits = formattedDateWith1Digit.replace( | ||
ACCEPT_REGEX, | ||
MASK_USER_INPUT_SYMBOL, | ||
); | ||
const inferredFormatPatternWith2Digits = staticDateWith2DigitTokens | ||
.format(format) | ||
.replace(ACCEPT_REGEX, '_'); | ||
|
||
if (inferredFormatPatternWith1Digits !== inferredFormatPatternWith2Digits) { | ||
throw new Error( | ||
`Mask does not support numbers with variable length such as 'M'.`, | ||
); | ||
} | ||
|
||
const maskToUse = inferredFormatPatternWith1Digits; | ||
|
||
return function formatMaskedDate(valueToFormat) { | ||
let outputCharIndex = 0; | ||
return valueToFormat | ||
.split('') | ||
.map((character, characterIndex) => { | ||
ACCEPT_REGEX.lastIndex = 0; | ||
|
||
if (outputCharIndex > maskToUse.length - 1) { | ||
return ''; | ||
} | ||
|
||
const maskChar = maskToUse[outputCharIndex]; | ||
const nextMaskChar = maskToUse[outputCharIndex + 1]; | ||
|
||
const acceptedChar = ACCEPT_REGEX.test(character) ? character : ''; | ||
const formattedChar = | ||
maskChar === MASK_USER_INPUT_SYMBOL | ||
? acceptedChar | ||
: maskChar + acceptedChar; | ||
|
||
outputCharIndex += formattedChar.length; | ||
|
||
const isLastCharacter = characterIndex === valueToFormat.length - 1; | ||
if ( | ||
isLastCharacter && | ||
nextMaskChar && | ||
nextMaskChar !== MASK_USER_INPUT_SYMBOL | ||
) { | ||
// when cursor at the end of mask part (e.g. month) prerender next symbol "21" -> "21/" | ||
return formattedChar ? formattedChar + nextMaskChar : ''; | ||
} | ||
|
||
return formattedChar; | ||
}) | ||
.join(''); | ||
}; | ||
}, [format]); | ||
|
||
const rifmProps = useRifm({ | ||
value: inputValue, | ||
onChange: handleValueStrChange, | ||
format: rifmFormat, | ||
}); | ||
|
||
return ( | ||
<TextField | ||
placeholder={parsedFormat} | ||
error={!!hasValidationError} | ||
{...rifmProps} | ||
{...forwardedProps} | ||
/> | ||
); | ||
} | ||
|
||
function MaskedFieldDatePicker(props) { | ||
return <DatePicker slots={{ ...props.slots, field: MaskedField }} {...props} />; | ||
} | ||
|
||
export default function MaskedMaterialTextField() { | ||
return ( | ||
<LocalizationProvider dateAdapter={AdapterDayjs}> | ||
<MaskedFieldDatePicker /> | ||
</LocalizationProvider> | ||
); | ||
} |
168 changes: 168 additions & 0 deletions
168
docs/data/date-pickers/custom-field/custom-behavior/MaskedMaterialTextField.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,168 @@ | ||
import * as React from 'react'; | ||
import dayjs, { Dayjs } from 'dayjs'; | ||
import { useRifm } from 'rifm'; | ||
import TextField from '@mui/material/TextField'; | ||
import useControlled from '@mui/utils/useControlled'; | ||
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; | ||
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; | ||
import { | ||
DatePicker, | ||
DatePickerProps, | ||
DatePickerFieldProps, | ||
} from '@mui/x-date-pickers/DatePicker'; | ||
import { useSplitFieldProps, useParsedFormat } from '@mui/x-date-pickers/hooks'; | ||
import { useValidation, validateDate } from '@mui/x-date-pickers/validation'; | ||
|
||
const MASK_USER_INPUT_SYMBOL = '_'; | ||
const ACCEPT_REGEX = /[\d]/gi; | ||
|
||
const staticDateWith2DigitTokens = dayjs('2019-11-21T11:30:00.000'); | ||
const staticDateWith1DigitTokens = dayjs('2019-01-01T09:00:00.000'); | ||
|
||
function getValueStrFromValue(value: Dayjs | null, format: string) { | ||
if (value == null) { | ||
return ''; | ||
} | ||
|
||
return value.isValid() ? value.format(format) : ''; | ||
} | ||
|
||
function MaskedField(props: DatePickerFieldProps<Dayjs>) { | ||
const { slots, slotProps, ...other } = props; | ||
|
||
const { forwardedProps, internalProps } = useSplitFieldProps(other, 'date'); | ||
|
||
const { | ||
format, | ||
value: valueProp, | ||
defaultValue, | ||
onChange, | ||
timezone, | ||
onError, | ||
} = internalProps; | ||
|
||
const [value, setValue] = useControlled({ | ||
controlled: valueProp, | ||
default: defaultValue ?? null, | ||
name: 'MaskedField', | ||
state: 'value', | ||
}); | ||
|
||
// Control the input text | ||
const [inputValue, setInputValue] = React.useState<string>(() => | ||
getValueStrFromValue(value, format), | ||
); | ||
|
||
React.useEffect(() => { | ||
if (value && value.isValid()) { | ||
const newDisplayDate = getValueStrFromValue(value, format); | ||
setInputValue(newDisplayDate); | ||
} | ||
}, [format, value]); | ||
|
||
const parsedFormat = useParsedFormat(internalProps); | ||
|
||
const { hasValidationError, getValidationErrorForNewValue } = useValidation({ | ||
value, | ||
timezone, | ||
onError, | ||
props: internalProps, | ||
validator: validateDate, | ||
}); | ||
|
||
const handleValueStrChange = (newValueStr: string) => { | ||
setInputValue(newValueStr); | ||
|
||
const newValue = dayjs(newValueStr, format); | ||
setValue(newValue); | ||
|
||
if (onChange) { | ||
onChange(newValue, { | ||
validationError: getValidationErrorForNewValue(newValue), | ||
}); | ||
} | ||
}; | ||
|
||
const rifmFormat = React.useMemo(() => { | ||
const formattedDateWith1Digit = staticDateWith1DigitTokens.format(format); | ||
const inferredFormatPatternWith1Digits = formattedDateWith1Digit.replace( | ||
ACCEPT_REGEX, | ||
MASK_USER_INPUT_SYMBOL, | ||
); | ||
const inferredFormatPatternWith2Digits = staticDateWith2DigitTokens | ||
.format(format) | ||
.replace(ACCEPT_REGEX, '_'); | ||
|
||
if (inferredFormatPatternWith1Digits !== inferredFormatPatternWith2Digits) { | ||
throw new Error( | ||
`Mask does not support numbers with variable length such as 'M'.`, | ||
); | ||
} | ||
|
||
const maskToUse = inferredFormatPatternWith1Digits; | ||
|
||
return function formatMaskedDate(valueToFormat: string) { | ||
let outputCharIndex = 0; | ||
return valueToFormat | ||
.split('') | ||
.map((character, characterIndex) => { | ||
ACCEPT_REGEX.lastIndex = 0; | ||
|
||
if (outputCharIndex > maskToUse.length - 1) { | ||
return ''; | ||
} | ||
|
||
const maskChar = maskToUse[outputCharIndex]; | ||
const nextMaskChar = maskToUse[outputCharIndex + 1]; | ||
|
||
const acceptedChar = ACCEPT_REGEX.test(character) ? character : ''; | ||
const formattedChar = | ||
maskChar === MASK_USER_INPUT_SYMBOL | ||
? acceptedChar | ||
: maskChar + acceptedChar; | ||
|
||
outputCharIndex += formattedChar.length; | ||
|
||
const isLastCharacter = characterIndex === valueToFormat.length - 1; | ||
if ( | ||
isLastCharacter && | ||
nextMaskChar && | ||
nextMaskChar !== MASK_USER_INPUT_SYMBOL | ||
) { | ||
// when cursor at the end of mask part (e.g. month) prerender next symbol "21" -> "21/" | ||
return formattedChar ? formattedChar + nextMaskChar : ''; | ||
} | ||
|
||
return formattedChar; | ||
}) | ||
.join(''); | ||
}; | ||
}, [format]); | ||
|
||
const rifmProps = useRifm({ | ||
value: inputValue, | ||
onChange: handleValueStrChange, | ||
format: rifmFormat, | ||
}); | ||
|
||
return ( | ||
<TextField | ||
placeholder={parsedFormat} | ||
error={!!hasValidationError} | ||
{...rifmProps} | ||
{...forwardedProps} | ||
/> | ||
); | ||
} | ||
|
||
function MaskedFieldDatePicker(props: DatePickerProps<Dayjs>) { | ||
return <DatePicker slots={{ ...props.slots, field: MaskedField }} {...props} />; | ||
} | ||
|
||
export default function MaskedMaterialTextField() { | ||
return ( | ||
<LocalizationProvider dateAdapter={AdapterDayjs}> | ||
<MaskedFieldDatePicker /> | ||
</LocalizationProvider> | ||
); | ||
} |
1 change: 1 addition & 0 deletions
1
docs/data/date-pickers/custom-field/custom-behavior/MaskedMaterialTextField.tsx.preview
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
<MaskedFieldDatePicker /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.