@material-ui/pickers#KeyboardDatePickerProps TypeScript Examples

The following examples show how to use @material-ui/pickers#KeyboardDatePickerProps. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: date-picker.tsx    From keycaplendar with MIT License 4 votes vote down vote up
DatePicker = ({
  pickerProps,
  modalProps,
  value,
  fallbackValue,
  onChange,
  month,
  allowQuarter,
  showNowButton,
  saveOnClose,
  required,
  helpTextProps = {},
  ...props
}: DatePickerProps) => {
  const device = useAppSelector(selectDevice);
  const useInline = device === "desktop";
  const orientation = useAppSelector(selectOrientation);
  const landscape = orientation === "landscape";

  const [touched, setTouched] = useState(false);
  const invalid = touched
    ? invalidDate(value, {
        allowQuarter,
        disableFuture: pickerProps?.disableFuture,
        month,
        required,
      })
    : false;

  const validFallback = invalidDate(fallbackValue || "") ? "" : fallbackValue;

  const views: KeyboardDatePickerProps["views"] = month
    ? ["year", "month"]
    : undefined;
  const openTo: KeyboardDatePickerProps["openTo"] = month ? "month" : "date";

  const minDate = pickerProps?.minDate || "2000-01-01";
  const maxDate = pickerProps?.disableFuture
    ? DateTime.now().toFormat(month ? "yyyy-MM" : "yyyy-MM-dd")
    : pickerProps?.maxDate
    ? pickerProps.maxDate
    : DateTime.now()
        .plus({ years: 2 })
        .toFormat(month ? "yyyy-MM" : "yyyy-MM-dd");

  const rifm = useRifm({
    accept: allowQuarter ? /\d|\s|Q/g : /\d/g,
    format: formatDateWithAppend(month, allowQuarter),
    onChange,
    value,
  });

  const [open, setOpen] = useState(false);

  const [dialogVal, setDialogVal] = useState(value);
  useEffect(() => {
    if (dialogVal !== value) {
      setDialogVal(value || validFallback || DateTime.now().toISODate());
    }
  }, [value, fallbackValue]);

  const confirmVal = useInline && !saveOnClose ? onChange : setDialogVal;

  const handleDatePickerChange: KeyboardDatePickerProps["onChange"] = (
    date,
    value
  ) => {
    const finalValue =
      (month ? date?.toFormat("yyyy-MM") : date?.toISODate()) || value || "";
    confirmVal(finalValue);
  };
  const setNow = () => {
    confirmVal(DateTime.now().toFormat(month ? "yyyy-MM" : "yyyy-MM-dd"));
  };

  const closeDialog = () => {
    setOpen(false);
  };

  const confirmDialog = () => {
    onChange(
      dialogVal ||
        validFallback ||
        DateTime.now().toFormat(month ? "yyyy-MM" : "yyyy-MM-dd")
    );
    closeDialog();
  };

  const modal = useInline ? (
    <MenuSurface
      {...modalProps}
      anchorCorner="bottomLeft"
      className={bemClasses("modal", { open }, [modalProps?.className || ""])}
      onClose={saveOnClose ? confirmDialog : undefined}
      open={open && (!allowQuarter || value.charAt(0) !== "Q")}
    >
      <KeyboardDatePicker
        maxDate={maxDate}
        minDate={minDate}
        onChange={handleDatePickerChange}
        openTo={openTo}
        orientation="portrait"
        value={
          saveOnClose
            ? dialogVal
            : value || validFallback || DateTime.now().toISODate()
        }
        variant="static"
        views={views}
        {...pickerProps}
      />
      {showNowButton ? (
        <div className={bemClasses("buttons")}>
          <Button
            label={month ? "This month" : "Today"}
            onClick={setNow}
            type="button"
          />
        </div>
      ) : null}
    </MenuSurface>
  ) : (
    <Dialog
      {...modalProps}
      className={bemClasses("modal", { open }, [modalProps?.className || ""])}
      onClose={closeDialog}
      open={open}
      renderToPortal
    >
      <KeyboardDatePicker
        maxDate={maxDate}
        minDate={minDate}
        onChange={handleDatePickerChange}
        openTo={openTo}
        orientation={orientation}
        value={dialogVal || validFallback || DateTime.now().toISODate()}
        variant="static"
        views={views}
        {...pickerProps}
      />
      <ConditionalWrapper
        condition={landscape}
        wrapper={(children) => (
          <div className={bemClasses("bottom-bar")}>{children}</div>
        )}
      >
        <DialogActions>
          {showNowButton ? (
            <Button
              className={bemClasses("show-now-button")}
              label={month ? "This month" : "Today"}
              onClick={setNow}
              type="button"
            />
          ) : null}
          <DialogButton isDefaultAction label="Cancel" onClick={closeDialog} />
          <DialogButton label="Confirm" onClick={confirmDialog} />
        </DialogActions>
      </ConditionalWrapper>
    </Dialog>
  );

  return (
    <ConditionalWrapper
      condition={useInline}
      wrapper={(children) => (
        <MenuSurfaceAnchor className={bemClasses("anchor")}>
          {children}
        </MenuSurfaceAnchor>
      )}
    >
      <TextField
        {...props}
        className={bemClasses("field")}
        helpText={{
          children: invalid
            ? capitalise(invalid)
            : `Format: ${month ? "YYYY-MM" : "YYYY-MM-DD"}${
                allowQuarter ? " or Q1-4 YYYY" : ""
              }`,
          persistent: true,
          validationMsg: true,
          ...helpTextProps,
        }}
        inputMode="numeric"
        invalid={!!invalid}
        onBlur={() => {
          if (!touched) {
            setTouched(true);
          }
          if (useInline) {
            setOpen(false);
          }
        }}
        onChange={rifm.onChange}
        onFocus={() => {
          if (touched) {
            setTouched(false);
          }
          if (useInline) {
            setOpen(true);
          }
        }}
        pattern={`^\\d{4}-\\d{1,2}${!month ? "-\\d{1,2}" : ""}$${
          allowQuarter ? "|^Q[1-4]{1} \\d{4}$" : ""
        }`}
        required={required}
        trailingIcon={
          useInline
            ? undefined
            : withTooltip(
                <IconButton
                  icon={iconObject(<Event />)}
                  onClick={() => setOpen(true)}
                />,
                "Date picker"
              )
        }
        value={rifm.value}
      />
      {modal}
    </ConditionalWrapper>
  );
}