All files / src/datepicker RangePicker.tsx

34.48% Statements 40/116
46.3% Branches 50/108
30.77% Functions 8/26
34.51% Lines 39/113

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 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446                                                                                                          16x     63x     2x   18x 18x                                           18x   18x     18x           18x     18x         18x             18x     18x     18x 18x   27x 27x 6x           21x       18x       18x 9x         9x     18x 9x                                                                                                                                                                                                                           36x 12x 4x   8x   24x                                                   36x   36x         36x   28x 28x       28x       8x       8x                                                             18x                                                                                                                                                                                                                  
import React, { useState, useEffect, useRef, useCallback } from "react";
import classNames from "classnames";
import moment, { Moment, isMoment } from "moment";
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 { useTranslation } from "../i18n";
import { CommonDatePickerProps } from "./DatePickerProps";
import { getYearMonthDate, DatePickerTrigger } from "./util";
import { getHourMinuteSecond, getValidTimeValue } from "../timepicker/util";
import { TimeDisabledProps } from "../timepicker/TimeProps";
import { DropdownBox } from "../dropdown";
import {
  RangeDateType,
  showTimeType,
  CalendarTableType,
  DateChangeContext,
} from "../calendar/DateProps";
import { withStatics } from "../_util/with-statics";
import { useDefault } from "../_util/use-default";
import { Popover } from "../popover/Popover";
import { useConfig } from "../_util/config-context";
 
export interface RangePickerProps
  extends Combine<CommonDatePickerProps, ControlledProps<RangeDateType>> {
  /**
   * 分隔符
   * @default ~
   */
  separator?: string;
 
  /**
   * 是否开启时间选择,可传递对象设定时间选择配置
   */
  showTime?: showTimeType<RangeDateType>;
 
  /**
   * 不可选的日期
   */
  disabledDate?: (date: Moment, startDate?: Moment) => boolean;
 
  /**
   * 不可选的时间
   */
  disabledTime?: (
    dates: RangeDateType,
    partial: "start" | "end"
  ) => TimeDisabledProps;
}
 
