mui-x icon indicating copy to clipboard operation
mui-x copied to clipboard

[pickers] Smart pasting in date and time fields

Open joserodolfofreitas opened this issue 3 years ago • 3 comments

Summary 💡

When users paste a date or time string, the field automatically recognizes the input and matches the string with the given sections of the field. The field can ideally distinguish different date separators and even date formats, for example, pasting a MM/DD into MMM d. The field ideally recognizes partial dates if the field "starts with" it.

Examples 🌈

https://retool.com/components/date

Motivation 🔦

Enable copying and pasting in forms using Fields (and Pickers).

joserodolfofreitas avatar Dec 19 '22 15:12 joserodolfofreitas

On the demo at https://mui.com/blog/v6-beta-pickers/

I tried pasting 2/2/23 and it did not work, I had to type in the zero padded dates 02/02/2023.

lb- avatar Feb 09 '23 00:02 lb-

Is there a potential workaround for this until this is implemented?

z0mby avatar Oct 11 '23 14:10 z0mby

@z0mby @joserodolfofreitas @matan44 @ImperadorSid @lb- there is workaround for this :) you will need something like this

I use the moment, because I have a very old project, but the point here is just to show the working code, adapt it to your needs, use a more modern date library, etc.

const CustomTextField = (props) => {
  const {
    handlePaste,
    ...textFieldProps
  } = props;

  return (
    <TextField
      {...textFieldProps}
      inputProps={{
        ...textFieldProps.inputProps,
        onPaste: handlePaste,
      }}
    />
  );
};

const DateInput = () => {
  const [value, setValue] = useState(null);

  const handlePaste = (event) => {
    event.stopPropagation();
    event.preventDefault();
    const dateToPaste = event.clipboardData.getData("text");

    const date = moment(dateToPaste, [
      "M/D/YYYY",
      "MM/DD/YYYY",
      "DD MMM YYYY",
      "DD MMMM YYYY",
      "YYYY-MM-DD",
      "YYYY-M-D",
      "YYYY.MM.DD",
      "YYYY.M.D",
      "DD.MM.YYYY",
      "D.M.YYYY",
      "YYYY/MM/DD",
      "YYYY-MM-DD",
    ]).format("MM/DD/YYYY");

    if (date !== "Invalid date") {
      setValue(moment(date));
    }
  };

  return (
    <DesktopDateTimePicker
      slots={{
        textField: CustomTextField,
      }}
      value={value}
      slotProps={{
        textField: {
          handlePaste,
        },
      }}
    />
  );
};

shadaxv avatar Aug 28 '24 14:08 shadaxv