"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var React = _interopRequireWildcard(require("react"));

var moment = _interopRequireWildcard(require("moment"));

var _reactLifecyclesCompat = require("react-lifecycles-compat");

var _RangeCalendar = _interopRequireDefault(require("rc-calendar/lib/RangeCalendar"));

var _Picker = _interopRequireDefault(require("rc-calendar/lib/Picker"));

var _classnames = _interopRequireDefault(require("classnames"));

var _shallowequal = _interopRequireDefault(require("shallowequal"));

var _icon = _interopRequireDefault(require("../icon"));

var _tag = _interopRequireDefault(require("../tag"));

var _configProvider = require("../config-provider");

var _warning = _interopRequireDefault(require("../_util/warning"));

var _interopDefault = _interopRequireDefault(require("../_util/interopDefault"));

var _utils = require("./utils");

var _InputIcon = _interopRequireDefault(require("./InputIcon"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function getShowDateFromValue(value, mode) {
  var _value = _slicedToArray(value, 2),
      start = _value[0],
      end = _value[1]; // value could be an empty array, then we should not reset showDate


  if (!start && !end) {
    return;
  }

  if (mode && mode[0] === 'month') {
    return [start, end];
  }

  var newEnd = end && end.isSame(start, 'month') ? end.clone().add(1, 'month') : end;
  return [start, newEnd];
}

function pickerValueAdapter(value) {
  if (!value) {
    return;
  }

  if (Array.isArray(value)) {
    return value;
  }

  return [value, value.clone().add(1, 'month')];
}

function isEmptyArray(arr) {
  if (Array.isArray(arr)) {
    return arr.length === 0 || arr.every(function (i) {
      return !i;
    });
  }

  return false;
}

function fixLocale(value, localeCode) {
  if (!localeCode) {
    return;
  }

  if (!value || value.length === 0) {
    return;
  }

  var _value2 = _slicedToArray(value, 2),
      start = _value2[0],
      end = _value2[1];

  if (start) {
    start.locale(localeCode);
  }

  if (end) {
    end.locale(localeCode);
  }
}

var RangePicker = /*#__PURE__*/function (_React$Component) {
  _inherits(RangePicker, _React$Component);

  var _super = _createSuper(RangePicker);

  function RangePicker(props) {
    var _this;

    _classCallCheck(this, RangePicker);

    _this = _super.call(this, props);

    _this.savePicker = function (node) {
      _this.picker = node;
    };

    _this.clearSelection = function (e) {
      e.preventDefault();
      e.stopPropagation();

      _this.setState({
        value: []
      });

      _this.handleChange([]);
    };

    _this.clearHoverValue = function () {
      return _this.setState({
        hoverValue: []
      });
    };

    _this.handleChange = function (value) {
      var _assertThisInitialize = _assertThisInitialized(_this),
          props = _assertThisInitialize.props;

      if (!('value' in props)) {
        _this.setState(function (_ref) {
          var showDate = _ref.showDate;
          return {
            value: value,
            showDate: getShowDateFromValue(value) || showDate
          };
        });
      }

      if (value[0] && value[1] && value[0].diff(value[1]) > 0) {
        value[1] = undefined;
      }

      var _value3 = _slicedToArray(value, 2),
          start = _value3[0],
          end = _value3[1];

      if (typeof props.onChange === 'function') {
        props.onChange(value, [(0, _utils.formatDate)(start, props.format), (0, _utils.formatDate)(end, props.format)]);
      }
    };

    _this.handleOpenChange = function (open) {
      if (!('open' in _this.props)) {
        _this.setState({
          open: open
        });
      }

      if (open === false) {
        _this.clearHoverValue();
      }

      var onOpenChange = _this.props.onOpenChange;

      if (onOpenChange) {
        onOpenChange(open);
      }
    };

    _this.handleShowDateChange = function (showDate) {
      return _this.setState({
        showDate: showDate
      });
    };

    _this.handleHoverChange = function (hoverValue) {
      return _this.setState({
        hoverValue: hoverValue
      });
    };

    _this.handleRangeMouseLeave = function () {
      if (_this.state.open) {
        _this.clearHoverValue();
      }
    };

    _this.handleCalendarInputSelect = function (value) {
      var _value4 = _slicedToArray(value, 1),
          start = _value4[0];

      if (!start) {
        return;
      }

      _this.setState(function (_ref2) {
        var showDate = _ref2.showDate;
        return {
          value: value,
          showDate: getShowDateFromValue(value) || showDate
        };
      });
    };

    _this.handleRangeClick = function (value) {
      if (typeof value === 'function') {
        value = value();
      }

      _this.setValue(value, true);

      var _this$props = _this.props,
          onOk = _this$props.onOk,
          onOpenChange = _this$props.onOpenChange;

      if (onOk) {
        onOk(value);
      }

      if (onOpenChange) {
        onOpenChange(false);
      }
    };

    _this.renderFooter = function () {
      var _this$props2 = _this.props,
          ranges = _this$props2.ranges,
          renderExtraFooter = _this$props2.renderExtraFooter;

      var _assertThisInitialize2 = _assertThisInitialized(_this),
          prefixCls = _assertThisInitialize2.prefixCls,
          tagPrefixCls = _assertThisInitialize2.tagPrefixCls;

      if (!ranges && !renderExtraFooter) {
        return null;
      }

      var customFooter = renderExtraFooter ? /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-footer-extra"),
        key: "extra"
      }, renderExtraFooter()) : null;
      var operations = ranges && Object.keys(ranges).map(function (range) {
        var value = ranges[range];
        var hoverValue = typeof value === 'function' ? value.call(_assertThisInitialized(_this)) : value;
        return /*#__PURE__*/React.createElement(_tag["default"], {
          key: range,
          prefixCls: tagPrefixCls,
          color: "blue",
          onClick: function onClick() {
            return _this.handleRangeClick(value);
          },
          onMouseEnter: function onMouseEnter() {
            return _this.setState({
              hoverValue: hoverValue
            });
          },
          onMouseLeave: _this.handleRangeMouseLeave
        }, range);
      });
      var rangeNode = operations && operations.length > 0 ? /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-footer-extra ").concat(prefixCls, "-range-quick-selector"),
        key: "range"
      }, operations) : null;
      return [rangeNode, customFooter];
    };

    _this.renderRangePicker = function (_ref3) {
      var _classNames;

      var getPrefixCls = _ref3.getPrefixCls;

      var _assertThisInitialize3 = _assertThisInitialized(_this),
          state = _assertThisInitialize3.state,
          props = _assertThisInitialize3.props;

      var value = state.value,
          showDate = state.showDate,
          hoverValue = state.hoverValue,
          open = state.open;
      var customizePrefixCls = props.prefixCls,
          customizeTagPrefixCls = props.tagPrefixCls,
          popupStyle = props.popupStyle,
          style = props.style,
          disabledDate = props.disabledDate,
          disabledTime = props.disabledTime,
          showTime = props.showTime,
          showToday = props.showToday,
          ranges = props.ranges,
          onOk = props.onOk,
          locale = props.locale,
          localeCode = props.localeCode,
          format = props.format,
          dateRender = props.dateRender,
          onCalendarChange = props.onCalendarChange,
          suffixIcon = props.suffixIcon,
          separator = props.separator;
      var prefixCls = getPrefixCls('calendar', customizePrefixCls);
      var tagPrefixCls = getPrefixCls('tag', customizeTagPrefixCls); // To support old version react.
      // Have to add prefixCls on the instance.
      // https://github.com/facebook/react/issues/12397

      _this.prefixCls = prefixCls;
      _this.tagPrefixCls = tagPrefixCls;
      fixLocale(value, localeCode);
      fixLocale(showDate, localeCode);
      (0, _warning["default"])(!('onOK' in props), 'RangePicker', 'It should be `RangePicker[onOk]`, instead of `onOK`!');
      var calendarClassName = (0, _classnames["default"])((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-time"), showTime), _defineProperty(_classNames, "".concat(prefixCls, "-range-with-ranges"), ranges), _classNames)); // 需要选择时间时，点击 ok 时才触发 onChange

      var pickerChangeHandler = {
        onChange: _this.handleChange
      };
      var calendarProps = {
        onOk: _this.handleChange
      };

      if (props.timePicker) {
        pickerChangeHandler.onChange = function (changedValue) {
          return _this.handleChange(changedValue);
        };
      } else {
        calendarProps = {};
      }

      if ('mode' in props) {
        calendarProps.mode = props.mode;
      }

      var startPlaceholder = Array.isArray(props.placeholder) ? props.placeholder[0] : locale.lang.rangePlaceholder[0];
      var endPlaceholder = Array.isArray(props.placeholder) ? props.placeholder[1] : locale.lang.rangePlaceholder[1];
      var calendar = /*#__PURE__*/React.createElement(_RangeCalendar["default"], _extends({}, calendarProps, {
        seperator: separator,
        onChange: onCalendarChange,
        format: format,
        prefixCls: prefixCls,
        className: calendarClassName,
        renderFooter: _this.renderFooter,
        timePicker: props.timePicker,
        disabledDate: disabledDate,
        disabledTime: disabledTime,
        dateInputPlaceholder: [startPlaceholder, endPlaceholder],
        locale: locale.lang,
        onOk: onOk,
        dateRender: dateRender,
        value: showDate,
        onValueChange: _this.handleShowDateChange,
        hoverValue: hoverValue,
        onHoverChange: _this.handleHoverChange,
        onPanelChange: props.onPanelChange,
        showToday: showToday,
        onInputSelect: _this.handleCalendarInputSelect
      })); // default width for showTime

      var pickerStyle = {};

      if (props.showTime) {
        pickerStyle.width = style && style.width || 350;
      }

      var _value5 = _slicedToArray(value, 2),
          startValue = _value5[0],
          endValue = _value5[1];

      var clearIcon = !props.disabled && props.allowClear && value && (startValue || endValue) ? /*#__PURE__*/React.createElement(_icon["default"], {
        type: "close-circle",
        className: "".concat(prefixCls, "-picker-clear"),
        onClick: _this.clearSelection,
        theme: "filled"
      }) : null;
      var inputIcon = /*#__PURE__*/React.createElement(_InputIcon["default"], {
        suffixIcon: suffixIcon,
        prefixCls: prefixCls
      });

      var input = function input(_ref4) {
        var inputValue = _ref4.value;

        var _inputValue = _slicedToArray(inputValue, 2),
            start = _inputValue[0],
            end = _inputValue[1];

        return /*#__PURE__*/React.createElement("span", {
          className: props.pickerInputClass
        }, /*#__PURE__*/React.createElement("input", {
          disabled: props.disabled,
          readOnly: true,
          value: (0, _utils.formatDate)(start, props.format),
          placeholder: startPlaceholder,
          className: "".concat(prefixCls, "-range-picker-input"),
          tabIndex: -1
        }), /*#__PURE__*/React.createElement("span", {
          className: "".concat(prefixCls, "-range-picker-separator")
        }, " ", separator, " "), /*#__PURE__*/React.createElement("input", {
          disabled: props.disabled,
          readOnly: true,
          value: (0, _utils.formatDate)(end, props.format),
          placeholder: endPlaceholder,
          className: "".concat(prefixCls, "-range-picker-input"),
          tabIndex: -1
        }), clearIcon, inputIcon);
      };

      return /*#__PURE__*/React.createElement("span", {
        ref: _this.savePicker,
        id: typeof props.id === 'number' ? props.id.toString() : props.id,
        className: (0, _classnames["default"])(props.className, props.pickerClass),
        style: _extends(_extends({}, style), pickerStyle),
        tabIndex: props.disabled ? -1 : 0,
        onFocus: props.onFocus,
        onBlur: props.onBlur,
        onMouseEnter: props.onMouseEnter,
        onMouseLeave: props.onMouseLeave
      }, /*#__PURE__*/React.createElement(_Picker["default"], _extends({}, props, pickerChangeHandler, {
        calendar: calendar,
        value: value,
        open: open,
        onOpenChange: _this.handleOpenChange,
        prefixCls: "".concat(prefixCls, "-picker-container"),
        style: popupStyle
      }), input));
    };

    var value = props.value || props.defaultValue || [];

    var _value6 = _slicedToArray(value, 2),
        start = _value6[0],
        end = _value6[1];

    if (start && !(0, _interopDefault["default"])(moment).isMoment(start) || end && !(0, _interopDefault["default"])(moment).isMoment(end)) {
      throw new Error('The value/defaultValue of RangePicker must be a moment object array after `antd@2.0`, ' + 'see: https://u.ant.design/date-picker-value');
    }

    var pickerValue = !value || isEmptyArray(value) ? props.defaultPickerValue : value;
    _this.state = {
      value: value,
      showDate: pickerValueAdapter(pickerValue || (0, _interopDefault["default"])(moment)()),
      open: props.open,
      hoverValue: []
    };
    return _this;
  }

  _createClass(RangePicker, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(_, prevState) {
      if (!('open' in this.props) && prevState.open && !this.state.open) {
        this.focus();
      }
    }
  }, {
    key: "setValue",
    value: function setValue(value, hidePanel) {
      this.handleChange(value);

      if ((hidePanel || !this.props.showTime) && !('open' in this.props)) {
        this.setState({
          open: false
        });
      }
    }
  }, {
    key: "focus",
    value: function focus() {
      this.picker.focus();
    }
  }, {
    key: "blur",
    value: function blur() {
      this.picker.blur();
    }
  }, {
    key: "render",
    value: function render() {
      return /*#__PURE__*/React.createElement(_configProvider.ConfigConsumer, null, this.renderRangePicker);
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      var state = null;

      if ('value' in nextProps) {
        var value = nextProps.value || [];
        state = {
          value: value
        };

        if (!(0, _shallowequal["default"])(nextProps.value, prevState.value)) {
          state = _extends(_extends({}, state), {
            showDate: getShowDateFromValue(value, nextProps.mode) || prevState.showDate
          });
        }
      }

      if ('open' in nextProps && prevState.open !== nextProps.open) {
        state = _extends(_extends({}, state), {
          open: nextProps.open
        });
      }

      return state;
    }
  }]);

  return RangePicker;
}(React.Component);

RangePicker.defaultProps = {
  allowClear: true,
  showToday: false,
  separator: '~'
};
(0, _reactLifecyclesCompat.polyfill)(RangePicker);
var _default = RangePicker;
exports["default"] = _default;