All files / src/timepicker TimePicker.tsx

30.77% Statements 16/52
33.33% Branches 13/39
30% Functions 3/10
30.77% Lines 16/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222                                                  1x         1x   5x 5x                                         5x   5x 5x 5x   5x 5x   10x         5x       5x 5x 5x                                                                                                                                                                       5x                                                                                                                              
import React, { useState, useRef, useEffect, useCallback } from "react";
import classNames from "classnames";
import moment, { Moment, isMoment } from "moment";
import CalendarPart from "../calendar/CalendarPart";
import { useDefaultValue } from "../form/controlled";
import { Input } from "../input";
import { TimeTable } from "./TimeTable";
import { Button } from "../button";
import { useTranslation } from "../i18n";
import { DropdownBox } from "../dropdown";
import { TimePickerProps } from "./TimeProps";
import {
  getHourMinuteSecond,
  genShowHourMinuteSecond,
  getDisabledHours,
  getDisabledSeconds,
  getDisabledMinutes,
} from "./util";
import { withStatics } from "../_util/with-statics";
import { TimeRangePicker } from "./TimeRangePicker";
import { useDefault } from "../_util/use-default";
import { Popover } from "../popover/Popover";
import { DatePickerTrigger } from "../datepicker/util";
import { useConfig } from "../_util/config-context";
 
const Keys = {
  "13": "enter",
  "27": "esc",
};
 
export const TimePicker = withStatics(
  function TimePicker(props: TimePickerProps) {
    const { classPrefix } = useConfig();
    const t = useTranslation(moment);
    const {
      value,
      onChange,
      format = "HH:mm:ss",
      placeholder = t.selectTime,
      disabled = false,
      hourStep = 1,
      minuteStep = 1,
      secondStep = 1,
      defaultOpen = false,
      open,
      onOpenChange = () => null,
      placement = "bottom-start",
      placementOffset = 5,
      closeOnScroll = true,
      escapeWithReference,
      overlayClassName,
      overlayStyle,
      className,
      style,
    } = useDefaultValue(props);
 
    const [curValue, setCurValue] = useState<Moment>(value);
    const [active, setActive] = useDefault(open, defaultOpen, onOpenChange);
    const [bubble, setBubble] = useState<string | null>(null);
 
    const inputRef = useRef<HTMLInputElement>(null);
    const getInputValue = useCallback(
      value => {
        return isMoment(value) ? value.locale(t.locale).format(format) : "";
      },
      [t.locale, format]
    );
 
    const [inputValue, setInputValue] = useState<string>(
      getInputValue(curValue)
    );
 
    useEffect(() => {
      setCurValue(value);
      setInputValue(getInputValue(value));
    }, [format, getInputValue, value]);
 
    function handleInputChange(content: string) {
      setInputValue(content);
 
      const value = moment(content, format, true);
 
      // 格式校验
      if (!value.isValid()) {
        setBubble(t.invalidFormat(format));
        return;
      }
 
      const { hour, minute, second } = getHourMinuteSecond(value);
      const { showHour, showMinute, showSecond } = genShowHourMinuteSecond(
        format
      );
 
      // 范围校验
      if (
        (showHour && getDisabledHours(props).includes(hour)) ||
        (showMinute && getDisabledMinutes(hour, props).includes(minute)) ||
        (showSecond && getDisabledSeconds(hour, minute, props).includes(second))
      ) {
        setBubble(t.invalidTime);
        return;
      }
 
      // 步长校验
      if (
        (showHour && hour % hourStep) ||
        (showMinute && minute % minuteStep) ||
        (showSecond && second % secondStep)
      ) {
        setBubble(t.invalidTime);
        return;
      }
 
      setCurValue(value);
      setBubble(null);
    }
 
    function handleKeyDown(event: React.KeyboardEvent) {
      switch (Keys[event.keyCode]) {
        case "enter":
          if (!bubble) {
            handleOk(event);
          }
          break;
        case "esc":
          handleClose();
          break;
      }
    }
 
    function handleSelectChange(value: Moment) {
      setBubble(null);
      setInputValue(getInputValue(value));
      setCurValue(value);
    }
 
    function handleOk(event: React.SyntheticEvent) {
      if (!curValue) {
        return;
      }
      onChange(curValue, { event });
      handleClose();
    }
 
    function handleOpen() {
      if (disabled) {
        return;
      }
      setActive(true);
    }
 
    function handleClose() {
      setInputValue(getInputValue(value));
      setActive(false);
      setBubble(null);
      inputRef.current.blur();
    }
 
    return (
      <Popover
        trigger={[
          DatePickerTrigger,
          { onOpen: handleOpen, onClose: handleClose },
        ]}
        visible={active}
        onVisibleChange={setActive}
        placement={placement}
        placementOffset={placementOffset}
        closeOnScroll={closeOnScroll}
        escapeWithReference={escapeWithReference}
        overlayClassName={overlayClassName}
        overlayStyle={overlayStyle}
        overlay={
          <DropdownBox>
            <CalendarPart.Panel timeMode>
              <CalendarPart.Body>
                <TimeTable
                  {...props}
                  value={curValue}
                  onChange={handleSelectChange}
                />
              </CalendarPart.Body>
              <CalendarPart.Footer
                right={
                  <Button
                    type="primary"
                    onClick={handleOk}
                    disabled={!curValue}
                  >
                    {t.okText}
                  </Button>
                }
              />
            </CalendarPart.Panel>
          </DropdownBox>
        }
      >
        <div
          className={classNames(`${classPrefix}-timepicker`, className)}
          style={style}
        >
          <div className={`${classPrefix}-timepicker__input`}>
            <Input
              ref={inputRef}
              maxLength={8}
              disabled={disabled}
              placeholder={placeholder}
              value={inputValue}
              onChange={handleInputChange}
              onKeyDown={handleKeyDown}
            />
          </div>
        </div>
      </Popover>
    );
  },
  {
    defaultLabelAlign: "middle",
    RangePicker: TimeRangePicker,
  }
);