const getFormat = showTime => (showTime ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD");
 
export function isValidRangeValue(value: any) {
  return Array.isArray(value) && isMoment(value[0]) && isMoment(value[1]);
}
 
export const RangePicker = withStatics(
  function RangePicker(props: RangePickerProps) {
    const t = useTranslation(moment);
    const { classPrefix } = useConfig();
    const {
      header,
      className,
      style,
      value,
      onChange,
      showTime,
      disabled,
      separator = "~",
      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, [null, null]);
 
    const format = _format || getFormat(showTime);
 
    // 当前面板类型
    const [type, setType] = useState<[CalendarTableType, CalendarTableType]>([
      "date",
      "date",
    ]);
 
    // 当前左/右面板展示时间
    const [curStartView, setStartCurView] = useState<Moment>(
      getDefaultViewMoment(0)
    );
    const [curEndView, setEndCurView] = useState<Moment>(
      getDefaultViewMoment(1)
    );
 
    // 当前选中日期
    const [curValue, setCurValue] = useState<RangeDateType>(
      isValidRangeValue(value)
        ? [value[0].clone(), value[1].clone()]
        : [null, null]
    );
 
    // 上次选中日期
    const preValidValueRef = useRef<RangeDateType>(value || [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(() => {
      setCurValue(
        isValidRangeValue(value)
          ? [value[0].clone(), value[1].clone()]
          : [null, null]
      );
      setInputValue(getInputValue(value));
    }, [format, separator, value, getInputValue]);
 
    useEffect(() => {
      preValidValueRef.current = value || [null, null];
    }, [value]);
 
    function handleChange(
      value: RangeDateType,
      context: DateChangeContext
    ): void {
      // 同步日期/时间
      if (showTime && isValidRangeValue(value)) {
        value = syncDate(value, context.type); // eslint-disable-line no-param-reassign
      }
 
      setCurValue(value);
      // moment 更改后直接获取值(format)可能拿到是之前值
      setTimeout(() => setInputValue(getInputValue(value)), 0);
 
      // 没有时间选择时没有二次确认选中
      if (!showTime && isValidRangeValue(value)) {
        onChange(value, context);
        handleClose();
      }
    }
 
    function handleOk(event): void {
      let value = curValue;
      if (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);
      setType(["date", "date"]);
    }
 
    function handleClose(): void {
      setInputValue(getInputValue(value));
      setActive(false);
    }
 
    /**
     * 同步日期/时间
     * 如果当前修改为日期,则同步上次时间并修正;
     * 如果当前修改为时间,则同步上次日期;
     */
    function syncDate(
      value: RangeDateType,
      type: CalendarTableType
    ): RangeDateType {
      const preValidValue = preValidValueRef.current;
      const { range, disabledTime = () => ({}) } = props;
 
      // 如果包含上次选择,则以上次选择为基准同步
      if (isValidRangeValue(preValidValue)) {
        if (type === "date") {
          const timeStart = getValidTimeValue(preValidValue[0], {
            range: getTimeRange(value[0], range),
            ...disabledTime(value, "start"),
          });
          const timeEnd = getValidTimeValue(preValidValue[1], {
            range: getTimeRange(value[1], range),
            ...disabledTime(value, "end"),
          });
          value[0].set(getHourMinuteSecond(timeStart));
          value[1].set(getHourMinuteSecond(timeEnd));
        }
        if (type === "time") {
          value[0].set(getYearMonthDate(preValidValue[0]));
          value[1].set(getYearMonthDate(preValidValue[1]));
        }
        // 如果是首次选择,则将当前时间进行修正
      } else if (type === "date") {
        // 合并 showTime.defaultValue
        if (
          typeof showTime === "object" &&
          isValidRangeValue(showTime.defaultValue)
        ) {
          const [start, end] = showTime.defaultValue;
          value[0].set(getHourMinuteSecond(start));
          value[1].set(getHourMinuteSecond(end));
        }
 
        const timeStart = getValidTimeValue(value[0], {
          range: getTimeRange(value[0], range),
          ...disabledTime(value, "start"),
        });
        const timeEnd = getValidTimeValue(value[1], {
          range: getTimeRange(value[1], range),
          ...disabledTime(value, "end"),
        });
 
        value[0].set(getHourMinuteSecond(timeStart));
        value[1].set(getHourMinuteSecond(timeEnd));
      }
 
      preValidValueRef.current = value;
      return value;
    }
 
    /**
     * 获取 ShowTime 参数
     * @param index 左/右面板 - 0/1
     */
    function getShowTime(index: number): showTimeType<Moment> {
      if (typeof showTime === "object") {
        if (Array.isArray(showTime.defaultValue)) {
          return { ...showTime, defaultValue: showTime.defaultValue[index] };
        }
        return showTime as showTimeType<Moment>;
      }
      return !!showTime;
    }
 
    /**
     * 获取左右面板 range
     */
    function getRange(range): [RangeDateType, RangeDateType] {
      const [rangeMin, rangeMax] = range || [null, null];
      const endPreEnd = moment(curEndView)
        .subtract(1, "month")
        .endOf("month");
      const startNxtStart = moment(curStartView)
        .add(1, "month")
        .startOf("month");
 
      return [
        [rangeMin, endPreEnd.isAfter(rangeMax) ? rangeMax : endPreEnd],
        [startNxtStart.isBefore(rangeMin) ? rangeMin : startNxtStart, rangeMax],
      ];
    }
 
    /**
     * 获取面板默认展示时间
     * @param index 左/右面板 - 0/1
     */
    function getDefaultViewMoment(index: number): Moment {
      const showTime = getShowTime(index);
      const time =
        showTime && typeof showTime === "object"
          ? showTime.defaultValue
          : undefined;
 
      // 没有初始值
      if (!isValidRangeValue(value)) {
        let m;
        Eif (!time) {
          m = moment();
        } else {
          m = moment(getHourMinuteSecond(time as Moment));
        }
        return index === 0 ? moment(m).subtract(1, "month") : m;
      }
 
      // 初始值在同个月
      Iif (value[0].isSame(value[1], "month")) {
        return index === 0 ? moment(value[1]).subtract(1, "month") : value[1];
      }
 
      return value[index];
    }
 
    /**
     * 是否改变当前视图时间
     * 连续两月情况下,点击中间交错日期不改变当前视图时间
     * @param from 当前视图变更事件来源
     * @param nextDate 要变更到的时间
     * @param type 当前视图类型
     */
    function shouldCurViewChange(
      from: string,
      nextDate: Moment,
      type: "start" | "end" = "start"
    ): boolean {
      if (from !== "outside-date") {
        return true;
      }
      const diffMonths = (start, end) => {
        const years = end.year() - start.year();
        return end.month() - start.month() + years * 12;
      };
      if (diffMonths(curStartView, curEndView) === 1) {
        if (type === "start") {
          return diffMonths(curStartView, nextDate) !== 1;
        }
        return diffMonths(nextDate, curEndView) !== 1;
      }
      return true;
    }
 
    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={type[0] === "time"}>
              {!!header && <CalendarPart.Header>{header}</CalendarPart.Header>}
              <TimeSupportWrapper
                {...restProps}
                showTime={showTime}
                value={curValue}
                onChange={handleChange}
                onOk={handleOk}
                type={type}
                onTypeChange={types =>
                  setType(types as [CalendarTableType, CalendarTableType])
                }
              >
                {({ type, onTypeChange, range, ...props }) => {
                  const [startRange, EndRange] = getRange(range);
                  return (
                    <>
                      <CalendarTable
                        {...props}
                        rangeType="start"
                        range={startRange}
                        type={type[0]}
                        onTypeChange={t => onTypeChange([t, type[1]])}
                        showTime={getShowTime(0)}
                        curViewMoment={curStartView}
                        onCurViewMomentChange={(date, { from } = {}) => {
                          if (!shouldCurViewChange(from, date)) {
                            return;
                          }
                          if (!curEndView.isAfter(date, "month")) {
                            setEndCurView(moment(date).add(1, "month"));
                          }
                          setStartCurView(date);
                        }}
                        dateRangeInRangePicker={range || [null, null]}
                      />
                      <CalendarTable
                        {...props}
                        rangeType="end"
                        range={EndRange}
                        type={type[1]}
                        onTypeChange={t => onTypeChange([type[0], t])}
                        showTime={getShowTime(1)}
                        curViewMoment={curEndView}
                        onCurViewMomentChange={(date, { from } = {}) => {
                          if (!shouldCurViewChange(from, date, "end")) {
                            return;
                          }
                          if (!curStartView.isBefore(date, "month")) {
                            setStartCurView(moment(date).subtract(1, "month"));
                          }
                          setEndCurView(date);
                        }}
                        dateRangeInRangePicker={range || [null, null]}
                      />
                    </>
                  );
                }}
              </TimeSupportWrapper>
            </CalendarPart.Panel>
          </DropdownBox>
        }
      >
        <div
          className={classNames(
            `${classPrefix}-date${showTime ? "time" : ""}picker`,
            className
          )}
          style={style}
        >
          <div
            className={`${classPrefix}-date${
              showTime ? "time" : ""
            }picker__input`}
          >
            <Input
              ref={inputRef}
              disabled={disabled}
              placeholder={placeholder}
              value={inputValue}
              onFocus={() => inputRef.current.blur()}
            />
          </div>
        </div>
      </Popover>
    );
  },
  { defaultLabelAlign: "middle" }
);