@material-ui/pickers#KeyboardTimePickerProps TypeScript Examples

The following examples show how to use @material-ui/pickers#KeyboardTimePickerProps. 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: time-picker.tsx    From keycaplendar with MIT License 4 votes vote down vote up
TimePicker = ({
  pickerProps,
  modalProps,
  value,
  fallbackValue,
  onChange,
  showNowButton,
  saveOnClose,
  required,
  helpTextProps = {},
  ...props
}: TimePickerProps) => {
  const device = useAppSelector(selectDevice);
  const useInline = device === "desktop";
  const orientation = useAppSelector(selectOrientation);
  const landscape = orientation === "landscape";

  const [touched, setTouched] = useState(false);
  const invalid = touched ? invalidTime(value, { required }) : false;

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

  const rifm = useRifm({
    accept: /\d:/g,
    format: formatTime,
    onChange,
    value,
  });

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

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

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

  const handleTimePickerChange: KeyboardTimePickerProps["onChange"] = (
    date,
    value
  ) => {
    const finalValue =
      date?.toLocaleString(DateTime.TIME_24_SIMPLE) || value || "";
    confirmVal(finalValue);
  };
  const setNow = () => {
    confirmVal(DateTime.now().toLocaleString(DateTime.TIME_24_SIMPLE));
  };

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

  const confirmDialog = () => {
    onChange(
      dialogVal ||
        validFallback ||
        DateTime.now().toLocaleString(DateTime.TIME_24_SIMPLE)
    );
    closeDialog();
  };

  const modal = useInline ? (
    <MenuSurface
      {...modalProps}
      anchorCorner="bottomLeft"
      className={bemClasses("modal", { open }, [modalProps?.className || ""])}
      onClose={saveOnClose ? confirmDialog : undefined}
      open={open}
    >
      <KeyboardTimePicker
        ampm={false}
        onChange={handleTimePickerChange}
        openTo="hours"
        orientation="portrait"
        value={`2020-12-20T${
          saveOnClose
            ? dialogVal
            : value || validFallback || DateTime.now().toISODate()
        }`}
        variant="static"
        {...pickerProps}
      />
      {showNowButton ? (
        <div className={bemClasses("buttons")}>
          <Button label="Now" onClick={setNow} type="button" />
        </div>
      ) : null}
    </MenuSurface>
  ) : (
    <Dialog
      {...modalProps}
      className={bemClasses("modal", { open }, [modalProps?.className || ""])}
      onClose={closeDialog}
      open={open}
      renderToPortal
    >
      <KeyboardTimePicker
        ampm={false}
        onChange={handleTimePickerChange}
        openTo="hours"
        orientation={orientation}
        value={`2020-12-20T${
          dialogVal ||
          validFallback ||
          DateTime.now().toLocaleString(DateTime.TIME_24_SIMPLE)
        }`}
        variant="static"
        {...pickerProps}
      />
      <ConditionalWrapper
        condition={landscape}
        wrapper={(children) => (
          <div className={bemClasses("bottom-bar")}>{children}</div>
        )}
      >
        <DialogActions>
          {showNowButton ? (
            <Button
              className={bemClasses("show-now-button")}
              label="Now"
              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", { inline: useInline })}
        helpText={{
          children: invalid ? capitalise(invalid) : "Format: HH:YY (24hr)",
          persistent: true,
          validationMsg: true,
          ...helpTextProps,
        }}
        inputMode="numeric"
        invalid={!!invalid}
        onBlur={() => {
          if (!touched) {
            setTouched(true);
          }
          if (useInline && !saveOnClose) {
            setOpen(false);
          }
        }}
        onChange={rifm.onChange}
        onFocus={() => {
          if (touched) {
            setTouched(false);
          }
          if (useInline) {
            setOpen(true);
          }
        }}
        pattern="^\d{2}:\d{2}"
        required={required}
        trailingIcon={
          useInline
            ? undefined
            : withTooltip(
                <IconButton
                  icon={iconObject(<Event />)}
                  onClick={() => setOpen(true)}
                />,
                "Time picker"
              )
        }
        value={rifm.value}
      />
      {modal}
    </ConditionalWrapper>
  );
}