All files / src/timepicker TimeRangePicker.tsx

56.1% Statements 23/41
67.44% Branches 29/43
46.15% Functions 6/13
57.5% Lines 23/40

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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279                                                                                                                                            1x       4x             6x     1x   6x 6x                                         2x           6x     6x             6x     6x 6x   9x 9x 5x           4x       6x       6x 3x 3x               3x                                                                                     6x             6x                                                                                                                                                
import React, { useState, useEffect, useRef, useCallback } from "react";
import classNames from "classnames";
import moment, { isMoment } from "moment";
import { ControlledProps, useDefaultValue } from "../form/controlled";
import CalendarPart from "../calendar/CalendarPart";
import { CalendarTable } from "../calendar/CalendarTable";
import { Combine, Omit } from "../_type";
import { Input } from "../input/Input";
import { useTranslation } from "../i18n";
import { getValidTimeValue } from "./util";
import { TimeDisabledProps, TimePickerProps } from "./TimeProps";
import { DropdownBox } from "../dropdown";
import { RangeDateType } from "../calendar/DateProps";
import { withStatics } from "../_util/with-statics";
import { CommonDatePickerProps } from "../datepicker";
import { Button } from "../button";
import { Popover } from "../popover/Popover";
import { DatePickerTrigger } from "../datepicker/util";
import { useDefault } from "../_util/use-default";
import { useConfig } from "../_util/config-context";
 
export interface TimeRangePickerProps
  extends Combine<
    Omit<CommonDatePickerProps, "header">,
    ControlledProps<RangeDateType>,
    Pick<TimePickerProps, "hourStep" | "minuteStep" | "secondStep">
  > {
  /**
   * 是否禁用选择值自动顺序校正,使得可以选择跨天类型的时间
   *
   * 如 22:00 ~ 00:00,23:00 ~ 01:00, 10:00 ~ 08:00 等
   *
   * @default false
   */
  disableAutoAdjust?: boolean;
 
  /**
   * 分隔符
   * @default ~
   */
  separator?: string;
 
  /**
   * placeholder
   * @default “选择时间”
   */
  placeholder?: string;
 
  /**
   * 日期展示格式
   * @default "HH:mm:ss"
   */
  format?: string;
 
  /**
   * 不可选的时间
   */
  disabledTime?: (
    dates: RangeDateType,
    partial: "start" | "end"
  ) => TimeDisabledProps;
 
  /**
   * 标题渲染
   * @default ["选择时间","选择时间"]
   * @version 2.0.14
   */
  caption?: [React.ReactNode, React.ReactNode];
}
 
const getDefaultMoment = (
  range: RangeDateType,
  disabledTime: TimeDisabledProps
) => {
  return getValidTimeValue(moment("00:00:00", "HH:mm:ss"), {
    range,
    ...disabledTime,
  });
};
 
function isValidRangeValue(value: any) {
  return Array.isArray(value) && isMoment(value[0]) && isMoment(value[1]);
}
 
export const TimeRangePicker = withStatics(
  function TimeRangePicker(props: TimeRangePickerProps) {
    const { classPrefix } = useConfig();
    const t = useTranslation(moment);
 
    const {
      className,
      style,
      value,
      onChange,
      disabled,
      separator = "~",
      format = "HH:mm:ss",
      placeholder = t.selectTime,
      defaultOpen = false,
      open,
      onOpenChange = () => null,
      placement = "bottom-start",
      placementOffset = 5,
      closeOnScroll = true,
      escapeWithReference,
      overlayClassName,
      overlayStyle,
      range,
      disabledTime = () => ({}),
      hourStep = 1,
      minuteStep = 1,
      secondStep = 1,
      disableAutoAdjust,
      caption = [t.selectTime, t.selectTime],
    } = useDefaultValue(props, [null, null]);
 
    // 当前选中时间
    const [curValue, setCurValue] = useState<RangeDateType>(
      isValidRangeValue(value)
        ? [value[0].clone(), value[1].clone()]
        : [null, null]
    );
 
    // 选择器是否展开
    const [active, setActive] = useDefault(open, defaultOpen, onOpenChange);
 
    // 输入框显示值
    const inputRef = useRef<HTMLInputElement>(null);
    const getInputValue = useCallback(
      (value: RangeDateType): string => {
        const [start, end] = value || [null, null];
        if (isMoment(start) && isMoment(end)) {
          return `${start
            .locale(t.locale)
            .format(format)} ${separator} ${end
            .locale(t.locale)
            .format(format)}`;
        }
        return "";
      },
      [format, separator, t.locale]
    );
    const [inputValue, setInputValue] = useState<string>(
      getInputValue(curValue)
    );
 
    useEffect(() => {
      const [start, end] = value;
      setCurValue([
        isMoment(start)
          ? start.clone()
          : getDefaultMoment(range, disabledTime(value, "start")),
        isMoment(end)
          ? end.clone()
          : getDefaultMoment(range, disabledTime(value, "end")),
      ]);
      setInputValue(getInputValue(value));
    }, [format, separator, value]); // eslint-disable-line react-hooks/exhaustive-deps
 
    function handleChange(
      value: RangeDateType
      // context: DateChangeContext
    ): void {
      const [start, end] = value;
      const fullValue: RangeDateType = [
        start || getDefaultMoment(range, disabledTime(value, "start")),
        end || getDefaultMoment(range, disabledTime(value, "end")),
      ];
      setCurValue(fullValue);
      // moment 更改后直接获取值(format)可能拿到是之前值
      setTimeout(() => setInputValue(getInputValue(fullValue)), 0);
    }
 
    function handleOk(event): void {
      let value = curValue;
      if (
        !disableAutoAdjust &&
        isValidRangeValue(curValue) &&
        curValue[0].isAfter(curValue[1])
      ) {
        value = [curValue[1], curValue[0]];
        setCurValue(value);
      }
      onChange(value, { event });
      handleClose();
    }
 
    function handleOpen(): void {
      if (disabled) {
        return;
      }
      setActive(true);
    }
 
    function handleClose(): void {
      setInputValue(getInputValue(value));
      setActive(false);
    }
 
    const timeProps = {
      hourStep,
      minuteStep,
      secondStep,
      format,
    };
 
    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 rangeMode timeMode>
              <CalendarPart.Body>
                <CalendarTable
                  {...props}
                  rangeType="start"
                  type="time"
                  showTime={{
                    ...timeProps,
                    caption: Array.isArray(caption) ? caption[0] : null,
                  }}
                  value={curValue}
                  onChange={handleChange}
                />
                <CalendarTable
                  {...props}
                  rangeType="end"
                  type="time"
                  showTime={{
                    ...timeProps,
                    caption: Array.isArray(caption) ? caption[1] : null,
                  }}
                  value={curValue}
                  onChange={handleChange}
                />
              </CalendarPart.Body>
              <CalendarPart.Footer
                right={
                  <Button type="primary" onClick={handleOk}>
                    {t.okText}
                  </Button>
                }
              />
            </CalendarPart.Panel>
          </DropdownBox>
        }
      >
        <div
          className={classNames(`${classPrefix}-timepicker`, className)}
          style={style}
        >
          <div className={`${classPrefix}-timepicker__input size-l`}>
            <Input
              ref={inputRef}
              maxLength={8}
              disabled={disabled}
              placeholder={placeholder}
              value={inputValue}
              onFocus={() => inputRef.current.blur()}
            />
          </div>
        </div>
      </Popover>
    );
  },
  { defaultLabelAlign: "middle" }
);