All files / src/calendar/tables DateTable.tsx

62.22% Statements 28/45
46.67% Branches 14/30
50% Functions 10/20
62.22% Lines 28/45

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                                                                                                                                                3x 3x   3x 3x     3x     3x         3x     3x   21x   3x   3x 3x 12x   84x   12x 12x     3x       3x               3x             3x       105x 105x     105x                         105x     3x                                                                                         21x           15x   105x                                            
import React from "react";
import moment, { Moment, isMoment } from "moment";
import Table, { CellStatus } from "./BaseTable";
import { useTranslation } from "../../i18n";
import {
  RangeDateType,
  CalendarTableType,
  DateChangeContext,
} from "../DateProps";
import { useConfig } from "../../_util/config-context";
 
export interface DateTableProps {
  /**
   * 当前展示日期
   */
  current: Moment;
 
  /**
   * 当前选中的日期
   */
  value: Moment;
 
  /**
   * 允许选择的时间范围限制
   */
  range?: RangeDateType;
 
  /**
   * 可选的日期范围
   */
  disabledDate?: (date: Moment) => boolean;
 
  /**
   * Cell 渲染状态
   */
  cellStatus?: (date: Moment) => CellStatus;
 
  /**
   * 选中回调
   */
  onSelect?: (value: Moment, context: DateChangeContext) => void;
 
  /**
   * type 变更回调
   */
  onTypeChange?: (type: CalendarTableType) => void;
 
  /**
   * 当前展示日期变更回调
   */
  onCurrentChange?: (
    current: Moment,
    context?: { from?: "jumper" | "outside-date" }
  ) => void;
 
  /**
   * 范围选择中日期的范围
   * 解决范围选择中相邻月间交错日期不可点的问题
   */
  dateRangeInRangePicker?: RangeDateType;
}
 
export function DateTable({
  current,
  onCurrentChange = () => null,
  range,
  disabledDate,
  onSelect = () => null,
  onTypeChange = () => null,
  cellStatus = () => CellStatus.Common,
  dateRangeInRangePicker,
}: DateTableProps) {
  const t = useTranslation();
  const { classPrefix } = useConfig();
 
  const year = current.year();
  const month = current.month();
 
  function genTable(): Moment[][] {
    const table = [];
 
    // 本月第一天
    const first = moment({
      year,
      month,
      date: 1,
    });
    const firstDay = first.day();
 
    // 第一周
    const firstWeek = Array<Moment>(7)
      .fill(null)
      .map((_, i) => first.clone().add(i - firstDay, "d"));
 
    table.push(firstWeek);
 
    let nextWeekFirst = firstWeek[6].clone().add(1, "d");
    while (nextWeekFirst.month() === month) {
      const week = Array<Moment>(7)
        .fill(null)
        .map((_, i) => nextWeekFirst.clone().add(i, "d")); // eslint-disable-line no-loop-func
 
      table.push(week);
      nextWeekFirst = week[6].clone().add(1, "d");
    }
 
    return table;
  }
 
  function renderYear() {
    return (
      <a className="op-item" onClick={() => onTypeChange("year")}>
        {current.format(t.yearFormat)}
      </a>
    );
  }
 
  function renderMonth() {
    return (
      <a className="op-item" onClick={() => onTypeChange("month")}>
        {moment.monthsShort(month)}
      </a>
    );
  }
 
  const [rangeMin, rangeMax] = range || [null, null];
 
  function isValidDate(date) {
    // 非 RangePicker
    Eif (typeof dateRangeInRangePicker === "undefined") {
      Iif (isMoment(rangeMin) && rangeMin.isAfter(date, "day")) {
        return false;
      }
      Iif (isMoment(rangeMax) && rangeMax.isBefore(date, "day")) {
        return false;
      }
    } else {
      // RangePicker
      const [aRangeMin, aRangeMax] = dateRangeInRangePicker;
      if (isMoment(aRangeMin) && aRangeMin.isAfter(date, "day")) {
        return false;
      }
      if (isMoment(aRangeMax) && aRangeMax.isBefore(date, "day")) {
        return false;
      }
    }
    return disabledDate(date);
  }
 
  return (
    <Table
      caption={
        t.monthBeforeYear ? (
          <>
            {renderMonth()}
            {renderYear()}
          </>
        ) : (
          <>
            {renderYear()}
            {renderMonth()}
          </>
        )
      }
      jumperOptions={{
        onNext: () =>
          onCurrentChange(moment(current).add(1, "month"), { from: "jumper" }),
        onPrev: () =>
          onCurrentChange(moment(current).subtract(1, "month"), {
            from: "jumper",
          }),
        onCurrent: () => onCurrentChange(moment(), { from: "jumper" }),
        isCurrent: current.isSame(moment(), "month"),
        nextDisabled:
          isMoment(rangeMax) &&
          rangeMax.isBefore(
            moment({ year, month, date: 1 }).add(1, "month"),
            "day"
          ),
        prevDisabled:
          isMoment(rangeMin) &&
          rangeMin.isAfter(
            moment({ year, month, date: 1 }).subtract(1, "day"),
            "day"
          ),
        nextTitle: t.nextMonth,
        prevTitle: t.prevMonth,
        curTitle: t.curMonth,
      }}
    >
      {/* 周 */}
      <div className={`${classPrefix}-calendar__header-group`}>
        <div className={`${classPrefix}-calendar__row`}>
          {moment.weekdaysMin().map(name => (
            <Table.Cell key={name} name={name} />
          ))}
        </div>
      </div>
 
      {genTable().map((week, i) => (
        <Table.Row key={`${month}-${i}`}>
          {week.map((date, j) => (
            <Table.Cell
              key={`${month}-${i}-${j}`}
              name={date.date()}
              value={date}
              onSelect={onSelect}
              status={cellStatus(date)}
              isNow={date.isSame(moment(), "day")}
              outside={date.month() !== month}
              disabled={!isValidDate(date)}
              onOutsideSelect={date =>
                onCurrentChange(
                  moment({ year: date.year(), month: date.month() }),
                  { from: "outside-date" }
                )
              }
            />
          ))}
        </Table.Row>
      ))}
    </Table>
  );
}