All files / src/datepicker DatePicker.tsx

40.98% Statements 25/61
46.67% Branches 21/45
37.5% Functions 6/16
40.68% Lines 24/59

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                                                                                          4x   2x   5x 5x                                         5x   5x     5x     5x         5x     5x     5x     5x 5x   10x       5x       5x 5x 5x     5x 5x                                                                                                                                                               2x     2x 2x         5x                                                                                                                            
import React, { useState, useEffect, useRef, useCallback } from "react";
import moment, { Moment, isMoment } from "moment";
import classNames from "classnames";
import { useTranslation } from "../i18n";
import { ControlledProps, useDefaultValue } from "../form/controlled";
import CalendarPart from "../calendar/CalendarPart";
import { CalendarTable, getTimeRange } from "../calendar/CalendarTable";
import { Combine } from "../_type";
import { TimeSupportWrapper } from "./TimeSupportWrapper";
import { Input } from "../input/Input";
import { RangePicker } from "./RangePicker";
import { TimeDisabledProps } from "../timepicker/TimeProps";
import { getHourMinuteSecond, getValidTimeValue } from "../timepicker/util";
import { DropdownBox } from "../dropdown";
import { MonthPicker } from "./MonthPicker";
import {
  showTimeType,
  CalendarTableType,
  DateChangeContext,
} from "../calendar/DateProps";
import { CommonDatePickerProps } from "./DatePickerProps";
import { getYearMonthDate, DatePickerTrigger } from "./util";
import { withStatics } from "../_util/with-statics";
import { Popover } from "../popover";
import { useDefault } from "../_util/use-default";
import { useConfig } from "../_util/config-context";
 
export interface DatePickerProps
  extends Combine<CommonDatePickerProps, ControlledProps<Moment>> {
  /**
   * 是否开启时间选择
   */
  showTime?: showTimeType<Moment>;
 
  /**
   * 不可选的日期
   */
  disabledDate?: (date: Moment) => boolean;
 
  /**
   * 不可选的时间
   */
  disabledTime?: (date: Moment) => TimeDisabledProps;
}
 
const getFormat = showTime => (showTime ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD");
 
export const DatePicker = withStatics(
  function DatePicker(props: DatePickerProps) {
    const t = useTranslation(moment);
    const { classPrefix } = useConfig();
    const {
      header,
      className,
      style,
      showTime,
      value,
      onChange,
      disabled,
      format: _format,
      placeholder = showTime ? t.selectTime : t.selectDate,
      defaultOpen = false,
      open,
      onOpenChange = () => null,
      placement = "bottom-start",
      placementOffset = 5,
      closeOnScroll = true,
      escapeWithReference,
      overlayClassName,
      overlayStyle,
      ...restProps
    } = useDefaultValue(props);
 
    const format = _format || getFormat(showTime);
 
    // 当前面板类型
    const [type, setType] = useState<CalendarTableType>("date");
 
    // 当前面板展示时间
    const [curViewMoment, setCurViewMoment] = useState<Moment>(
      isMoment(value) ? value : getDefaultViewMoment()
    );
 
    // 当前选中日期
    const [curValue, setCurValue] = useState<Moment>(value);
 
    // 上次选中日期
    const preValidValueRef = useRef<Moment>(value);
 
    // 选择器是否展开
    const [active, setActive] = useDefault(open, defaultOpen, onOpenChange);
 
    // 输入框显示值
    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, value, getInputValue]);
 
    useEffect(() => {
      preValidValueRef.current = value;
    }, [value]);
 
    function handleChange(value: Moment, context: DateChangeContext): void {
      // 同步日期/时间
      if (showTime && isMoment(value)) {
        value = syncDate(value, context.type); // eslint-disable-line no-param-reassign
      }
 
      setCurValue(value);
      setInputValue(getInputValue(value));
 
      // 没有时间选择时没有二次确认选中
      if (!showTime) {
        onChange(value, context);
        handleClose();
      }
    }
 
    function handleOk(event): void {
      onChange(curValue, { event });
      handleClose();
    }
 
    function handleOpen(): void {
      if (disabled) {
        return;
      }
      setActive(true);
      setType("date");
    }
 
    function handleClose(): void {
      setInputValue(getInputValue(value));
      setActive(false);
    }
 
    /**
     * 同步日期/时间
     * 如果当前修改为日期,则同步上次时间并修正;
     * 如果当前修改为时间,则同步上次日期;
     */
    function syncDate(value: Moment, type: CalendarTableType): Moment {
      const preValidValue = preValidValueRef.current;
      const { range, disabledTime = () => ({}) } = props;
 
      // 如果包含上次选择,则以上次选择为基准同步
      if (isMoment(preValidValue)) {
        if (type === "date") {
          const time = getValidTimeValue(preValidValue, {
            range: getTimeRange(value, range),
            ...disabledTime(value),
          });
          value.set(getHourMinuteSecond(time));
        }
        if (type === "time") {
          value.set(getYearMonthDate(preValidValue));
        }
        // 如果是首次选择,则将当前时间进行修正
      } else if (type === "date") {
        // 合并 showTime.defaultValue
        if (typeof showTime === "object" && isMoment(showTime.defaultValue)) {
          value.set(getHourMinuteSecond(showTime.defaultValue));
        }
        const time = getValidTimeValue(value, {
          range: getTimeRange(value, range),
          ...disabledTime(value),
        });
        value.set(getHourMinuteSecond(time));
      }
 
      preValidValueRef.current = value;
      return value;
    }
 
    /**
     * 获取面板默认展示时间
     */
    function getDefaultViewMoment(): Moment {
      const time =
        showTime && typeof showTime === "object"
          ? showTime.defaultValue
          : undefined;
      Eif (!time) {
        return moment();
      }
      return moment(getHourMinuteSecond(time));
    }
 
    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={type === "time"}>
              {!!header && <CalendarPart.Header>{header}</CalendarPart.Header>}
              <TimeSupportWrapper
                {...restProps}
                showTime={showTime}
                value={curValue}
                onChange={handleChange}
                onOk={handleOk}
                type={type}
                onTypeChange={type => setType(type as CalendarTableType)}
              >
                {props => (
                  <CalendarTable
                    {...props}
                    curViewMoment={curViewMoment}
                    onCurViewMomentChange={setCurViewMoment}
                  />
                )}
              </TimeSupportWrapper>
            </CalendarPart.Panel>
          </DropdownBox>
        }
      >
        <div
          className={classNames(`${classPrefix}-datepicker`, className)}
          style={style}
        >
          <div className={`${classPrefix}-datepicker__input`}>
            <Input
              ref={inputRef}
              disabled={disabled}
              placeholder={placeholder}
              value={inputValue}
              onFocus={() => inputRef.current.blur()}
            />
          </div>
        </div>
      </Popover>
    );
  },
  {
    RangePicker,
    MonthPicker,
    defaultLabelAlign: "middle",
  }
);